KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tapestry > contrib > jdbc > StatementAssembly


1 // Copyright 2004, 2005 The Apache Software Foundation
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
// http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15 package org.apache.tapestry.contrib.jdbc;
16
17 import java.sql.Connection JavaDoc;
18 import java.sql.SQLException JavaDoc;
19 import java.sql.Timestamp JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Calendar JavaDoc;
22 import java.util.Date JavaDoc;
23 import java.util.GregorianCalendar JavaDoc;
24 import java.util.List JavaDoc;
25
26 /**
27  * Class for creating and executing JDBC statements. Allows statements to be assembled
28  * incrementally (like a {@link StringBuffer}), but also tracks parameters, shielding
29  * the developer from the differences between constructing and
30  * using a JDBC
31  * {@link java.sql.Statement} and
32  * a JDBC {@link java.sql.PreparedStatement}. This class is somewhat skewed towards
33  * Oracle, which works more efficiently with prepared staments than
34  * simple SQL.
35  *
36  * <p>In addition, implements {@link #toString()} in a useful way (you can see the
37  * SQL and parameters), which is invaluable when debugging.
38  *
39  * <p>{@link #addParameter(int)} (and all overloaded versions of it for scalar types)
40  * adds a "?" to the statement and records the parameter value.
41  *
42  * <p>{@link #addParameter(Integer)} (and all overloaded version of it for wrapper
43  * types) does the same ... unless the value is null, in which case "NULL" is
44  * inserted into the statement.
45  *
46  * <p>{@link #addParameterList(int[], String)} (and all overloaded versions of it)
47  * simply invokes the appropriate {@link #addParameter(int)}, adding the
48  * separator in between parameters.
49  *
50  * @author Howard Lewis Ship
51  *
52  **/

53
54 public class StatementAssembly
55 {
56     private StringBuffer JavaDoc _buffer = new StringBuffer JavaDoc();
57
58     private static final String JavaDoc NULL = "NULL";
59
60     public static final String JavaDoc SEP = ", ";
61
62     /**
63      * List of {@link IParameter}
64      *
65      **/

66
67     private List JavaDoc _parameters;
68
69     private int _lineLength;
70     private int _maxLineLength = 80;
71     private int _indent = 5;
72
73     /**
74      * Default constructor; uses a maximum line length of 80 and an indent of 5.
75      *
76      **/

77
78     public StatementAssembly()
79     {
80     }
81
82     public StatementAssembly(int maxLineLength, int indent)
83     {
84         _maxLineLength = maxLineLength;
85         _indent = indent;
86     }
87
88     /**
89      * Clears the assembly, preparing it for re-use.
90      *
91      * @since 1.0.7
92      *
93      **/

94
95     public void clear()
96     {
97         _buffer.setLength(0);
98         _lineLength = 0;
99
100         if (_parameters != null)
101             _parameters.clear();
102     }
103
104     /**
105      * Maximum length of a line.
106      *
107      **/

108
109     public int getMaxLineLength()
110     {
111         return _maxLineLength;
112     }
113
114     /**
115      * Number of spaces to indent continuation lines by.
116      *
117      **/

118
119     public int getIndent()
120     {
121         return _indent;
122     }
123
124     /**
125      * Adds text to the current line, unless that would make the line too long, in
126      * which case a new line is started (and indented) before adding the text.
127      *
128      * <p>Text is added as-is, with no concept of quoting. To add arbitrary strings
129      * (such as in a where clause), use {@link #addParameter(String)}.
130      *
131      *
132      **/

133
134     public void add(String JavaDoc text)
135     {
136         int textLength;
137
138         textLength = text.length();
139
140         if (_lineLength + textLength > _maxLineLength)
141         {
142             _buffer.append('\n');
143
144             for (int i = 0; i < _indent; i++)
145                 _buffer.append(' ');
146
147             _lineLength = _indent;
148         }
149
150         _buffer.append(text);
151         _lineLength += textLength;
152     }
153     
154     public void add(short value)
155     {
156         add(Short.toString(value));
157     }
158     
159     public void add(int value)
160     {
161         add(Integer.toString(value));
162     }
163     
164     public void add(long value)
165     {
166         add(Long.toString(value));
167     }
168     
169     public void add(float value)
170     {
171         add(Float.toString(value));
172     }
173     
174     public void add(double value)
175     {
176         add(Double.toString(value));
177     }
178
179     /**
180      * Adds a date value to a {@link StatementAssembly} converting
181      * it to a {@link java.sql.Timestamp} first.
182      *
183      **/

184
185     public void addParameter(Date JavaDoc date)
186     {
187         if (date == null)
188         {
189             add("NULL");
190             return;
191         }
192
193         Calendar JavaDoc calendar = GregorianCalendar.getInstance();
194
195         calendar.setTime(date);
196         calendar.set(Calendar.MILLISECOND, 0);
197
198         Date JavaDoc adjusted = calendar.getTime();
199
200         Timestamp JavaDoc timestamp = new Timestamp JavaDoc(adjusted.getTime());
201
202         addParameter(timestamp);
203     }
204
205     /**
206      * Adds a separator (usually a comma and a space) to the current line, regardless
207      * of line length. This is purely aesthetic ... it just looks odd if a separator
208      * gets wrapped to a new line by itself.
209      *
210      **/

211
212     public void addSep(String JavaDoc text)
213     {
214         _buffer.append(text);
215         _lineLength += text.length();
216     }
217
218     /**
219      * Starts a new line, without indenting.
220      *
221      **/

222
223     public void newLine()
224     {
225         if (_buffer.length() != 0)
226             _buffer.append('\n');
227
228         _lineLength = 0;
229     }
230
231     /**
232      * Starts a new line, then adds the given text.
233      *
234      **/

235
236     public void newLine(String JavaDoc text)
237     {
238         if (_buffer.length() != 0)
239             _buffer.append('\n');
240
241         _buffer.append(text);
242
243         _lineLength = text.length();
244     }
245
246     public void addList(String JavaDoc[] items, String JavaDoc separator)
247     {
248         for (int i = 0; i < items.length; i++)
249         {
250             if (i > 0)
251                 addSep(separator);
252
253             add(items[i]);
254         }
255     }
256
257     public void addParameterList(int[] items, String JavaDoc separator)
258     {
259         for (int i = 0; i < items.length; i++)
260         {
261             if (i > 0)
262                 addSep(separator);
263
264             addParameter(items[i]);
265         }
266     }
267
268     public void addParameterList(Integer JavaDoc[] items, String JavaDoc separator)
269     {
270         for (int i = 0; i < items.length; i++)
271         {
272             if (i > 0)
273                 addSep(separator);
274
275             addParameter(items[i]);
276         }
277     }
278
279     public void addParameterList(long[] items, String JavaDoc separator)
280     {
281         for (int i = 0; i < items.length; i++)
282         {
283             if (i > 0)
284                 addSep(separator);
285
286             addParameter(items[i]);
287         }
288     }
289
290     public void addParameterList(Long JavaDoc[] items, String JavaDoc separator)
291     {
292         for (int i = 0; i < items.length; i++)
293         {
294             if (i > 0)
295                 addSep(separator);
296
297             addParameter(items[i]);
298         }
299     }
300
301     public void addParameterList(String JavaDoc[] items, String JavaDoc separator)
302     {
303         for (int i = 0; i < items.length; i++)
304         {
305             if (i > 0)
306                 addSep(separator);
307
308             addParameter(items[i]);
309         }
310     }
311
312     public void addParameterList(double[] items, String JavaDoc separator)
313     {
314         for (int i = 0; i < items.length; i++)
315         {
316             if (i > 0)
317                 addSep(separator);
318
319             addParameter(items[i]);
320         }
321     }
322
323     public void addParameter(Object JavaDoc value)
324     {
325         if (value == null)
326             add(NULL);
327         else
328             addParameter(new ObjectParameter(value));
329     }
330
331     public void addParameter(Timestamp JavaDoc timestamp)
332     {
333         if (timestamp == null)
334             add(NULL);
335         else
336             addParameter(new TimestampParameter(timestamp));
337     }
338
339     public void addParameter(String JavaDoc value)
340     {
341         if (value == null)
342             add(NULL);
343         else
344             addParameter(new StringParameter(value));
345     }
346
347     public void addParameter(int value)
348     {
349         addParameter(new IntegerParameter(value));
350     }
351
352     public void addParameter(Integer JavaDoc value)
353     {
354         if (value == null)
355             add(NULL);
356         else
357             addParameter(value.intValue());
358     }
359
360     public void addParameter(long value)
361     {
362         addParameter(new LongParameter(value));
363     }
364
365     public void addParameter(Long JavaDoc value)
366     {
367         if (value == null)
368             add(NULL);
369         else
370             addParameter(value.longValue());
371     }
372
373     public void addParameter(float value)
374     {
375         addParameter(new FloatParameter(value));
376     }
377
378     public void addParameter(Float JavaDoc value)
379     {
380         if (value == null)
381             add(NULL);
382         else
383             addParameter(value.floatValue());
384     }
385
386     public void addParameter(double value)
387     {
388         addParameter(new DoubleParameter(value));
389     }
390
391     public void addParameter(Double JavaDoc value)
392     {
393         if (value == null)
394             add(NULL);
395         else
396             addParameter(value.doubleValue());
397     }
398
399     public void addParameter(short value)
400     {
401         addParameter(new ShortParameter(value));
402     }
403
404     public void addParameter(Short JavaDoc value)
405     {
406         if (value == null)
407             add(NULL);
408         else
409             addParameter(value.shortValue());
410     }
411
412     public void addParameter(boolean value)
413     {
414         addParameter(value ? BooleanParameter.TRUE : BooleanParameter.FALSE);
415     }
416
417     public void addParameter(Boolean JavaDoc value)
418     {
419         if (value == null)
420             add(NULL);
421         else
422             addParameter(value.booleanValue());
423     }
424
425     private void addParameter(IParameter parameter)
426     {
427         if (_parameters == null)
428             _parameters = new ArrayList JavaDoc();
429
430         _parameters.add(parameter);
431
432         add("?");
433     }
434
435     /**
436      * Creates and returns an {@link IStatement} based on the SQL and parameters
437      * acquired.
438      *
439      **/

440
441     public IStatement createStatement(Connection JavaDoc connection) throws SQLException JavaDoc
442     {
443         String JavaDoc sql = _buffer.toString();
444
445         if (_parameters == null || _parameters.isEmpty())
446             return new SimpleStatement(sql, connection);
447
448         return new ParameterizedStatement(sql, connection, _parameters);
449     }
450
451     public String JavaDoc toString()
452     {
453         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc("StatementAssembly@");
454
455         buffer.append(Integer.toHexString(hashCode()));
456         buffer.append("[SQL=\n<");
457         buffer.append(_buffer);
458         buffer.append("\n>");
459
460         if (_parameters != null)
461         {
462             int count = _parameters.size();
463             for (int i = 0; i < count; i++)
464             {
465                 Object JavaDoc parameter = _parameters.get(i);
466
467                 buffer.append(" ?");
468                 buffer.append(i + 1);
469                 buffer.append('=');
470
471                 buffer.append(parameter);
472             }
473         }
474
475         buffer.append(']');
476
477         return buffer.toString();
478     }
479 }
Popular Tags