KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > iapi > types > UserType


1 /*
2
3    Derby - Class org.apache.derby.iapi.types.UserType
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to you under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derby.iapi.types;
23
24 import org.apache.derby.catalog.TypeDescriptor;
25
26 import org.apache.derby.iapi.reference.SQLState;
27
28 import org.apache.derby.iapi.services.io.ArrayInputStream;
29
30 import org.apache.derby.iapi.services.loader.ClassInspector;
31 import org.apache.derby.iapi.services.sanity.SanityManager;
32 import org.apache.derby.iapi.services.io.StoredFormatIds;
33
34 import org.apache.derby.iapi.error.StandardException;
35
36 import org.apache.derby.iapi.types.DataValueDescriptor;
37 import org.apache.derby.iapi.types.TypeId;
38
39 import org.apache.derby.iapi.types.BooleanDataValue;
40 import org.apache.derby.iapi.types.UserDataValue;
41
42 import org.apache.derby.iapi.services.cache.ClassSize;
43
44 import java.sql.Date JavaDoc;
45 import java.sql.Time JavaDoc;
46 import java.sql.Timestamp JavaDoc;
47
48 import java.io.ObjectOutput JavaDoc;
49 import java.io.ObjectInput JavaDoc;
50 import java.io.IOException JavaDoc;
51
52 import java.sql.ResultSet JavaDoc;
53 import java.sql.SQLException JavaDoc;
54
55 import java.util.Calendar JavaDoc;
56
57
58 /**
59  * This contains an instance of a user-defined type, that is, a java object.
60  *
61  */

62
63 public class UserType extends DataType
64                         implements UserDataValue
65 {
66     private Object JavaDoc value;
67
68     /*
69     ** DataValueDescriptor interface
70     ** (mostly implemented in DataType)
71     */

72
73     private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( UserType.class);
74
75     public int estimateMemoryUsage()
76     {
77         int sz = BASE_MEMORY_USAGE;
78         if( null != value)
79         {
80             // Probably an underestimate. Examining each field value would be expensive
81
// and would produce an overestimate when fields reference shared objects
82
sz += ClassSize.estimateAndCatalogBase( value.getClass());
83         }
84         
85         return sz;
86     } // end of estimateMemoryUsage
87

88     public String JavaDoc getString()
89     {
90         if (! isNull())
91         {
92             return value.toString();
93
94         }
95         else
96         {
97             return null;
98         }
99     }
100
101     /**
102      * @exception StandardException thrown on failure to convert
103      */

104     public boolean getBoolean() throws StandardException
105     {
106         if (! isNull())
107             if (value instanceof Boolean JavaDoc) return ((Boolean JavaDoc)value).booleanValue();
108         return super.getBoolean();
109     }
110
111     /**
112      * @exception StandardException thrown on failure to convert
113      */

114     public byte getByte() throws StandardException
115     {
116         if (! isNull())
117             // REMIND: check for overflow and truncation
118
if (value instanceof Number JavaDoc) return ((Number JavaDoc)value).byteValue();
119         return super.getByte();
120     }
121
122     /**
123      * @exception StandardException thrown on failure to convert
124      */

125     public short getShort() throws StandardException
126     {
127         if (! isNull())
128             // REMIND: check for overflow and truncation
129
if (value instanceof Number JavaDoc) return ((Number JavaDoc)value).shortValue();
130         return super.getShort();
131     }
132
133     /**
134      * @exception StandardException thrown on failure to convert
135      */

136     public int getInt() throws StandardException
137     {
138         if (! isNull())
139             // REMIND: check for overflow and truncation
140
if (value instanceof Number JavaDoc) return ((Number JavaDoc)value).intValue();
141         return super.getInt();
142     }
143
144     /**
145      * @exception StandardException thrown on failure to convert
146      */

147
148     public long getLong() throws StandardException
149     {
150         if (! isNull())
151             // REMIND: check for overflow and truncation
152
if (value instanceof Number JavaDoc) return ((Number JavaDoc)value).longValue();
153         return super.getLong();
154     }
155
156
157     /**
158      * @exception StandardException thrown on failure to convert
159      */

160     public float getFloat() throws StandardException
161     {
162         if (! isNull())
163             // REMIND: check for overflow
164
if (value instanceof Number JavaDoc) return ((Number JavaDoc)value).floatValue();
165         return super.getFloat();
166     }
167
168
169     /**
170      * @exception StandardException thrown on failure to convert
171      */

172     public double getDouble() throws StandardException
173     {
174         if (! isNull())
175             // REMIND: check for overflow
176
if (value instanceof Number JavaDoc) return ((Number JavaDoc)value).doubleValue();
177         return super.getDouble();
178     }
179
180     /**
181      * @exception StandardException thrown on failure to convert
182      */

183     public byte[] getBytes() throws StandardException
184     {
185         if (! isNull())
186             if (value instanceof byte[]) return ((byte[])value);
187         return super.getBytes();
188     }
189
190     /**
191
192         @exception StandardException thrown on failure
193      */

194     public Date JavaDoc getDate( Calendar JavaDoc cal) throws StandardException
195     {
196         if (! isNull())
197         {
198             if (value instanceof Date JavaDoc)
199                 return ((Date JavaDoc)value);
200             else if (value instanceof Timestamp JavaDoc)
201                 return (new SQLTimestamp((Timestamp JavaDoc)value).getDate(cal));
202         }
203         return super.getDate(cal);
204     }
205
206     /**
207         @exception StandardException thrown on failure
208      */

209     public Time JavaDoc getTime( Calendar JavaDoc cal) throws StandardException
210     {
211         if (! isNull())
212         {
213             if (value instanceof Time JavaDoc)
214                 return ((Time JavaDoc)value);
215             else if (value instanceof Timestamp JavaDoc)
216                 return (new SQLTimestamp((Timestamp JavaDoc)value).getTime(cal));
217         }
218         return super.getTime(cal);
219     }
220
221     /**
222         @exception StandardException thrown on failure
223      */

224     public Timestamp JavaDoc getTimestamp( Calendar JavaDoc cal) throws StandardException
225     {
226         if (! isNull())
227         {
228             if (value instanceof Timestamp JavaDoc)
229                 return ((Timestamp JavaDoc)value);
230             else if (value instanceof Date JavaDoc)
231                 return (new SQLDate((Date JavaDoc)value).getTimestamp(cal));
232             else if (value instanceof Time JavaDoc)
233                 return (new SQLTime((Time JavaDoc)value).getTimestamp(cal));
234         }
235         return super.getTimestamp(cal);
236     }
237
238     public Object JavaDoc getObject()
239     {
240         return value;
241     }
242         
243     public int getLength()
244     {
245         return TypeDescriptor.MAXIMUM_WIDTH_UNKNOWN;
246     }
247
248     /* this is for DataType's error generator */
249     public String JavaDoc getTypeName()
250     {
251
252         return isNull() ? "JAVA_OBJECT" : ClassInspector.readableClassName(value.getClass());
253     }
254     
255     /**
256      * Get the type name of this value, overriding
257      * with the passed in class name (for user/java types).
258      */

259     String JavaDoc getTypeName(String JavaDoc className)
260     {
261         return className;
262     }
263
264     /*
265      * Storable interface, implies Externalizable, TypedFormat
266      */

267
268     /**
269         Return my format identifier.
270
271         @see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId
272     */

273     public int getTypeFormatId() {
274         return StoredFormatIds.SQL_USERTYPE_ID_V3;
275     }
276
277     /**
278         @exception IOException error writing data
279
280     */

281     public void writeExternal(ObjectOutput JavaDoc out) throws IOException JavaDoc {
282
283         if (SanityManager.DEBUG)
284             SanityManager.ASSERT(!isNull(), "writeExternal() is not supposed to be called for null values.");
285
286             out.writeObject(value);
287     }
288
289     /**
290      * @see java.io.Externalizable#readExternal
291      *
292      * @exception IOException Thrown on error reading the object
293      * @exception ClassNotFoundException Thrown if the class of the object
294      * is not found
295      */

296     public void readExternal(ObjectInput JavaDoc in)
297         throws IOException JavaDoc, ClassNotFoundException JavaDoc
298     {
299         /* RESOLVE: Sanity check for right class */
300         value = in.readObject();
301     }
302     public void readExternalFromArray(ArrayInputStream in)
303         throws IOException JavaDoc, ClassNotFoundException JavaDoc
304     {
305         /* RESOLVE: Sanity check for right class */
306         value = in.readObject();
307     }
308
309     /*
310      * DataValueDescriptor interface
311      */

312
313     /** @see DataValueDescriptor#getClone */
314     public DataValueDescriptor getClone()
315     {
316         // Call constructor with all of our info
317
return new UserType(value);
318     }
319
320     /**
321      * @see DataValueDescriptor#getNewNull
322      */

323     public DataValueDescriptor getNewNull()
324     {
325         return new UserType();
326     }
327     /**
328      * @see org.apache.derby.iapi.services.io.Storable#restoreToNull
329      *
330      */

331
332     public void restoreToNull()
333     {
334         value = null;
335     }
336
337     /*
338      * DataValueDescriptor interface
339      */

340
341     /**
342      * @see DataValueDescriptor#setValueFromResultSet
343      *
344      * @exception SQLException Thrown on error
345      */

346     public void setValueFromResultSet(ResultSet JavaDoc resultSet, int colNumber,
347                                       boolean isNullable)
348         throws SQLException JavaDoc
349     {
350             value = resultSet.getObject(colNumber);
351     }
352
353     /**
354      * Orderable interface
355      *
356      *
357      * @see org.apache.derby.iapi.types.Orderable
358      *
359      * @exception StandardException thrown on failure
360      */

361     public int compare(DataValueDescriptor other)
362         throws StandardException
363     {
364         /* Use compare method from dominant type, negating result
365          * to reflect flipping of sides.
366          */

367         if (typePrecedence() < other.typePrecedence())
368         {
369             return - (other.compare(this));
370         }
371
372         boolean thisNull, otherNull;
373
374         thisNull = this.isNull();
375         otherNull = other.isNull();
376
377         /*
378          * thisNull otherNull return
379          * T T 0 (this == other)
380          * F T -1 (this < other)
381          * T F 1 (this > other)
382          */

383         if (thisNull || otherNull)
384         {
385             if (!thisNull) // otherNull must be true
386
return -1;
387             if (!otherNull) // thisNull must be true
388
return 1;
389             return 0;
390         }
391
392         /*
393             Neither are null compare them
394          */

395
396         int comparison;
397
398         try
399         {
400             comparison = ((java.lang.Comparable JavaDoc) value).compareTo(other.getObject());
401         }
402         catch (ClassCastException JavaDoc cce)
403         {
404             throw StandardException.newException(SQLState.LANG_INVALID_COMPARE_TO,
405                         getTypeName(),
406                         ClassInspector.readableClassName(other.getObject().getClass()));
407         }
408         /*
409         ** compareTo() can return any negative number if less than, and
410         ** any positive number if greater than. Change to -1, 0, 1.
411         */

412         if (comparison < 0)
413             comparison = -1;
414         else if (comparison > 0)
415             comparison = 1;
416
417         return comparison;
418     }
419
420     /**
421         @exception StandardException thrown on error
422      */

423     public boolean compare(int op,
424                            DataValueDescriptor other,
425                            boolean orderedNulls,
426                            boolean unknownRV)
427         throws StandardException
428     {
429         if (!orderedNulls) // nulls are unordered
430
{
431             if (this.isNull() || other.isNull())
432                 return unknownRV;
433         }
434
435         /* For usertypes and equal do some special processing when
436          * neither value is null. (Superclass will handle comparison
437          * if either value is null.)
438          */

439         if ( (op == ORDER_OP_EQUALS) &&
440             (! this.isNull()) && (! other.isNull()) )
441         {
442             // if this object implements java.lang.Comparable (JDK1.2)
443
// then we let the compareTo method handle equality
444
// if it doesn't then we use the equals() method
445
Object JavaDoc o = getObject();
446
447             if (!(o instanceof java.lang.Comparable JavaDoc))
448             {
449                 return o.equals(other.getObject());
450             }
451         }
452         
453
454         /* Do the comparison */
455         return super.compare(op, other, orderedNulls, unknownRV);
456     }
457
458     /*
459     ** Class interface
460     */

461
462     /*
463     ** Constructors
464     */

465
466     /** no-arg constructor required by Formattable */
467     public UserType() { }
468
469     public UserType(Object JavaDoc value)
470     {
471         this.value = value;
472     }
473     /**
474      * @see UserDataValue#setValue
475      *
476      */

477     public void setValue(Object JavaDoc value)
478     {
479         this.value = value;
480     }
481     protected void setFrom(DataValueDescriptor theValue) throws StandardException {
482
483         setValue(theValue.getObject());
484     }
485
486     /**
487      * @see UserDataValue#setValue
488      *
489      */

490     public void setBigDecimal(Number JavaDoc theValue)
491     {
492         // needed to allow serializable BigDecimal
493
setValue((Object JavaDoc) theValue);
494     }
495
496     public void setValue(String JavaDoc theValue)
497     {
498         if (theValue == null)
499         {
500             value = null;
501         }
502         else
503         {
504             // Higher levels must have performed type checking for us.
505
value = theValue;
506         }
507     }
508
509     /*
510     ** SQL Operators
511     */

512
513     /**
514      * The = operator as called from the language module, as opposed to
515      * the storage module.
516      *
517      * @param left The value on the left side of the =
518      * @param right The value on the right side of the =
519      *
520      * @return A SQL boolean value telling whether the two parameters are equal
521      *
522      * @exception StandardException Thrown on error
523      */

524
525     public BooleanDataValue equals(DataValueDescriptor left,
526                             DataValueDescriptor right)
527             throws StandardException
528     {
529         return SQLBoolean.truthValue(left,
530                                      right,
531                                      left.compare(ORDER_OP_EQUALS, right, true, false));
532     }
533
534     /**
535      * The <> operator as called from the language module, as opposed to
536      * the storage module.
537      *
538      * @param left The value on the left side of the <>
539      * @param right The value on the right side of the <>
540      *
541      * @return A SQL boolean value telling whether the two parameters
542      * are not equal
543      *
544      * @exception StandardException Thrown on error
545      */

546
547     public BooleanDataValue notEquals(DataValueDescriptor left,
548                             DataValueDescriptor right)
549             throws StandardException
550     {
551         return SQLBoolean.truthValue(left,
552                                      right,
553                                      !left.compare(ORDER_OP_EQUALS, right, true, false));
554     }
555
556
557
558     /*
559     ** String display of value
560     */

561
562     public String JavaDoc toString()
563     {
564         if (isNull())
565         {
566             return "NULL";
567         }
568         else
569         {
570             return value.toString();
571         }
572     }
573
574     /*
575      * Hash code
576      */

577     public int hashCode()
578     {
579         if (isNull())
580             return 0;
581         return value.hashCode();
582     }
583
584     /** @see DataValueDescriptor#typePrecedence */
585     public int typePrecedence()
586     {
587         return TypeId.USER_PRECEDENCE;
588     }
589
590     /**
591      * Check if the value is null.
592      *
593      * @return Whether or not value is logically null.
594      */

595     public final boolean isNull()
596     {
597         return (value == null);
598     }
599 }
600
601
Popular Tags