KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > jdbc > SQLTemplateProcessor


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.access.jdbc;
57
58 import java.io.StringReader JavaDoc;
59 import java.io.StringWriter JavaDoc;
60 import java.util.ArrayList JavaDoc;
61 import java.util.HashMap JavaDoc;
62 import java.util.List JavaDoc;
63 import java.util.Map JavaDoc;
64
65 import org.apache.velocity.VelocityContext;
66 import org.apache.velocity.context.InternalContextAdapterImpl;
67 import org.apache.velocity.exception.ParseErrorException;
68 import org.apache.velocity.runtime.RuntimeConstants;
69 import org.apache.velocity.runtime.RuntimeInstance;
70 import org.apache.velocity.runtime.log.NullLogSystem;
71 import org.apache.velocity.runtime.parser.ParseException;
72 import org.apache.velocity.runtime.parser.node.SimpleNode;
73 import org.objectstyle.cayenne.CayenneRuntimeException;
74
75 /**
76  * Processor for SQL velocity templates.
77  *
78  * @see org.objectstyle.cayenne.query.SQLTemplate
79  * @since 1.1
80  * @author Andrei Adamchik
81  */

82 class SQLTemplateProcessor {
83     private static RuntimeInstance sharedRuntime;
84
85     static final String JavaDoc BINDINGS_LIST_KEY = "bindings";
86     static final String JavaDoc RESULT_COLUMNS_LIST_KEY = "resultColumns";
87     static final String JavaDoc HELPER_KEY = "helper";
88
89     private static final SQLTemplateRenderingUtils sharedUtils =
90         new SQLTemplateRenderingUtils();
91
92     RuntimeInstance velocityRuntime;
93     SQLTemplateRenderingUtils renderingUtils;
94
95     static {
96         initVelocityRuntime();
97     }
98
99     private static void initVelocityRuntime() {
100         // init static velocity engine
101
sharedRuntime = new RuntimeInstance();
102
103         // set null logger
104
sharedRuntime.addProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogSystem());
105         
106         sharedRuntime.addProperty(
107             RuntimeConstants.RESOURCE_MANAGER_CLASS,
108             SQLTemplateResourceManager.class.getName());
109         sharedRuntime.addProperty("userdirective", BindDirective.class.getName());
110         sharedRuntime.addProperty("userdirective", BindEqualDirective.class.getName());
111         sharedRuntime.addProperty("userdirective", BindNotEqualDirective.class.getName());
112         sharedRuntime.addProperty("userdirective", ResultDirective.class.getName());
113         sharedRuntime.addProperty("userdirective", ChainDirective.class.getName());
114         sharedRuntime.addProperty("userdirective", ChunkDirective.class.getName());
115         try {
116             sharedRuntime.init();
117         }
118         catch (Exception JavaDoc ex) {
119             throw new CayenneRuntimeException(
120                 "Error setting up Velocity RuntimeInstance.",
121                 ex);
122         }
123     }
124
125     SQLTemplateProcessor() {
126         this.velocityRuntime = sharedRuntime;
127         this.renderingUtils = sharedUtils;
128     }
129
130     SQLTemplateProcessor(
131         RuntimeInstance velocityRuntime,
132         SQLTemplateRenderingUtils renderingUtils) {
133         this.velocityRuntime = velocityRuntime;
134         this.renderingUtils = renderingUtils;
135     }
136
137     /**
138      * Builds and returns a SQLSelectStatement based on SQL template and a set of parameters.
139      * During rendering VelocityContext exposes the following as variables: all parameters
140      * in the map, {@link SQLTemplateRenderingUtils} as a "helper" variable and SQLStatement
141      * object as "statement" variable.
142      */

143     SQLSelectStatement processSelectTemplate(String JavaDoc template, Map JavaDoc parameters)
144         throws Exception JavaDoc {
145
146         // have to make a copy of parameter map since we are gonna modify it..
147
Map JavaDoc internalParameters =
148             (parameters != null && !parameters.isEmpty())
149                 ? new HashMap JavaDoc(parameters)
150                 : new HashMap JavaDoc(3);
151
152         List JavaDoc bindings = new ArrayList JavaDoc();
153         List JavaDoc results = new ArrayList JavaDoc();
154         internalParameters.put(BINDINGS_LIST_KEY, bindings);
155         internalParameters.put(RESULT_COLUMNS_LIST_KEY, results);
156         internalParameters.put(HELPER_KEY, renderingUtils);
157
158         String JavaDoc sql =
159             buildStatement(new VelocityContext(internalParameters), template, parameters);
160
161         ParameterBinding[] bindingsArray = new ParameterBinding[bindings.size()];
162         bindings.toArray(bindingsArray);
163
164         ColumnDescriptor[] resultsArray = new ColumnDescriptor[results.size()];
165         results.toArray(resultsArray);
166         return new SQLSelectStatement(sql, resultsArray, bindingsArray);
167     }
168
169     /**
170      * Builds and returns a SQLStatement based on SQL template and a set of parameters.
171      * During rendering, VelocityContext exposes the following as variables: all parameters
172      * in the map, {@link SQLTemplateRenderingUtils} as a "helper" variable and SQLStatement
173      * object as "statement" variable.
174      */

175     SQLStatement processTemplate(String JavaDoc template, Map JavaDoc parameters) throws Exception JavaDoc {
176         // have to make a copy of parameter map since we are gonna modify it..
177
Map JavaDoc internalParameters =
178             (parameters != null && !parameters.isEmpty())
179                 ? new HashMap JavaDoc(parameters)
180                 : new HashMap JavaDoc(3);
181
182         List JavaDoc bindings = new ArrayList JavaDoc();
183         internalParameters.put(BINDINGS_LIST_KEY, bindings);
184         internalParameters.put(HELPER_KEY, renderingUtils);
185
186         String JavaDoc sql =
187             buildStatement(new VelocityContext(internalParameters), template, parameters);
188
189         ParameterBinding[] bindingsArray = new ParameterBinding[bindings.size()];
190         bindings.toArray(bindingsArray);
191         return new SQLStatement(sql, bindingsArray);
192     }
193
194     String JavaDoc buildStatement(VelocityContext context, String JavaDoc template, Map JavaDoc parameters)
195         throws Exception JavaDoc {
196         // Note: this method is a reworked version of org.apache.velocity.app.Velocity.evaluate(..)
197
// cleaned up to avoid using any Velocity singletons
198

199         StringWriter JavaDoc out = new StringWriter JavaDoc(template.length());
200         SimpleNode nodeTree = null;
201
202         try {
203             nodeTree = velocityRuntime.parse(new StringReader JavaDoc(template), template);
204         }
205         catch (ParseException pex) {
206             throw new ParseErrorException(pex.getMessage());
207         }
208
209         if (nodeTree == null) {
210             throw new CayenneRuntimeException("Error parsing template " + template);
211         }
212
213         // ... not sure what InternalContextAdapter is for...
214
InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context);
215         ica.pushCurrentTemplateName(template);
216
217         try {
218             nodeTree.init(ica, velocityRuntime);
219             nodeTree.render(ica, out);
220             return out.toString();
221         }
222         finally {
223             ica.popCurrentTemplateName();
224         }
225     }
226 }
227
Popular Tags