KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > util > JDBCTypeConversions


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 package org.apache.cocoon.util;
17
18 import java.io.BufferedInputStream JavaDoc;
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.math.BigDecimal JavaDoc;
24 import java.sql.Array JavaDoc;
25 import java.sql.Blob JavaDoc;
26 import java.sql.Clob JavaDoc;
27 import java.sql.Date JavaDoc;
28 import java.sql.PreparedStatement JavaDoc;
29 import java.sql.ResultSet JavaDoc;
30 import java.sql.SQLException JavaDoc;
31 import java.sql.Struct JavaDoc;
32 import java.sql.Time JavaDoc;
33 import java.sql.Timestamp JavaDoc;
34 import java.sql.Types JavaDoc;
35 import java.util.Calendar JavaDoc;
36 import java.util.Collections JavaDoc;
37 import java.util.HashMap JavaDoc;
38 import java.util.Map JavaDoc;
39
40 import org.apache.avalon.framework.configuration.Configuration;
41 import org.apache.cocoon.servlet.multipart.Part;
42 import org.apache.commons.lang.BooleanUtils;
43 import org.apache.excalibur.source.Source;
44
45
46 /**
47  * Provide some utility methods to read from JDBC result sets or store
48  * them to JDBC statements. Largely copied from
49  * org.apache.cocoon.acting.AbstractDatabaseAction.
50  *
51  * <p>The following table lists all available column type names
52  * together with the JDBC methods used to get or set a column with
53  * that type. In some cases the returned type differs from the type
54  * returned by the getXXX method. To set a column, a number of
55  * conversions are automatically used. For details, please see the
56  * actual code.</p>
57  *
58  * <p><table border="1">
59  * <tr><th>type </th><th>getXXX </th><th>returns </th><th>setXXX </th></tr>
60  * <tr><td>clob </td><td>Clob </td><td>String </td><td>Clob </td></tr>
61  * <tr><td>ascii </td><td>Clob </td><td>String </td><td>asciStream </td></tr>
62  * <tr><td>big-decimal</td><td>BigDecimal </td><td> </td><td>BigDecimal </td></tr>
63  * <tr><td>binary </td><td> </td><td> </td><td>BinaryStream </td></tr>
64  * <tr><td>blob </td><td> </td><td> </td><td>Blob </td></tr>
65  * <tr><td>boolean </td><td>Boolean </td><td>Boolean </td><td>Boolean </td></tr>
66  * <tr><td>byte </td><td>Byte </td><td>Byte </td><td>Byte </td></tr>
67  * <tr><td>string </td><td>String </td><td> </td><td>String </td></tr>
68  * <tr><td>date </td><td>Date </td><td> </td><td>Date </td></tr>
69  * <tr><td>double </td><td>Double </td><td>Double </td><td>Double </td></tr>
70  * <tr><td>float </td><td>Float </td><td>Float </td><td>Float </td></tr>
71  * <tr><td>int </td><td>Int </td><td>Integer </td><td>Int </td></tr>
72  * <tr><td>long </td><td>Long </td><td>Long </td><td>Long </td></tr>
73  * <tr><td>short </td><td>Short </td><td> </td><td>Short </td></tr>
74  * <tr><td>time </td><td>Time </td><td> </td><td>Time </td></tr>
75  * <tr><td>time-stamp </td><td>Timestamp </td><td> </td><td>Timestamp </td></tr>
76  * <tr><td>array </td><td>Array </td><td> </td><td>Array </td></tr>
77  * <tr><td>row </td><td>Object </td><td>Struct </td><td>Object </td></tr>
78  * <tr><td>object </td><td>Object </td><td> </td><td>Object </td></tr>
79  * </table></p>
80  *
81  * @version CVS $Id: JDBCTypeConversions.java 123788 2004-12-31 12:43:00Z antonio $
82  */

83 public class JDBCTypeConversions {
84     public static final Map JavaDoc typeConstants;
85
86     static {
87         /** Initialize the map of type names to jdbc column types.
88             Note that INTEGER, BLOB, and VARCHAR column types map to more than
89             one type name. **/

90         Map JavaDoc constants = new HashMap();
91         constants.put("clob", new Integer JavaDoc(Types.CLOB));
92         constants.put("ascii", new Integer JavaDoc(Types.CHAR));
93         constants.put("big-decimal", new Integer JavaDoc(Types.BIGINT));
94         constants.put("binary", new Integer JavaDoc(Types.VARBINARY));
95         constants.put("blob", new Integer JavaDoc(Types.BLOB));
96         constants.put("boolean", new Integer JavaDoc(Types.BIT));
97         constants.put("byte", new Integer JavaDoc(Types.TINYINT));
98         constants.put("string", new Integer JavaDoc(Types.VARCHAR));
99         constants.put("date", new Integer JavaDoc(Types.DATE));
100         constants.put("double", new Integer JavaDoc(Types.DOUBLE));
101         constants.put("float", new Integer JavaDoc(Types.FLOAT));
102         constants.put("int", new Integer JavaDoc(Types.INTEGER));
103         constants.put("long", new Integer JavaDoc(Types.NUMERIC));
104         constants.put("short", new Integer JavaDoc(Types.SMALLINT));
105         constants.put("time", new Integer JavaDoc(Types.TIME));
106         constants.put("time-stamp", new Integer JavaDoc(Types.TIMESTAMP));
107         constants.put("array", new Integer JavaDoc(Types.ARRAY));
108         constants.put("row", new Integer JavaDoc(Types.STRUCT));
109         constants.put("object", new Integer JavaDoc(Types.OTHER));
110         typeConstants = Collections.unmodifiableMap(constants);
111     }
112
113     /**
114      * Converts an object to a JDBC type. This has just been started
115      * and does not do much at the moment.
116      *
117      */

118     public static Object JavaDoc convert(Object JavaDoc value, String JavaDoc jType) {
119
120         Object JavaDoc object=null;
121         if (jType.equalsIgnoreCase("string")) {
122             if (value instanceof String JavaDoc) {
123                 object = value;
124             } else {
125                 object = value.toString();
126             }
127         } else if (jType.equalsIgnoreCase("int")) {
128             if (value instanceof String JavaDoc) {
129                 object = Integer.decode((String JavaDoc)value);
130             } else if (value instanceof Integer JavaDoc) {
131                 object = value;
132             } else {
133                 //
134
}
135         } else if (jType.equalsIgnoreCase("long")) {
136             if (value instanceof String JavaDoc) {
137                 object = Long.decode((String JavaDoc)value);
138             } else if (value instanceof Long JavaDoc) {
139                 object = value;
140             } else {
141                 //
142
}
143         } else {
144             // other types need parsing & creation
145
//
146
}
147         return object;
148     }
149                     
150       
151
152     /**
153      * Get the Statement column so that the results are mapped correctly.
154      * (this has been copied from AbstractDatabaseAction and modified slightly)
155      */

156     public static Object JavaDoc getColumn(ResultSet JavaDoc set, Configuration column ) throws Exception JavaDoc {
157
158         Integer JavaDoc type = (Integer JavaDoc) JDBCTypeConversions.typeConstants.get(column.getAttribute("type"));
159         String JavaDoc dbcol = column.getAttribute("name");
160         Object JavaDoc value = null;
161
162         switch (type.intValue()) {
163         case Types.CLOB:
164         case Types.CHAR:
165             Clob JavaDoc dbClob = set.getClob(dbcol);
166             int length = (int) dbClob.length();
167             InputStream JavaDoc asciiStream = new BufferedInputStream JavaDoc(dbClob.getAsciiStream());
168             byte[] buffer = new byte[length];
169             asciiStream.read(buffer);
170             String JavaDoc str = new String JavaDoc(buffer);
171             asciiStream.close();
172             value = str;
173             break;
174         case Types.BIGINT:
175             value = set.getBigDecimal(dbcol);
176             break;
177         case Types.TINYINT:
178             value = new Byte JavaDoc(set.getByte(dbcol));
179             break;
180         case Types.VARCHAR:
181             value = set.getString(dbcol);
182             break;
183         case Types.DATE:
184             value = set.getDate(dbcol);
185             break;
186         case Types.DOUBLE:
187             value = new Double JavaDoc(set.getDouble(dbcol));
188             break;
189         case Types.FLOAT:
190             value = new Float JavaDoc(set.getFloat(dbcol));
191             break;
192         case Types.INTEGER:
193             value = new Integer JavaDoc(set.getInt(dbcol));
194             break;
195         case Types.NUMERIC:
196             value = new Long JavaDoc(set.getLong(dbcol));
197             break;
198         case Types.SMALLINT:
199             value = new Short JavaDoc(set.getShort(dbcol));
200             break;
201         case Types.TIME:
202             value = set.getTime(dbcol);
203             break;
204         case Types.TIMESTAMP:
205             value = set.getTimestamp(dbcol);
206             break;
207         case Types.ARRAY:
208             value = set.getArray(dbcol); // new Integer(set.getInt(dbcol));
209
break;
210         case Types.BIT:
211             value = BooleanUtils.toBooleanObject(set.getBoolean(dbcol));
212             break;
213         case Types.STRUCT:
214             value = (Struct JavaDoc) set.getObject(dbcol);
215             break;
216         case Types.OTHER:
217             value = set.getObject(dbcol);
218             break;
219
220         default:
221             // The blob types have to be requested separately, via a Reader.
222
value = "";
223             break;
224         }
225
226         return value;
227     }
228
229
230     /**
231      * Set the Statement column so that the results are mapped correctly.
232      *
233      * @param statement the prepared statement
234      * @param position the position of the column
235      * @param value the value of the column
236      */

237     public static void setColumn(PreparedStatement JavaDoc statement, int position, Object JavaDoc value, Integer JavaDoc typeObject) throws Exception JavaDoc {
238         if (value instanceof String JavaDoc) {
239             value = ((String JavaDoc) value).trim();
240         }
241         if (typeObject == null) {
242             throw new SQLException JavaDoc("Can't set column because the type is unrecognized");
243         }
244         if (value == null) {
245             /** If the value is null, set the column value null and return **/
246             statement.setNull(position, typeObject.intValue());
247             return;
248         }
249         if ("".equals(value)) {
250             switch (typeObject.intValue()) {
251             case Types.CHAR:
252             case Types.CLOB:
253             case Types.VARCHAR:
254                 /** If the value is an empty string and the column is
255                     a string type, we can continue **/

256                 break;
257             default:
258                 /** If the value is an empty string and the column
259                     is something else, we treat it as a null value **/

260                 statement.setNull(position, typeObject.intValue());
261                 return;
262             }
263         }
264
265         File JavaDoc file = null;
266         int length = -1;
267         InputStream JavaDoc asciiStream = null;
268
269         //System.out.println("========================================================================");
270
//System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
271
switch (typeObject.intValue()) {
272         case Types.CLOB:
273             //System.out.println("CLOB");
274
Clob JavaDoc clob = null;
275             if (value instanceof Clob JavaDoc) {
276                 clob = (Clob JavaDoc) value;
277             } else if (value instanceof File JavaDoc) {
278                 File JavaDoc asciiFile = (File JavaDoc) value;
279                 asciiStream = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(asciiFile));
280                 length = (int) asciiFile.length();
281                 clob = new ClobHelper(asciiStream, length);
282             } else if (value instanceof Part) {
283                 Part anyFile = (Part) value;
284                 asciiStream = new BufferedInputStream JavaDoc(anyFile.getInputStream());
285                 length = anyFile.getSize();
286                 clob = new ClobHelper(asciiStream, length);
287             } else if (value instanceof JDBCxlobHelper) {
288                 asciiStream = ((JDBCxlobHelper) value).inputStream;
289                 length = ((JDBCxlobHelper) value).length;
290                 clob = new ClobHelper(asciiStream, length);
291             } else if (value instanceof Source) {
292                 asciiStream = ((Source) value).getInputStream();
293                 length = (int)((Source) value).getContentLength();
294                 clob = new ClobHelper(asciiStream, length);
295             } else {
296                 String JavaDoc asciiText = value.toString();
297                 asciiStream = new ByteArrayInputStream JavaDoc(asciiText.getBytes());
298                 length = asciiText.length();
299                 clob = new ClobHelper(asciiStream, length);
300             }
301             
302             statement.setClob(position, clob);
303             break;
304         case Types.CHAR:
305             // simple large object, e.g. Informix's TEXT
306
//System.out.println("CHAR");
307

308             if (value instanceof File JavaDoc) {
309                 File JavaDoc asciiFile = (File JavaDoc) value;
310                 asciiStream = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(asciiFile));
311                 length = (int) asciiFile.length();
312             } else if (value instanceof JDBCxlobHelper) {
313                 asciiStream = ((JDBCxlobHelper) value).inputStream;
314                 length = ((JDBCxlobHelper) value).length;
315             } else if (value instanceof Source) {
316                 asciiStream = ((Source) value).getInputStream();
317                 length = (int)((Source) value).getContentLength();
318             } else if (value instanceof Part) {
319                 Part anyFile = (Part) value;
320                 asciiStream = new BufferedInputStream JavaDoc(anyFile.getInputStream());
321                 length = anyFile.getSize();
322                 clob = new ClobHelper(asciiStream, length);
323             } else {
324                 String JavaDoc asciiText = value.toString();
325                 asciiStream = new BufferedInputStream JavaDoc(new ByteArrayInputStream JavaDoc(asciiText.getBytes()));
326                 length = asciiText.length();
327             }
328             
329             statement.setAsciiStream(position, asciiStream, length);
330             break;
331         case Types.BIGINT:
332             //System.out.println("BIGINT");
333
BigDecimal JavaDoc bd = null;
334             
335             if (value instanceof BigDecimal JavaDoc) {
336                 bd = (BigDecimal JavaDoc) value;
337             } else if (value instanceof Number JavaDoc) {
338                 bd = BigDecimal.valueOf(((Number JavaDoc)value).longValue());
339             } else {
340                 bd = new BigDecimal JavaDoc(value.toString());
341             }
342             
343             statement.setBigDecimal(position, bd);
344             break;
345         case Types.TINYINT:
346             //System.out.println("TINYINT");
347
Byte JavaDoc b = null;
348             
349             if (value instanceof Byte JavaDoc) {
350                 b = (Byte JavaDoc) value;
351             } else if (value instanceof Number JavaDoc) {
352                 b = new Byte JavaDoc(((Number JavaDoc) value).byteValue());
353             } else {
354                 b = new Byte JavaDoc(value.toString());
355             }
356             
357             statement.setByte(position, b.byteValue());
358             break;
359         case Types.DATE:
360             //System.out.println("DATE");
361
Date JavaDoc d = null;
362             
363             if (value instanceof Date JavaDoc) {
364                 d = (Date JavaDoc) value;
365             } else if (value instanceof java.util.Date JavaDoc) {
366                 d = new Date JavaDoc(((java.util.Date JavaDoc) value).getTime());
367             } else if (value instanceof Calendar JavaDoc) {
368                 d = new Date JavaDoc(((Calendar JavaDoc) value).getTime().getTime());
369             } else {
370                 d = Date.valueOf(value.toString());
371             }
372             
373             statement.setDate(position, d);
374             break;
375         case Types.DOUBLE:
376             //System.out.println("DOUBLE");
377
double db;
378             
379             if (value instanceof Number JavaDoc) {
380                 db = (((Number JavaDoc) value).doubleValue());
381             } else {
382                 db = Double.parseDouble(value.toString());
383             }
384             statement.setDouble(position, db);
385             break;
386         case Types.FLOAT:
387             //System.out.println("FLOAT");
388
float f;
389             
390             if (value instanceof Number JavaDoc) {
391                 f = (((Number JavaDoc) value).floatValue());
392             } else {
393                 f = Float.parseFloat(value.toString());
394             }
395             statement.setFloat(position, f);
396             break;
397         case Types.NUMERIC:
398             //System.out.println("NUMERIC");
399
long l;
400             
401             if (value instanceof Number JavaDoc) {
402                 l = (((Number JavaDoc) value).longValue());
403             } else {
404                 l = Long.parseLong(value.toString());
405             }
406             
407             statement.setLong(position, l);
408             break;
409         case Types.SMALLINT:
410             //System.out.println("SMALLINT");
411
Short JavaDoc s = null;
412             
413             if (value instanceof Short JavaDoc) {
414                 s = (Short JavaDoc) value;
415             } else if (value instanceof Number JavaDoc) {
416                 s = new Short JavaDoc(((Number JavaDoc) value).shortValue());
417             } else {
418                 s = new Short JavaDoc(value.toString());
419             }
420             
421             statement.setShort(position, s.shortValue());
422             break;
423         case Types.TIME:
424             //System.out.println("TIME");
425
Time JavaDoc t = null;
426             
427             if (value instanceof Time JavaDoc) {
428                 t = (Time JavaDoc) value;
429             } else if (value instanceof java.util.Date JavaDoc){
430                 t = new Time JavaDoc(((java.util.Date JavaDoc) value).getTime());
431             } else {
432                 t = Time.valueOf(value.toString());
433             }
434             
435             statement.setTime(position, t);
436             break;
437         case Types.TIMESTAMP:
438             //System.out.println("TIMESTAMP");
439
Timestamp JavaDoc ts = null;
440             
441             if (value instanceof Time JavaDoc) {
442                 ts = (Timestamp JavaDoc) value;
443             } else if (value instanceof java.util.Date JavaDoc) {
444                 ts = new Timestamp JavaDoc(((java.util.Date JavaDoc) value).getTime());
445             } else {
446                 ts = Timestamp.valueOf(value.toString());
447             }
448             
449             statement.setTimestamp(position, ts);
450             break;
451         case Types.ARRAY:
452             //System.out.println("ARRAY");
453
statement.setArray(position, (Array JavaDoc) value); // no way to convert string to array
454
break;
455         case Types.STRUCT:
456             //System.out.println("STRUCT");
457
case Types.OTHER:
458             //System.out.println("OTHER");
459
statement.setObject(position, value);
460             break;
461         case Types.LONGVARBINARY:
462             //System.out.println("LONGVARBINARY");
463
statement.setTimestamp(position, new Timestamp JavaDoc((new java.util.Date JavaDoc()).getTime()));
464             break;
465         case Types.VARCHAR:
466             //System.out.println("VARCHAR");
467
statement.setString(position, value.toString());
468             break;
469         case Types.BLOB:
470             //System.out.println("BLOB");
471
if (value instanceof JDBCxlobHelper) {
472                 statement.setBinaryStream(position, ((JDBCxlobHelper)value).inputStream, ((JDBCxlobHelper)value).length);
473             } else if (value instanceof Source){
474                 statement.setBinaryStream(position, ((Source)value).getInputStream(), (int)((Source)value).getContentLength());
475             } else {
476                 Blob JavaDoc blob = null;
477                 if (value instanceof Blob JavaDoc) {
478                     blob = (Blob JavaDoc) value;
479                 } else if( value instanceof File JavaDoc) {
480                     file = (File JavaDoc)value;
481                     blob = new BlobHelper(new FileInputStream JavaDoc(file), (int) file.length());
482                 } else if (value instanceof String JavaDoc) {
483                     file = new File JavaDoc((String JavaDoc)value);
484                     blob = new BlobHelper(new FileInputStream JavaDoc(file), (int) file.length());
485                 } else if (value instanceof Part) {
486                     Part anyFile = (Part) value;
487                     blob = new BlobHelper(new BufferedInputStream JavaDoc(anyFile.getInputStream()), anyFile.getSize());
488                 } else {
489                     throw new SQLException JavaDoc("Invalid type for blob: "+value.getClass().getName());
490                 }
491                 //InputStream input = new BufferedInputStream(new FileInputStream(file));
492
statement.setBlob(position, blob);
493             }
494             break;
495         case Types.VARBINARY:
496             //System.out.println("VARBINARY");
497
if (value instanceof JDBCxlobHelper) {
498                 statement.setBinaryStream(position, ((JDBCxlobHelper)value).inputStream, ((JDBCxlobHelper)value).length);
499             } else if (value instanceof Source){
500                 statement.setBinaryStream(position, ((Source)value).getInputStream(), (int)((Source)value).getContentLength());
501             } else if (value instanceof Part) {
502                 statement.setBinaryStream(position, ((Part)value).getInputStream(), ((Part)value).getSize());
503             } else {
504                 if (value instanceof File JavaDoc) {
505                    file = (File JavaDoc)value;
506                } else if (value instanceof String JavaDoc) {
507                    file = new File JavaDoc((String JavaDoc)value);
508                } else {
509                    throw new SQLException JavaDoc("Invalid type for blob: "+value.getClass().getName());
510                 }
511                  //InputStream input = new BufferedInputStream(new FileInputStream(file));
512
FileInputStream JavaDoc input = new FileInputStream JavaDoc(file);
513                  statement.setBinaryStream(position, input, (int)file.length());
514             }
515             break;
516         case Types.INTEGER:
517             //System.out.println("INTEGER");
518
Integer JavaDoc i = null;
519             if (value instanceof Integer JavaDoc) {
520                 i = (Integer JavaDoc) value;
521             } else if (value instanceof Number JavaDoc) {
522                 i = new Integer JavaDoc(((Number JavaDoc) value).intValue());
523             } else {
524                 i = new Integer JavaDoc(value.toString());
525             }
526             statement.setInt(position, i.intValue());
527             break;
528         case Types.BIT:
529             //System.out.println("BIT");
530
Boolean JavaDoc bo = null;
531             if (value instanceof Boolean JavaDoc) {
532                 bo = (Boolean JavaDoc)value;
533             } else if (value instanceof Number JavaDoc) {
534                 bo = BooleanUtils.toBooleanObject(((Number JavaDoc) value).intValue()==1);
535             } else {
536                 bo = BooleanUtils.toBooleanObject(value.toString());
537             }
538             statement.setBoolean(position, bo.booleanValue());
539             break;
540
541         default:
542             //System.out.println("default");
543
throw new SQLException JavaDoc("Impossible exception - invalid type ");
544         }
545         //System.out.println("========================================================================");
546
}
547 }
548
Popular Tags