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