1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.kew.rule;
17
18 import org.kuali.rice.kew.api.WorkflowRuntimeException;
19 import org.kuali.rice.kew.engine.RouteContext;
20 import org.kuali.rice.kew.exception.WorkflowException;
21 import org.kuali.rice.kew.service.KEWServiceLocator;
22
23 import javax.script.ScriptEngine;
24 import javax.script.ScriptEngineManager;
25 import javax.script.ScriptException;
26
27
28
29
30
31
32
33
34
35 public class BSFRuleExpression implements RuleExpression {
36 public RuleExpressionResult evaluate(Rule rule, RouteContext context) throws WorkflowException {
37 RuleBaseValues ruleDefinition = rule.getDefinition();
38 String type = ruleDefinition.getRuleExpressionDef().getType();
39 String lang = parseLang(type, "groovy");
40 String expression = ruleDefinition.getRuleExpressionDef().getExpression();
41 RuleExpressionResult result;
42 ScriptEngineManager factory = new ScriptEngineManager();
43 ScriptEngine engine = factory.getEngineByName(lang);
44 try {
45 declareBeans(engine, rule, context);
46 result = (RuleExpressionResult) engine.eval(expression);
47 } catch (ScriptException e) {
48 throw new WorkflowException("Error evaluating " + type + " expression: '" + expression + "'", e);
49 }
50 if (result == null) {
51 return new RuleExpressionResult(rule, false);
52 } else {
53 return result;
54 }
55 }
56
57
58
59
60
61
62
63 protected String parseLang(String type, String deflt) {
64 int colon = type.indexOf(':');
65 if (colon > -1) {
66 return type.substring(colon + 1);
67 } else {
68 return deflt;
69 }
70 }
71
72
73
74
75
76
77
78
79 protected void declareBeans(ScriptEngine engine, Rule rule, RouteContext context) throws ScriptException {
80 engine.put("rule", rule);
81 engine.put("routeContext", context);
82 engine.put("workflow", new WorkflowRuleAPI(context));
83 }
84
85
86
87
88
89
90
91 protected static final class WorkflowRuleAPI {
92 private final RouteContext context;
93 WorkflowRuleAPI(RouteContext context) {
94 this.context = context;
95 }
96
97
98
99
100
101
102 public RuleExpressionResult invokeRule(String name) throws WorkflowException {
103 RuleBaseValues rbv = KEWServiceLocator.getRuleService().getRuleByName(name);
104 if (rbv == null) throw new WorkflowRuntimeException("Could not find rule named \"" + name + "\"");
105 Rule r = new RuleImpl(rbv);
106 return r.evaluate(r, context);
107 }
108 }
109 }