01: package org.compass.core.converter.dynamic;
02:
03: import groovy.lang.Binding;
04: import groovy.lang.GroovyShell;
05: import groovy.lang.Script;
06: import org.compass.core.converter.ConversionException;
07: import org.compass.core.mapping.ResourcePropertyMapping;
08:
09: /**
10: * @author kimchy
11: */
12: public class GroovyDynamicConverter extends AbstractDynamicConverter {
13:
14: private String expression;
15:
16: private ThreadSafeExpressionEvaluator expressionEvaluator;
17:
18: public void setExpression(final String expression)
19: throws ConversionException {
20: this .expression = expression;
21: this .expressionEvaluator = new ThreadSafeExpressionEvaluator(
22: 10, 20, new ExpressionEvaluatorFactory() {
23: public ExpressionEvaluator create()
24: throws ConversionException {
25: return new GroovyExpressionEvaluator();
26: }
27: });
28: }
29:
30: protected Object evaluate(Object o,
31: ResourcePropertyMapping resourcePropertyMapping)
32: throws ConversionException {
33: return expressionEvaluator.evaluate(o, resourcePropertyMapping);
34: }
35:
36: public class GroovyExpressionEvaluator implements
37: ExpressionEvaluator {
38:
39: private Script script;
40:
41: public GroovyExpressionEvaluator() {
42: this .script = new GroovyShell().parse(expression);
43: }
44:
45: public Object evaluate(Object o,
46: ResourcePropertyMapping resourcePropertyMapping)
47: throws ConversionException {
48: Binding binding = new Binding();
49: binding.setVariable(DATA_CONTEXT_KEY, o);
50: // thread safe so we are ok
51: script.setBinding(binding);
52: try {
53: return script.run();
54: } catch (Exception e) {
55: throw new ConversionException("Failed to evaluate ["
56: + o + "] with expression [" + expression + "]",
57: e);
58: }
59: }
60: }
61: }
|