1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.enforcer.rules;
20
21 import javax.inject.Inject;
22 import javax.inject.Named;
23
24 import java.util.Objects;
25
26 import bsh.EvalError;
27 import bsh.Interpreter;
28 import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
29 import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
30 import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
31
32
33
34
35
36
37 @Named("evaluateBeanshell")
38 public final class EvaluateBeanshell extends AbstractStandardEnforcerRule {
39
40
41 private final Interpreter interpreter = new Interpreter();
42
43
44
45 private String condition;
46
47 private final ExpressionEvaluator evaluator;
48
49 @Inject
50 public EvaluateBeanshell(ExpressionEvaluator evaluator) {
51 this.evaluator = Objects.requireNonNull(evaluator);
52 }
53
54 public void setCondition(String condition) {
55 this.condition = condition;
56 }
57
58 public String getCondition() {
59 return condition;
60 }
61
62 @Override
63 public void execute() throws EnforcerRuleException {
64
65 try {
66 getLog().debug("Echo condition : " + condition);
67
68 String script = (String) evaluator.evaluate(condition);
69 getLog().debug("Echo script : " + script);
70 if (!evaluateCondition(script)) {
71 String message = getMessage();
72 if (message == null || message.isEmpty()) {
73 message = "The expression \"" + condition + "\" is not true.";
74 }
75 throw new EnforcerRuleException(message);
76 }
77 } catch (ExpressionEvaluationException e) {
78 throw new EnforcerRuleException("Unable to evaluate an expression '" + condition + "'", e);
79 }
80 }
81
82
83
84
85
86
87
88
89 private boolean evaluateCondition(String script) throws EnforcerRuleException {
90 Boolean evaluation;
91 try {
92 evaluation = (Boolean) interpreter.eval(script);
93 getLog().debug("Echo evaluating : " + evaluation);
94 } catch (EvalError ex) {
95 throw new EnforcerRuleException("Couldn't evaluate condition: " + script, ex);
96 }
97 return evaluation;
98 }
99
100 @Override
101 public String toString() {
102 return String.format("EvaluateBeanshell[message=%s, condition=%s]", getMessage(), condition);
103 }
104 }