01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.compass.core.converter.dynamic;
18:
19: import java.io.StringWriter;
20:
21: import org.apache.velocity.VelocityContext;
22: import org.apache.velocity.app.Velocity;
23: import org.compass.core.converter.ConversionException;
24: import org.compass.core.mapping.ResourcePropertyMapping;
25:
26: /**
27: * @author kimchy
28: */
29: public class VelocityDynamicConverter extends AbstractDynamicConverter {
30:
31: private String vtl;
32:
33: public void setExpression(String expression)
34: throws ConversionException {
35: this .vtl = expression;
36: try {
37: Velocity.init();
38: } catch (Exception e) {
39: throw new ConversionException(
40: "Failed to initialize velocity", e);
41: }
42: }
43:
44: protected Object evaluate(Object o,
45: ResourcePropertyMapping resourcePropertyMapping)
46: throws ConversionException {
47: VelocityContext ctx = new VelocityContext();
48: ctx.put(DATA_CONTEXT_KEY, o);
49:
50: StringWriter sw = new StringWriter();
51: try {
52: Velocity.evaluate(ctx, sw, "", vtl);
53: } catch (Exception e) {
54: throw new ConversionException("Failed to evaluate [" + o
55: + "] with expression [" + vtl + "]", e);
56: }
57: return sw.toString();
58: }
59: }
|