-
Notifications
You must be signed in to change notification settings - Fork 130
/
RuleSubset.java
456 lines (390 loc) · 16 KB
/
RuleSubset.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
* Copyright 2014 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.windup.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.jboss.windup.config.metadata.RuleMetadata;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.model.performance.RulePhaseExecutionStatisticsModel;
import org.jboss.windup.graph.model.performance.RuleProviderExecutionStatisticsModel;
import org.jboss.windup.util.exception.WindupException;
import org.ocpsoft.common.util.Assert;
import org.ocpsoft.logging.Logger;
import org.ocpsoft.rewrite.bind.Binding;
import org.ocpsoft.rewrite.bind.Evaluation;
import org.ocpsoft.rewrite.config.CompositeOperation;
import org.ocpsoft.rewrite.config.Condition;
import org.ocpsoft.rewrite.config.ConditionVisit;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.DefaultOperationBuilder;
import org.ocpsoft.rewrite.config.Operation;
import org.ocpsoft.rewrite.config.OperationVisit;
import org.ocpsoft.rewrite.config.ParameterizedCallback;
import org.ocpsoft.rewrite.config.ParameterizedConditionVisitor;
import org.ocpsoft.rewrite.config.ParameterizedOperationVisitor;
import org.ocpsoft.rewrite.config.Rule;
import org.ocpsoft.rewrite.config.RuleBuilder;
import org.ocpsoft.rewrite.context.Context;
import org.ocpsoft.rewrite.context.ContextBase;
import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.context.RewriteState;
import org.ocpsoft.rewrite.event.Rewrite;
import org.ocpsoft.rewrite.param.ConfigurableParameter;
import org.ocpsoft.rewrite.param.Constraint;
import org.ocpsoft.rewrite.param.DefaultParameter;
import org.ocpsoft.rewrite.param.DefaultParameterStore;
import org.ocpsoft.rewrite.param.Parameter;
import org.ocpsoft.rewrite.param.ParameterStore;
import org.ocpsoft.rewrite.param.ParameterValueStore;
import org.ocpsoft.rewrite.param.Parameterized;
import org.ocpsoft.rewrite.param.Transposition;
import org.ocpsoft.rewrite.util.ParameterUtils;
import org.ocpsoft.rewrite.util.Visitor;
/**
* An {@link Operation} that allows for conditional evaluation of nested {@link Rule} sets.
*
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public class RuleSubset extends DefaultOperationBuilder implements CompositeOperation, Parameterized
{
private static Logger log = Logger.getLogger(RuleSubset.class);
/**
* Used for tracking the time taken by the rules within each RuleProvider
*/
private final IdentityHashMap<WindupRuleProvider, RuleProviderExecutionStatisticsModel> timeTakenByProvider = new IdentityHashMap<>();
/**
* Used for tracking the time taken by each phase of execution
*/
private final Map<RulePhase, RulePhaseExecutionStatisticsModel> timeTakenByPhase = new HashMap<>();
private final Configuration config;
private RuleSubset(Configuration config)
{
Assert.notNull(config, "Configuration must not be null.");
this.config = config;
}
public static RuleSubset evaluate(Configuration config)
{
return new RuleSubset(config);
}
/**
* Logs the time taken by this rule, and attaches this to the total for the RuleProvider
*/
private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)
{
WindupRuleProvider ruleProvider = (WindupRuleProvider) context.get(RuleMetadata.RULE_PROVIDER);
if (ruleProvider == null)
return;
if (!timeTakenByProvider.containsKey(ruleProvider))
{
RuleProviderExecutionStatisticsModel model = graphContext
.getService(RuleProviderExecutionStatisticsModel.class).create();
model.setRuleIndex(ruleIndex);
model.setRuleProviderID(ruleProvider.getID());
model.setTimeTaken(timeTaken);
timeTakenByProvider.put(ruleProvider, model);
}
else
{
RuleProviderExecutionStatisticsModel model = timeTakenByProvider.get(ruleProvider);
int prevTimeTaken = model.getTimeTaken();
model.setTimeTaken(prevTimeTaken + timeTaken);
}
logTimeTakenByPhase(graphContext, ruleProvider.getPhase(), timeTaken);
}
/**
* Logs the time taken by this rule and adds this to the total time taken for this phase
*/
private void logTimeTakenByPhase(GraphContext graphContext, RulePhase phase, int timeTaken)
{
if (!timeTakenByPhase.containsKey(phase))
{
RulePhaseExecutionStatisticsModel model = graphContext.getService(RulePhaseExecutionStatisticsModel.class)
.create();
model.setRulePhase(phase == null ? "Implicit" : phase.toString());
model.setTimeTaken(timeTaken);
timeTakenByPhase.put(phase, model);
}
else
{
RulePhaseExecutionStatisticsModel model = timeTakenByPhase.get(phase);
int prevTimeTaken = model.getTimeTaken();
model.setTimeTaken(prevTimeTaken + timeTaken);
}
}
/*
* Executors
*/
@Override
public void perform(Rewrite rewrite, EvaluationContext context)
{
if (!(rewrite instanceof GraphRewrite))
throw new IllegalArgumentException("Rewrite must be an instanceof GraphRewrite");
/*
* Highly optimized loop - for performance reasons. Think before you change this!
*/
GraphRewrite event = (GraphRewrite) rewrite;
List<Rule> rules = config.getRules();
final EvaluationContextImpl subContext = new EvaluationContextImpl();
for (int i = 0; i < rules.size(); i++)
{
Rule rule = rules.get(i);
Context ruleContext = rule instanceof Context ? (Context) rule : null;
long ruleTimeStarted = System.currentTimeMillis();
try
{
subContext.clear();
subContext.put(ParameterStore.class, context.get(ParameterStore.class));
ParameterValueStore values = (ParameterValueStore) context.get(ParameterValueStore.class);
subContext.put(ParameterValueStore.class, values);
subContext.setState(RewriteState.EVALUATING);
subContext.put(Rule.class, rule);
event.selectionPush();
try
{
if (!rule.evaluate(event, subContext))
continue;
if (!handleBindings(event, subContext, values))
continue;
subContext.setState(RewriteState.PERFORMING);
log.debug("Rule [" + rule + "] matched and will be performed.");
List<Operation> preOperations = subContext.getPreOperations();
for (Operation preOperation : preOperations)
{
preOperation.perform(event, subContext);
}
if (event.getFlow().isHandled())
break;
rule.perform(event, subContext);
if (event.getFlow().isHandled())
break;
List<Operation> postOperations = subContext.getPostOperations();
for (Operation postOperation : postOperations)
{
postOperation.perform(event, subContext);
}
if (event.getFlow().isHandled())
break;
}
finally
{
boolean autocommit = true;
if (ruleContext != null && ruleContext.containsKey(RuleMetadata.AUTO_COMMIT))
{
autocommit = (Boolean) ruleContext.get(RuleMetadata.AUTO_COMMIT);
}
if (autocommit)
{
event.getGraphContext().getGraph().getBaseGraph().commit();
}
event.selectionPop();
long ruleTimeCompleted = System.currentTimeMillis();
if (ruleContext != null)
{
int timeTaken = (int) (ruleTimeCompleted - ruleTimeStarted);
logTimeTakenByRuleProvider(event.getGraphContext(), ruleContext, i, timeTaken);
}
}
}
catch (RuntimeException e)
{
String message = "Error encountered while evaluating rule: " + rule;
if (ruleContext != null)
{
Object origin = ruleContext.get(RuleMetadata.ORIGIN);
if (origin != null)
message += " from: " + origin;
Object location = ruleContext.get(org.ocpsoft.rewrite.config.RuleMetadata.PROVIDER_LOCATION);
if (location != null)
message += " defined in: " + location;
}
throw new WindupException(message, e);
}
}
}
private boolean handleBindings(final Rewrite event, final EvaluationContextImpl context,
ParameterValueStore values)
{
boolean result = true;
ParameterStore store = (ParameterStore) context.get(ParameterStore.class);
for (Entry<String, Parameter<?>> entry : store)
{
Parameter<?> parameter = entry.getValue();
String value = values.retrieve(parameter);
if (!ParameterUtils.enqueueSubmission(event, context, parameter, value))
{
result = false;
break;
}
}
return result;
}
/*
* Getters
*/
@Override
public List<Operation> getOperations()
{
return Collections.emptyList();
}
private static class EvaluationContextImpl extends ContextBase implements EvaluationContext
{
private final List<Operation> preOperations = new ArrayList<>();
private final List<Operation> postOperations = new ArrayList<>();
private RewriteState state;
public EvaluationContextImpl()
{
put(ParameterStore.class, new DefaultParameterStore());
}
@Override
public void addPreOperation(final Operation operation)
{
this.preOperations.add(operation);
}
@Override
public void addPostOperation(final Operation operation)
{
this.preOperations.add(operation);
}
/**
* Get an immutable view of the added pre-{@link Operation} instances.
*/
public List<Operation> getPreOperations()
{
return Collections.unmodifiableList(preOperations);
}
/**
* Get an immutable view of the added post-{@link Operation} instances.
*/
public List<Operation> getPostOperations()
{
return Collections.unmodifiableList(postOperations);
}
@Override
public String toString()
{
return "EvaluationContextImpl [preOperations=" + preOperations + ", postOperations=" + postOperations + "]";
}
/**
* Clears the state of this context so that it may be reused, saving instantiation cost during rule iteration.
*/
public void clear()
{
this.postOperations.clear();
this.postOperations.clear();
}
@Override
public RewriteState getState()
{
return state;
}
public void setState(RewriteState state)
{
this.state = state;
}
}
@Override
public Set<String> getRequiredParameterNames()
{
return Collections.emptySet();
}
@Override
public void setParameterStore(final ParameterStore parent)
{
for (int i = 0; i < config.getRules().size(); i++)
{
Rule rule = config.getRules().get(i);
if (!(rule instanceof RuleBuilder))
continue;
ParameterizedCallback callback = new ParameterizedCallbackImpl(rule, parent);
Visitor<Condition> conditionVisitor = new ParameterizedConditionVisitor(callback);
new ConditionVisit(rule).accept(conditionVisitor);
Visitor<Operation> operationVisitor = new ParameterizedOperationVisitor(callback);
new OperationVisit(rule).accept(operationVisitor);
}
}
/**
*
*/
private static class ParameterizedCallbackImpl implements ParameterizedCallback
{
private final Rule rule;
private final ParameterStore parent;
public ParameterizedCallbackImpl(Rule rule, ParameterStore parent)
{
this.rule = rule;
this.parent = parent;
}
@Override
public void call(Parameterized parameterized)
{
Set<String> names = parameterized.getRequiredParameterNames();
if (!(rule instanceof RuleBuilder))
return;
ParameterStore store = ((RuleBuilder) rule).getParameterStore();
for (Entry<String, Parameter<?>> entry : parent)
{
String name = entry.getKey();
Parameter<?> parentParam = entry.getValue();
if (!store.contains(name))
{
store.get(name, parentParam);
continue;
}
Parameter<?> parameter = store.get(name);
for (Binding binding : parameter.getBindings())
{
if (!parentParam.getBindings().contains(binding))
throwRedefinitionError(rule, name);
}
for (Constraint<String> constraint : parameter.getConstraints())
{
if (!parentParam.getConstraints().contains(constraint))
throwRedefinitionError(rule, name);
}
for (Transposition<String> transposition : parameter.getTranspositions())
{
if (!parentParam.getTranspositions().contains(transposition))
throwRedefinitionError(rule, name);
}
if (parentParam.getConverter() != null
&& !parentParam.getConverter().equals(parameter.getConverter()))
throwRedefinitionError(rule, name);
if (parentParam.getValidator() != null
&& !parentParam.getValidator().equals(parameter.getValidator()))
throwRedefinitionError(rule, name);
}
for (String name : names)
{
Parameter<?> parameter = store.get(name, new DefaultParameter(name));
if (parameter instanceof ConfigurableParameter<?>)
((ConfigurableParameter<?>) parameter).bindsTo(Evaluation.property(name));
}
parameterized.setParameterStore(store);
}
private void throwRedefinitionError(Rule rule, String name)
{
throw new IllegalStateException("Subset cannot re-configure parameter [" + name
+ "] that was configured in parent Configuration. Re-definition was attempted at ["
+ rule + "] ");
}
}
}