01: /*
02: * Created on Aug 13, 2004
03: */
04: package net.sourceforge.orbroker;
05:
06: import java.io.IOException;
07: import java.io.InputStream;
08: import java.io.StringWriter;
09: import java.util.Properties;
10: import java.util.logging.Level;
11:
12: import net.sourceforge.orbroker.velocity.LogWrapper;
13: import net.sourceforge.orbroker.velocity.StringResourceLoader;
14:
15: import org.apache.velocity.Template;
16: import org.apache.velocity.VelocityContext;
17: import org.apache.velocity.app.VelocityEngine;
18: import org.apache.velocity.context.Context;
19:
20: /**
21: * @author Nils Kilden-Pedersen
22: */
23: final class VelocityStatement extends DynamicStatement {
24:
25: private static final VelocityEngine ENGINE;
26: static {
27: ENGINE = new VelocityEngine();
28: Properties props = new Properties();
29: try {
30: InputStream velocityConfig = ENGINE.getClass()
31: .getResourceAsStream("/velocity.properties");
32: if (velocityConfig != null) {
33: props.load(velocityConfig);
34: } else {
35: Broker.log(Level.CONFIG,
36: "Unable to find \"velocity.properties\" file");
37: }
38: } catch (IOException e) {
39: Broker.log(Level.WARNING, e.toString());
40: }
41: props.setProperty("runtime.log.logsystem.class",
42: LogWrapper.class.getName());
43: props.setProperty("resource.loader", "string");
44: props.setProperty("string.resource.loader.class",
45: StringResourceLoader.class.getName());
46: try {
47: ENGINE.init(props);
48: } catch (Exception e) {
49: throw new ConfigurationException(e);
50: }
51: }
52: private final Template template;
53:
54: /**
55: * Constructor.
56: * @param id
57: * @param statement
58: * @param resultObjectDef
59: */
60: VelocityStatement(String id, String statement,
61: ResultObjectDefinition resultObjectDef) {
62: super (id, resultObjectDef);
63: if (statement.indexOf("##") > -1) {
64: throw new ConfigurationException(
65: "Velocity statements cannot contain '##' for comments with O/R Broker. Use '#* comment *#' instead.");
66: }
67: try {
68: this .template = ENGINE.getTemplate(statement);
69: } catch (Exception e) {
70: throw new ConfigurationException(e);
71: }
72:
73: }
74:
75: /**
76: * @inheritDoc
77: * @param parameter
78: * @param replacements
79: * @return runtime statement
80: * @throws BrokerException
81: */
82: ImmutableSQL getRunnableSQL(ConnectionContext context)
83: throws BrokerException {
84: Context ctx = new VelocityContext(context.copyParameters());
85: StringWriter writer = new StringWriter();
86: try {
87: this .template.merge(ctx, writer);
88: } catch (Exception e) {
89: throw buildFailedParsingException(e);
90: }
91: logBrokerStatement(writer.getBuffer(), Statement.Type.VELOCITY);
92: return new SQLParser(writer.getBuffer())
93: .getRunnableStatement(context.getTextReplacements());
94: }
95: }
|