-
Notifications
You must be signed in to change notification settings - Fork 130
/
JavaClass.java
401 lines (351 loc) · 14.9 KB
/
JavaClass.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package org.jboss.windup.rules.apps.java.condition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.jboss.forge.furnace.util.Assert;
import org.jboss.windup.ast.java.data.TypeReferenceLocation;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.Variables;
import org.jboss.windup.config.condition.EvaluationStrategy;
import org.jboss.windup.config.condition.GraphCondition;
import org.jboss.windup.config.condition.NoopEvaluationStrategy;
import org.jboss.windup.config.parameters.FrameContext;
import org.jboss.windup.config.parameters.FrameCreationContext;
import org.jboss.windup.config.parameters.ParameterizedGraphCondition;
import org.jboss.windup.config.query.Query;
import org.jboss.windup.config.query.QueryBuilderFrom;
import org.jboss.windup.config.query.QueryGremlinCriterion;
import org.jboss.windup.config.query.QueryPropertyComparisonType;
import org.jboss.windup.graph.model.WindupVertexFrame;
import org.jboss.windup.graph.model.resource.FileModel;
import org.jboss.windup.rules.apps.java.model.AbstractJavaSourceModel;
import org.jboss.windup.rules.apps.java.model.JavaClassFileModel;
import org.jboss.windup.rules.apps.java.model.JavaClassModel;
import org.jboss.windup.rules.apps.java.model.JavaSourceFileModel;
import org.jboss.windup.rules.apps.java.scan.ast.JavaTypeReferenceModel;
import org.jboss.windup.rules.apps.java.scan.ast.TypeInterestFactory;
import org.jboss.windup.rules.files.model.FileReferenceModel;
import org.jboss.windup.util.ExecutionStatistics;
import org.ocpsoft.rewrite.config.Condition;
import org.ocpsoft.rewrite.config.ConditionBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.param.DefaultParameterStore;
import org.ocpsoft.rewrite.param.ParameterStore;
import org.ocpsoft.rewrite.param.ParameterizedPatternResult;
import org.ocpsoft.rewrite.param.RegexParameterizedPatternParser;
import org.ocpsoft.rewrite.util.Maps;
import com.thinkaurelius.titan.core.attribute.Text;
import com.tinkerpop.blueprints.Predicate;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.frames.structures.FramedVertexIterable;
import com.tinkerpop.gremlin.java.GremlinPipeline;
/**
* {@link GraphCondition} that matches Vertices in the graph based upon the provided parameters.
*/
public class JavaClass extends ParameterizedGraphCondition implements JavaClassBuilder, JavaClassBuilderAt,
JavaClassBuilderInFile, JavaClassBuilderLineMatch
{
private static final AtomicInteger numberCreated = new AtomicInteger(0);
private final String uniqueID;
private List<TypeReferenceLocation> locations = Collections.emptyList();
private RegexParameterizedPatternParser referencePattern;
private RegexParameterizedPatternParser lineMatchPattern;
private RegexParameterizedPatternParser typeFilterPattern;
private JavaClass(String referencePattern)
{
this.referencePattern = new RegexParameterizedPatternParser(referencePattern);
this.uniqueID = numberCreated.incrementAndGet() + "_JavaClass";
}
/**
* Create a new {@link JavaClass} {@link Condition} based upon the provided Java regular expression.
*/
public static JavaClassBuilder references(String regex)
{
return new JavaClass(regex);
}
/**
* Create a new {@link JavaClass} {@link Condition} based upon the provided Java regular expression.
*/
public static JavaClassBuilderReferences from(String inputVarName)
{
return new JavaClassBuilderReferences(inputVarName);
}
/**
* Specify a Java type pattern pattern for which this condition should match.
*/
public JavaClassBuilderInFile inType(String typeFilterPattern)
{
this.typeFilterPattern = new RegexParameterizedPatternParser(typeFilterPattern);
return this;
}
public JavaClassBuilderLineMatch matchesSource(String lineMatchRegex)
{
this.lineMatchPattern = new RegexParameterizedPatternParser(lineMatchRegex);
return this;
}
/**
* Only match if the TypeReference is at the specified location within the file.
*/
@Override
public JavaClassBuilderAt at(TypeReferenceLocation... locations)
{
if (locations != null)
this.locations = Arrays.asList(locations);
return this;
}
/**
* Optionally specify the variable name to use for the output of this condition
*/
@Override
public ConditionBuilder as(String variable)
{
Assert.notNull(variable, "Variable name must not be null.");
this.setOutputVariablesName(variable);
return this;
}
@Override
@SuppressWarnings("unchecked")
protected boolean evaluateAndPopulateValueStores(GraphRewrite event, EvaluationContext context,
final FrameCreationContext frameCreationContext)
{
return evaluate(event, context, new EvaluationStrategy()
{
private LinkedHashMap<String, List<WindupVertexFrame>> variables;
@Override
@SuppressWarnings("rawtypes")
public void modelMatched()
{
this.variables = new LinkedHashMap<>();
frameCreationContext.beginNew((Map) variables);
}
@Override
public void modelSubmitted(WindupVertexFrame model)
{
Maps.addListValue(this.variables, getVarname(), model);
}
@Override
public void modelSubmissionRejected()
{
frameCreationContext.rollback();
}
});
}
@Override
protected boolean evaluateWithValueStore(GraphRewrite event, EvaluationContext context,
final FrameContext frameContext)
{
boolean result = evaluate(event, context, new NoopEvaluationStrategy());
if (result == false)
frameContext.reject();
return result;
}
private String titanify(Pattern pattern)
{
return pattern.pattern().replace("\\Q", "\"").replace("\\E", "\"").replace("?:", "");
}
private boolean evaluate(GraphRewrite event, EvaluationContext context, EvaluationStrategy evaluationStrategy)
{
try
{
ExecutionStatistics.get().begin("JavaClass.evaluate");
final ParameterStore store = DefaultParameterStore.getInstance(context);
final Pattern compiledPattern = referencePattern.getCompiledPattern(store);
/*
* Only set in the case of a query with no "from" variable.
*/
String initialQueryID = null;
QueryBuilderFrom query;
if (!StringUtils.isBlank(getInputVariablesName()))
{
query = Query.from(getInputVariablesName());
query.withProperty(JavaTypeReferenceModel.RESOLVED_SOURCE_SNIPPIT, QueryPropertyComparisonType.REGEX, titanify(compiledPattern));
}
else
{
initialQueryID = "iqi." + UUID.randomUUID().toString();
GremlinPipeline<Vertex, Vertex> resolvedTextSearch = new GremlinPipeline<>(event.getGraphContext().getGraph());
resolvedTextSearch.V();
resolvedTextSearch.has(JavaTypeReferenceModel.RESOLVED_SOURCE_SNIPPIT, Text.REGEX, titanify(compiledPattern));
// resolvedTextSearch.has(WindupVertexFrame.TYPE_PROP, Text.CONTAINS, JavaTypeReferenceModel.TYPE);
if (!resolvedTextSearch.iterator().hasNext())
return false;
Variables.instance(event).setVariable(
initialQueryID,
new FramedVertexIterable<>(event.getGraphContext().getFramed(), resolvedTextSearch,
JavaTypeReferenceModel.class));
query = Query.from(initialQueryID);
}
if (lineMatchPattern != null)
{
final Pattern compiledLineMatchPattern = lineMatchPattern.getCompiledPattern(store);
query.withProperty(JavaTypeReferenceModel.SOURCE_SNIPPIT, QueryPropertyComparisonType.REGEX, compiledLineMatchPattern.pattern());
}
String uuid = UUID.randomUUID().toString();
query.as(uuid);
if (typeFilterPattern != null)
{
Pattern compiledTypeFilterPattern = typeFilterPattern.getCompiledPattern(store);
query.piped(new TypeFilterCriterion(compiledTypeFilterPattern));
}
if (!locations.isEmpty())
query.withProperty(JavaTypeReferenceModel.REFERENCE_TYPE, locations);
List<WindupVertexFrame> results = new ArrayList<>();
if (query.evaluate(event, context))
{
Iterable<? extends WindupVertexFrame> frames = Variables.instance(event).findVariable(uuid);
for (WindupVertexFrame frame : frames)
{
FileModel fileModel = ((FileReferenceModel) frame).getFile();
Iterable<JavaClassModel> javaClasses = null;
if (fileModel instanceof AbstractJavaSourceModel)
javaClasses = ((AbstractJavaSourceModel) fileModel).getJavaClasses();
else if (fileModel instanceof JavaClassFileModel)
javaClasses = Arrays.asList(((JavaClassFileModel) fileModel).getJavaClass());
for (JavaClassModel javaClassModel : javaClasses)
{
if (typeFilterPattern == null || typeFilterPattern.parse(javaClassModel
.getQualifiedName()).matches())
{
JavaTypeReferenceModel model = (JavaTypeReferenceModel) frame;
ParameterizedPatternResult referenceResult = referencePattern.parse(model
.getResolvedSourceSnippit());
if (referenceResult.matches())
{
evaluationStrategy.modelMatched();
if (referenceResult.submit(event, context)
&& (typeFilterPattern == null || typeFilterPattern.parse(javaClassModel
.getQualifiedName()).submit(event, context)))
{
results.add(model);
evaluationStrategy.modelSubmitted(model);
}
else
{
evaluationStrategy.modelSubmissionRejected();
}
}
}
}
}
Variables.instance(event).removeVariable(uuid);
if (initialQueryID != null)
Variables.instance(event).removeVariable(initialQueryID);
setResults(event, getVarname(), results);
return !results.isEmpty();
}
return false;
}
finally
{
ExecutionStatistics.get().end("JavaClass.evaluate");
}
}
private final class TypeFilterCriterion implements QueryGremlinCriterion
{
private final Pattern compiledTypeFilterPattern;
private TypeFilterCriterion(Pattern compiledTypeFilterPattern)
{
this.compiledTypeFilterPattern = compiledTypeFilterPattern;
}
@Override
public void query(GraphRewrite event, GremlinPipeline<Vertex, Vertex> pipeline)
{
Predicate regexPredicate = new Predicate()
{
@Override
public boolean evaluate(Object first, Object second)
{
return ((String) first).matches((String) second);
}
};
pipeline.as("result")
.out(FileReferenceModel.FILE_MODEL)
.out(JavaSourceFileModel.JAVA_CLASS_MODEL)
.has(JavaClassModel.QUALIFIED_NAME,
regexPredicate,
compiledTypeFilterPattern.pattern())
.back("result");
}
}
@Override
public Set<String> getRequiredParameterNames()
{
Set<String> result = new HashSet<>(referencePattern.getRequiredParameterNames());
if (typeFilterPattern != null)
result.addAll(typeFilterPattern.getRequiredParameterNames());
if (lineMatchPattern != null)
result.addAll(lineMatchPattern.getRequiredParameterNames());
return result;
}
@Override
public void setParameterStore(ParameterStore store)
{
if (locations != null && !locations.isEmpty())
{
TypeInterestFactory.registerInterest(
this.uniqueID,
referencePattern.getCompiledPattern(store).pattern(),
referencePattern.getPattern(),
locations);
}
else
{
TypeInterestFactory.registerInterest(
this.uniqueID,
referencePattern.getCompiledPattern(store).pattern(),
referencePattern.getPattern());
}
referencePattern.setParameterStore(store);
if (typeFilterPattern != null)
typeFilterPattern.setParameterStore(store);
}
@Override
public String getVarname()
{
return getOutputVariablesName();
}
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("JavaClass");
if (typeFilterPattern != null)
{
builder.append(".inType(" + typeFilterPattern + ")");
}
if (referencePattern != null)
{
builder.append(".references(" + referencePattern + ")");
}
if (!locations.isEmpty())
{
builder.append(".at(" + locations + ")");
}
builder.append(".as(" + getVarname() + ")");
return builder.toString();
}
public RegexParameterizedPatternParser getReferences()
{
return referencePattern;
}
public RegexParameterizedPatternParser getMatchesSource()
{
return lineMatchPattern;
}
public List<TypeReferenceLocation> getLocations()
{
return locations;
}
public RegexParameterizedPatternParser getTypeFilterRegex()
{
return typeFilterPattern;
}
}