1 package com.stateofflow.eclipse.metrics.calculators;
2
3 import org.eclipse.jdt.core.ICompilationUnit;
4 import org.eclipse.jdt.core.IType;
5 import org.eclipse.jdt.core.JavaModelException;
6 import org.eclipse.jdt.core.dom.AST;
7 import org.eclipse.jdt.core.dom.ASTParser;
8 import org.eclipse.jdt.core.dom.CompilationUnit;
9 import org.eclipse.jdt.core.dom.MethodDeclaration;
10
11 import com.stateofflow.eclipse.metrics.location.MetricLocationFactory;
12 import com.stateofflow.eclipse.metrics.metric.MetricId;
13 import com.stateofflow.eclipse.metrics.type.NonNullType;
14
15 public final class MeasurementContext {
16 private final ICompilationUnit unparsed;
17 private final MetricLocationFactory locations;
18 private final CalculatorListener listener;
19 private CompilationUnit parsed;
20
21 public MeasurementContext(final ICompilationUnit unparsed, final CalculatorListener listener) {
22 this.unparsed = unparsed;
23 this.listener = listener;
24
25 locations = new MetricLocationFactory();
26 }
27
28 public CompilationUnit getParsedCompilationUnit() {
29 if (parsed == null) {
30 parse();
31 }
32 return parsed;
33 }
34
35 public String getSource() throws JavaModelException {
36 return unparsed.getSource();
37 }
38
39 public ICompilationUnit getUnparsedCompilationUnit() {
40 return unparsed;
41 }
42
43 public void noteMethodValue(final MetricId metricId, final int value, final NonNullType typeNode, final MethodDeclaration methodNode) {
44 listener.noteMethodValue(metricId, locations.findOrCreate(typeNode, methodNode, getParsedCompilationUnit()), value);
45 }
46
47 public void noteTypeValue(final MetricId metricId, final int value, final IType type) throws JavaModelException {
48 listener.noteTypeValue(metricId, locations.findOrCreate(type, getParsedCompilationUnit()), value);
49 }
50
51 public void noteTypeValue(final MetricId metricId, final int value, final NonNullType typeNode) {
52 listener.noteTypeValue(metricId, locations.findOrCreate(typeNode, getParsedCompilationUnit()), value);
53 }
54
55 private void parse() {
56 final ASTParser c = ASTParser.newParser(AST.JLS3);
57 c.setSource(unparsed);
58 c.setResolveBindings(true);
59 parsed = (CompilationUnit) c.createAST(null);
60 }
61 }
62