01: package org.drools.decisiontable.parser;
02:
03: /*
04: * Copyright 2005 JBoss Inc
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License");
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */
18: import java.io.IOException;
19: import java.util.ArrayList;
20: import java.util.HashMap;
21: import java.util.Iterator;
22: import java.util.List;
23: import java.util.Map;
24:
25: import org.mvel.MVELTemplateRegistry;
26: import org.mvel.TemplateInterpreter;
27: import org.mvel.TemplateRegistry;
28:
29: /**
30: * @author <a href="mailto:stevearoonie@gmail.com">Steven Williams</a>
31: *
32: * Generate the rules for a decision table row from a rule template.
33: */
34: public class DefaultGenerator implements Generator {
35:
36: private Map ruleTemplates;
37:
38: private TemplateRegistry registry = new MVELTemplateRegistry();
39:
40: private List rules = new ArrayList();
41:
42: public DefaultGenerator(final Map t) {
43: ruleTemplates = t;
44: }
45:
46: /*
47: * (non-Javadoc)
48: *
49: * @see org.drools.decisiontable.parser.Generator#generate(java.lang.String,
50: * org.drools.decisiontable.parser.Row)
51: */
52: public void generate(String templateName, Row row) {
53: try {
54: String content = getTemplate(templateName);
55: Map vars = new HashMap();
56: vars.put("row", row);
57:
58: for (Iterator it = row.getCells().iterator(); it.hasNext();) {
59: Cell cell = (Cell) it.next();
60: cell.addValue(vars);
61: }
62: String drl = (String) TemplateInterpreter.parse(content,
63: null, vars, this .registry);
64: rules.add(drl);
65: } catch (Exception e) {
66: throw new RuntimeException(e);
67: }
68: }
69:
70: private String getTemplate(String templateName) throws IOException {
71: String contents = (String) registry.getTemplate(templateName);
72: if (contents == null) {
73: RuleTemplate template = (RuleTemplate) ruleTemplates
74: .get(templateName);
75: contents = template.getContents();
76: registry.registerTemplate(templateName, contents);
77: }
78: return contents;
79: }
80:
81: /*
82: * (non-Javadoc)
83: *
84: * @see org.drools.decisiontable.parser.Generator#getDrl()
85: */
86: public String getDrl() {
87: StringBuffer sb = new StringBuffer();
88: for (Iterator it = rules.iterator(); it.hasNext();) {
89: String rule = (String) it.next();
90: sb.append(rule).append("\n");
91: }
92: return sb.toString();
93: }
94:
95: }
|