KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > ejb > plugins > cmp > jdbc > JDBCResultSetReader


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.ejb.plugins.cmp.jdbc;
23
24 import org.jboss.logging.Logger;
25
26 import javax.ejb.Handle JavaDoc;
27 import java.sql.ResultSet JavaDoc;
28 import java.sql.SQLException JavaDoc;
29 import java.sql.Clob JavaDoc;
30 import java.sql.Blob JavaDoc;
31 import java.rmi.MarshalledObject JavaDoc;
32 import java.rmi.RemoteException JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.io.Reader JavaDoc;
35 import java.io.InputStream JavaDoc;
36
37 /**
38  * Implementations of this interface are used to read java.sql.ResultSet.
39  *
40  * @author <a HREF="mailto:alex@jboss.org">Alexey Loubyansky</a>
41  * @version <tt>$Revision: 45069 $</tt>
42  */

43 public interface JDBCResultSetReader
44 {
45    /**
46     * Reads one column from the java.sql.ResultSet.
47     * @param rs the java.sql.ResultSet to read from
48     * @param index the index of the column
49     * @param destination the expected Java class of result
50     * @param log the logger
51     * @return column value
52     * @throws SQLException
53     */

54    Object JavaDoc get(ResultSet JavaDoc rs, int index, Class JavaDoc destination, Logger log) throws SQLException JavaDoc;
55
56    public static final JDBCResultSetReader CLOB_READER = new AbstractResultSetReader()
57    {
58       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
59       {
60          Clob JavaDoc clob = rs.getClob(index);
61
62          String JavaDoc content;
63          if(clob == null)
64          {
65             content = null;
66          }
67          else
68          {
69             final Reader JavaDoc reader = clob.getCharacterStream();
70             if(reader != null)
71             {
72                int intLength = (int)clob.length();
73
74                char[] chars;
75                try
76                {
77                   if(intLength <= 8192)
78                   {
79                      chars = new char[intLength];
80                      reader.read(chars);
81                      content = String.valueOf(chars);
82                   }
83                   else
84                   {
85                      StringBuffer JavaDoc buf = new StringBuffer JavaDoc(intLength);
86                      chars = new char[8192];
87                      int i = reader.read(chars);
88                      while(i > 0)
89                      {
90                         buf.append(chars, 0, i);
91                         i = reader.read(chars);
92                      }
93                      content = buf.toString();
94                   }
95                }
96                catch(IOException JavaDoc e)
97                {
98                   throw new SQLException JavaDoc("Failed to read CLOB character stream: " + e.getMessage());
99                }
100                finally
101                {
102                   JDBCUtil.safeClose(reader);
103                }
104             }
105             else
106             {
107                content = null;
108             }
109          }
110
111          return content;
112       }
113    };
114
115    public static final JDBCResultSetReader LONGVARCHAR_READER = new AbstractResultSetReader()
116    {
117       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
118       {
119          return JDBCUtil.getLongString(rs, index);
120       }
121    };
122
123    public static final JDBCResultSetReader BINARY_READER = new AbstractResultSetReader()
124    {
125       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
126       {
127          Object JavaDoc value = null;
128          byte[] bytes = rs.getBytes(index);
129          if(!rs.wasNull())
130          {
131             if(destination == byte[].class)
132                value = bytes;
133             else
134                value = JDBCUtil.convertToObject(bytes);
135          }
136          return value;
137       }
138    };
139
140    public static final JDBCResultSetReader VARBINARY_READER = new AbstractResultSetReader()
141    {
142       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
143       {
144          Object JavaDoc value = null;
145          byte[] bytes = rs.getBytes(index);
146          if(!rs.wasNull())
147          {
148             if(destination == byte[].class)
149                value = bytes;
150             else
151                value = JDBCUtil.convertToObject(bytes);
152          }
153          return value;
154       }
155    };
156
157    public static final JDBCResultSetReader BLOB_READER = new AbstractResultSetReader()
158    {
159       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
160       {
161          Blob JavaDoc blob = rs.getBlob(index);
162
163          Object JavaDoc value;
164          if(blob == null)
165          {
166             value = null;
167          }
168          else
169          {
170             InputStream JavaDoc binaryData = blob.getBinaryStream();
171             if(binaryData != null)
172             {
173                if(destination == byte[].class)
174                   value = JDBCUtil.getByteArray(binaryData);
175                else
176                   value = JDBCUtil.convertToObject(binaryData);
177             }
178             else
179             {
180                value = null;
181             }
182          }
183
184          return value;
185       }
186    };
187
188    public static final JDBCResultSetReader LONGVARBINARY_READER = new AbstractResultSetReader()
189    {
190       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
191       {
192          Object JavaDoc value = null;
193          InputStream JavaDoc binaryData = rs.getBinaryStream(index);
194          if(binaryData != null && !rs.wasNull())
195          {
196             if(destination == byte[].class)
197                value = JDBCUtil.getByteArray(binaryData);
198             else
199                value = JDBCUtil.convertToObject(binaryData);
200          }
201          return value;
202       }
203    };
204
205    public static final JDBCResultSetReader JAVA_OBJECT_READER = new AbstractResultSetReader()
206    {
207       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
208       {
209          return rs.getObject(index);
210       }
211    };
212
213    public static final JDBCResultSetReader STRUCT_READER = new AbstractResultSetReader()
214    {
215       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
216       {
217          return rs.getObject(index);
218       }
219    };
220
221    public static final JDBCResultSetReader ARRAY_READER = new AbstractResultSetReader()
222    {
223       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
224       {
225          return rs.getObject(index);
226       }
227    };
228
229    public static final JDBCResultSetReader OTHER_READER = new AbstractResultSetReader()
230    {
231       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
232       {
233          return rs.getObject(index);
234       }
235    };
236
237    public static final JDBCResultSetReader JAVA_UTIL_DATE_READER = new AbstractResultSetReader()
238    {
239       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
240       {
241          return rs.getTimestamp(index);
242       }
243
244       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
245       {
246          // make new copy as sub types have problems in comparions
247
java.util.Date JavaDoc result;
248          // handle timestamp special becauses it hoses the milisecond values
249
if(value instanceof java.sql.Timestamp JavaDoc)
250          {
251             java.sql.Timestamp JavaDoc ts = (java.sql.Timestamp JavaDoc)value;
252             // Timestamp returns whole seconds from getTime and partial
253
// seconds are retrieved from getNanos()
254
// Adrian Brock: Not in 1.4 it doesn't
255
long temp = ts.getTime();
256             if(temp % 1000 == 0)
257                temp += ts.getNanos() / 1000000;
258             result = new java.util.Date JavaDoc(temp);
259          }
260          else
261          {
262             result = new java.util.Date JavaDoc(((java.util.Date JavaDoc)value).getTime());
263          }
264          return result;
265       }
266    };
267
268    public static final JDBCResultSetReader JAVA_SQL_DATE_READER = new AbstractResultSetReader()
269    {
270       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
271       {
272          return rs.getDate(index);
273       }
274
275       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
276       {
277          // make a new copy object; you never know what a driver will return
278
return new java.sql.Date JavaDoc(((java.sql.Date JavaDoc)value).getTime());
279       }
280    };
281
282    public static final JDBCResultSetReader JAVA_SQL_TIME_READER = new AbstractResultSetReader()
283    {
284       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
285       {
286          return rs.getTime(index);
287       }
288
289       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
290       {
291          // make a new copy object; you never know what a driver will return
292
return new java.sql.Time JavaDoc(((java.sql.Time JavaDoc)value).getTime());
293       }
294    };
295
296    public static final JDBCResultSetReader JAVA_SQL_TIMESTAMP_READER = new AbstractResultSetReader()
297    {
298       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
299       {
300          return rs.getTimestamp(index);
301       }
302
303       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
304       {
305          // make a new copy object; you never know what a driver will return
306
java.sql.Timestamp JavaDoc orignal = (java.sql.Timestamp JavaDoc)value;
307          java.sql.Timestamp JavaDoc copy = new java.sql.Timestamp JavaDoc(orignal.getTime());
308          copy.setNanos(orignal.getNanos());
309          return copy;
310       }
311    };
312
313    public static final JDBCResultSetReader BIGDECIMAL_READER = new AbstractResultSetReader()
314    {
315       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
316          throws SQLException JavaDoc
317       {
318          return rs.getBigDecimal(index);
319       }
320    };
321
322    public static final JDBCResultSetReader REF_READER = new AbstractResultSetReader()
323    {
324       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
325          throws SQLException JavaDoc
326       {
327          return rs.getRef(index);
328       }
329    };
330
331    public static final JDBCResultSetReader BYTE_ARRAY_READER = new AbstractResultSetReader()
332    {
333       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
334          throws SQLException JavaDoc
335       {
336          return rs.getBytes(index);
337       }
338    };
339
340    public static final JDBCResultSetReader OBJECT_READER = new AbstractResultSetReader()
341    {
342       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination) throws SQLException JavaDoc
343       {
344          return rs.getObject(index);
345       }
346    };
347
348    public static final JDBCResultSetReader STRING_READER = new JDBCResultSetReader()
349    {
350       public Object JavaDoc get(ResultSet JavaDoc rs, int index, Class JavaDoc destination, Logger log) throws SQLException JavaDoc
351       {
352          final String JavaDoc result = rs.getString(index);
353
354          if(log.isTraceEnabled())
355          {
356             log.trace("result: i=" + index + ", type=" + destination.getName() + ", value=" + result);
357          }
358
359          return result;
360       }
361    };
362
363    abstract class AbstractPrimitiveReader
364       extends AbstractResultSetReader
365    {
366       // ResultSetReader implementation
367

368       public Object JavaDoc get(ResultSet JavaDoc rs, int index, Class JavaDoc destination, Logger log)
369          throws SQLException JavaDoc
370       {
371          Object JavaDoc result = readResult(rs, index, destination);
372          if(rs.wasNull())
373             result = null;
374          else
375             result = coerceToJavaType(result, destination);
376
377          if(log.isTraceEnabled())
378          {
379             log.trace("result: i=" + index + ", type=" + destination.getName() + ", value=" + result);
380          }
381
382          return result;
383       }
384
385       // Protected
386

387       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
388          throws SQLException JavaDoc
389       {
390          return value;
391       }
392    }
393
394    public static final JDBCResultSetReader BOOLEAN_READER = new AbstractPrimitiveReader()
395    {
396       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
397          throws SQLException JavaDoc
398       {
399          return (rs.getBoolean(index) ? Boolean.TRUE : Boolean.FALSE);
400       }
401    };
402
403    public static final JDBCResultSetReader BYTE_READER = new AbstractPrimitiveReader()
404    {
405       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
406          throws SQLException JavaDoc
407       {
408          return new Byte JavaDoc(rs.getByte(index));
409       }
410    };
411
412    public static final JDBCResultSetReader CHARACTER_READER = new AbstractPrimitiveReader()
413    {
414       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
415          throws SQLException JavaDoc
416       {
417          return rs.getString(index);
418       }
419
420       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
421       {
422          //
423
// java.lang.String --> java.lang.Character or char
424
//
425
// just grab first character
426
if(value instanceof String JavaDoc && (destination == Character JavaDoc.class || destination == Character.TYPE))
427          {
428             return new Character JavaDoc(((String JavaDoc)value).charAt(0));
429          }
430          else
431          {
432             return value;
433          }
434       }
435    };
436
437    public static final JDBCResultSetReader SHORT_READER = new AbstractPrimitiveReader()
438    {
439       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
440          throws SQLException JavaDoc
441       {
442          return new Short JavaDoc(rs.getShort(index));
443       }
444    };
445
446    public static final JDBCResultSetReader INT_READER = new AbstractPrimitiveReader()
447    {
448       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
449          throws SQLException JavaDoc
450       {
451          return new Integer JavaDoc(rs.getInt(index));
452       }
453    };
454
455    public static final JDBCResultSetReader LONG_READER = new AbstractPrimitiveReader()
456    {
457       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
458          throws SQLException JavaDoc
459       {
460          return new Long JavaDoc(rs.getLong(index));
461       }
462    };
463
464    public static final JDBCResultSetReader FLOAT_READER = new AbstractPrimitiveReader()
465    {
466       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
467          throws SQLException JavaDoc
468       {
469          return new Float JavaDoc(rs.getFloat(index));
470       }
471    };
472
473    public static final JDBCResultSetReader DOUBLE_READER = new AbstractPrimitiveReader()
474    {
475       protected Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
476          throws SQLException JavaDoc
477       {
478          return new Double JavaDoc(rs.getDouble(index));
479       }
480    };
481
482    abstract class AbstractResultSetReader implements JDBCResultSetReader
483    {
484       public Object JavaDoc get(ResultSet JavaDoc rs, int index, Class JavaDoc destination, Logger log) throws SQLException JavaDoc
485       {
486          Object JavaDoc result = readResult(rs, index, destination);
487          if(result != null)
488             result = coerceToJavaType(result, destination);
489
490          if(log.isTraceEnabled())
491          {
492             log.trace("result: i=" + index + ", type=" + destination.getName() + ", value=" + result);
493          }
494
495          return result;
496       }
497
498       protected abstract Object JavaDoc readResult(ResultSet JavaDoc rs, int index, Class JavaDoc destination)
499          throws SQLException JavaDoc;
500
501       protected Object JavaDoc coerceToJavaType(Object JavaDoc value, Class JavaDoc destination)
502          throws SQLException JavaDoc
503       {
504          try
505          {
506             //
507
// java.rmi.MarshalledObject
508
//
509
// get unmarshalled value
510
if(value instanceof MarshalledObject JavaDoc && !destination.equals(MarshalledObject JavaDoc.class))
511             {
512                value = ((MarshalledObject JavaDoc)value).get();
513             }
514
515             //
516
// javax.ejb.Handle
517
//
518
// get the object back from the handle
519
if(value instanceof Handle JavaDoc)
520             {
521                value = ((Handle JavaDoc)value).getEJBObject();
522             }
523
524             // Did we get the desired result?
525
if(destination.isAssignableFrom(value.getClass()))
526             {
527                return value;
528             }
529
530             if(destination == java.math.BigInteger JavaDoc.class && value.getClass() == java.math.BigDecimal JavaDoc.class)
531             {
532                return ((java.math.BigDecimal JavaDoc)value).toBigInteger();
533             }
534
535             // oops got the wrong type - nothing we can do
536
throw new SQLException JavaDoc("Got a " + value.getClass().getName() + "[cl=" +
537                System.identityHashCode(value.getClass().getClassLoader()) +
538                ", value=" + value + "] while looking for a " +
539                destination.getName() + "[cl=" +
540                System.identityHashCode(destination) + "]");
541          }
542          catch(RemoteException JavaDoc e)
543          {
544             throw new SQLException JavaDoc("Unable to load EJBObject back from Handle: " + e);
545          }
546          catch(IOException JavaDoc e)
547          {
548             throw new SQLException JavaDoc("Unable to load to deserialize result: " + e);
549          }
550          catch(ClassNotFoundException JavaDoc e)
551          {
552             throw new SQLException JavaDoc("Unable to load to deserialize result: " + e);
553          }
554       }
555    }
556 }
557
Popular Tags