KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > dataobjs > DBPersist


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/O�a, 107 1�2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.dataobjs;
34
35 import java.io.IOException JavaDoc;
36 import java.io.FileNotFoundException JavaDoc;
37 import java.io.File JavaDoc;
38
39 import java.sql.SQLException JavaDoc;
40 import java.sql.CallableStatement JavaDoc;
41 import java.sql.PreparedStatement JavaDoc;
42 import java.sql.ResultSet JavaDoc;
43 import java.sql.Time JavaDoc;
44 import java.sql.Timestamp JavaDoc;
45
46 import java.lang.ClassNotFoundException JavaDoc;
47 import java.lang.IllegalAccessException JavaDoc;
48 import java.lang.InstantiationException JavaDoc;
49
50 import java.util.Date JavaDoc;
51 import java.util.Map JavaDoc;
52 import java.util.Collection JavaDoc;
53 import java.util.ArrayList JavaDoc;
54 import java.util.HashMap JavaDoc;
55 import java.util.Iterator JavaDoc;
56 import java.util.LinkedList JavaDoc;
57 import java.util.ListIterator JavaDoc;
58 import java.util.Set JavaDoc;
59 import java.util.Properties JavaDoc;
60
61 import java.math.BigDecimal JavaDoc;
62
63 import java.text.ParseException JavaDoc;
64 import java.text.SimpleDateFormat JavaDoc;
65 import java.text.DecimalFormat JavaDoc;
66 import java.text.DecimalFormatSymbols JavaDoc;
67
68 import org.xml.sax.SAXException JavaDoc;
69 import org.xml.sax.SAXNotRecognizedException JavaDoc;
70 import org.xml.sax.SAXNotSupportedException JavaDoc;
71 import org.xml.sax.SAXParseException JavaDoc;
72
73 import com.knowgate.debug.*;
74 import com.knowgate.jdc.*;
75 import com.knowgate.math.Money;
76 import com.knowgate.misc.Gadgets;
77
78 /**
79  * <p>Core class for persisting Java objects as registers in a RDMS.<p>
80  * <p>Althought not an abstract class, DBPersist is mainly designed to be inherited
81  * by a child class implementing specific behavior for reading a writting a Java
82  * object from and to a relational database.</p>
83  * <p>DBPersist mantains an internal collection of values each one mapped to a database field.</p>
84  * This mapping is done automatically by DBPersist reading the target table metadata definition
85  * and preparing the proper internal value set.</p>
86  * <p>This object keeps the internal value set in memory as long as it is not garbage collected,
87  * but it does not mantaing any session information nor transaction management with the database.
88  * It is the programmer's responsability to pass an open database connection on each method call
89  * and to commit or rollback transaction involving the usage of a DBPersist object.
90  * @author Sergio Montoro Ten
91  * @version 3.0
92  */

93
94 public class DBPersist implements Map JavaDoc {
95
96   /**
97    * Create instance for reading and writing register from a table
98    * @param sTable Database table name for storing objects.
99    * @param sAuditClass Name of child Java class inheriting from DBPersist.
100    * @throws IllegalStateException
101   */

102
103   public DBPersist (String JavaDoc sTableName, String JavaDoc sAuditClass)
104     throws IllegalStateException JavaDoc {
105
106     sTable = sTableName;
107
108     sAuditCls = sAuditClass;
109     sAuditUsr = "";
110     sTransactId = "";
111     bAllCaps = bHasLongVarBinaryData = false;
112     AllVals = new HashMap JavaDoc();
113   }
114
115   /**
116    * Create instance for reading and writing register from a table
117    * @param sTable Database table name for storing objects.
118    * @param sAuditClass Name of child Java class inheriting from DBPersist.
119    * @param bAllValuesUpperCase Convert all put string values to uppercase
120    * @throws IllegalStateException
121    * @since 3.0
122   */

123
124   public DBPersist (String JavaDoc sTableName, String JavaDoc sAuditClass, boolean bAllValuesUpperCase)
125     throws IllegalStateException JavaDoc {
126
127     sTable = sTableName;
128
129     sAuditCls = sAuditClass;
130     sAuditUsr = "";
131     sTransactId = "";
132     bAllCaps = bAllValuesUpperCase;
133     bHasLongVarBinaryData = false;
134     AllVals = new HashMap JavaDoc();
135   }
136
137   /**
138    * Automatically convert put string values to uppercase
139    * @param bAllValuesUpperCase boolean
140    * @since 3.0
141    */

142   public void allcaps(boolean bAllValuesUpperCase) {
143     bAllCaps = bAllValuesUpperCase;
144   }
145
146   /**
147    * Get allcaps state
148    * @return boolean
149    * @since 3.0
150    */

151   public boolean allcaps() {
152     return bAllCaps;
153   }
154
155   /**
156    * Set user id for automatic operation auditing.
157    */

158   public void setAuditUser (String JavaDoc sAuditUser) {
159     sAuditUsr = sAuditUser;
160   }
161
162   /**
163    * Set transaction id for automatic operation auditing.
164    */

165
166   public void setAuditTransact (String JavaDoc sAuditTransact) {
167     sTransactId = sAuditTransact;
168   }
169
170   /**
171    * Returns whether or not this DBPersist contains no field values
172    * @return boolean
173    */

174   public boolean isEmpty() {
175     return AllVals.isEmpty();
176   }
177
178   /**
179    * Actual number of field values on this DBPersist
180    * @return int
181    */

182   public int size() {
183     return AllVals.size();
184   }
185
186   /**
187    * <p>Clears internal values.</p>
188    * <p>No register is deleted at the database.</p>
189    */

190   public void clear() {
191     AllVals.clear();
192   }
193
194   /**
195    * <p>Copy another DBPersist into this instance</p>
196    * Table and audit class values are replaced with to ones from source object
197    * @param oSource Source Object
198    * @since 2.2
199    */

200   public void clone(DBPersist oSource) {
201     sTable = oSource.getTableName();
202     sAuditCls = oSource.getAuditClassName();
203     AllVals = new HashMap JavaDoc(oSource.AllVals);
204   }
205
206   /**
207    * Returns true if any of this DBPersist fields has the specified value.
208    * @param oKey Object whose presence in this map is to be tested
209    * @return boolean
210    * @since 2.2
211    */

212   public boolean containsValue(Object JavaDoc oKey) {
213     return AllVals.containsValue(oKey);
214   }
215
216   /**
217    * Returns true if this DBPersist contains a field for the given name
218    * @param oKey Field Name
219    * @return boolean
220    * @throws NullPointerException If oKey is <b>null</b>
221    * @since 2.2
222    */

223   public boolean containsKey(Object JavaDoc oKey)
224     throws NullPointerException JavaDoc {
225     if (oKey==null) throw new NullPointerException JavaDoc("DBPersist.containsKey() field name cannot be null");
226     return AllVals.containsKey(oKey);
227   }
228
229   /**
230    * <p>Get value for a field name</p>
231    * @param sKey String Field Name
232    * @return Field value. If field is <b>null</b> or DBPersist has not been loaded,
233    * or no field with given name exists at table, get() returns <b>null</b>.
234    */

235
236   public Object JavaDoc get(String JavaDoc sKey) {
237     return AllVals.get(sKey);
238   }
239
240   /**
241    * Get dt_created column of register corresponding to this DBPersist instace
242    * @param oConn JDCConnection
243    * @return Date or <b>null</b> if no data is found
244    * @throws SQLException If table for this DBPersist does not have a column named dt_created
245    */

246   public Date JavaDoc getCreationDate(JDCConnection oConn) throws SQLException JavaDoc {
247     Date JavaDoc oDt;
248     ResultSet JavaDoc oRSet = null;
249     PreparedStatement JavaDoc oStmt = null;
250     DBTable oTbl = getTable(oConn);
251     LinkedList JavaDoc oList = oTbl.getPrimaryKey();
252     ListIterator JavaDoc oIter;
253     String JavaDoc sSQL = "SELECT "+DB.dt_created+" FROM "+oTbl.getName()+" WHERE 1=1";
254     oIter = oList.listIterator();
255     while (oIter.hasNext())
256       sSQL += " AND " + oIter.next() + "=?";
257     try {
258     oStmt = oConn.prepareStatement(sSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
259     int p=0;
260     oIter = oList.listIterator();
261     while (oIter.hasNext())
262       oStmt.setObject(++p, get(oIter.next()));
263     oRSet = oStmt.executeQuery();
264     if (oRSet.next())
265       oDt = oRSet.getDate(1);
266     else
267       oDt = null;
268     oRSet.close();
269     oRSet=null;
270     oStmt.close();
271     oStmt=null;
272     } catch (Exception JavaDoc xcpt) {
273       if (null!=oRSet) { try { oRSet.close(); } catch (Exception JavaDoc ignore) { /* ignore */ } }
274       if (null!=oStmt) { try { oStmt.close(); } catch (Exception JavaDoc ignore) { /* ignore */ } }
275       throw new SQLException JavaDoc ("DBPersist.getCreationDate() "+xcpt.getClass().getName()+" "+xcpt.getMessage());
276     }
277     return oDt;
278   } // getCreationDate
279

280   /**
281    * <p>Get value for a field name</p>
282    * @param sKey String Field Name
283    * @return Field value. If field is <b>null</b> or DBPersist has not been loaded,
284    * or no field with given name exists at table, get() returns <b>null</b>.
285    * @throws NullPointerException If oKey is <b>null</b>
286    * @since 2.2
287    */

288
289   public Object JavaDoc get(Object JavaDoc oKey) throws NullPointerException JavaDoc {
290     if (oKey==null) throw new NullPointerException JavaDoc("DBPersist.get() field name cannot be null");
291     return AllVals.get(oKey);
292   }
293
294   /**
295    * <p>Get value for a DECIMAL or NUMERIC field<p>
296    * @param sKey Field Name
297    * @return Field value or <b>null</b>.
298    * @throws java.lang.ClassCastException
299    * @throws java.lang.NumberFormatException
300    */

301
302   public BigDecimal JavaDoc getDecimal(String JavaDoc sKey)
303     throws ClassCastException JavaDoc, NumberFormatException JavaDoc {
304
305     Object JavaDoc oDec = AllVals.get(sKey);
306
307     if (oDec==null)
308       return null;
309     else {
310       if (oDec.getClass().getName().equalsIgnoreCase("java.lang.String"))
311         return new BigDecimal JavaDoc((String JavaDoc) oDec);
312       else
313         return (BigDecimal JavaDoc) oDec;
314     }
315   } // getDecimal
316

317
318   /**
319    * <p>Get decimal formated as a String using the given pattern and the symbols for the default locale</p>
320    * @param sKey Field Name
321    * @param sPattern A non-localized pattern string, for example: "#0.00"
322    * @return String decimal value formated according to sPatern or <b>null</b>
323    * @throws ClassCastException
324    * @throws NumberFormatException
325    * @throws NullPointerException if sPattern is <b>null</b>
326    * @throws IllegalArgumentException if sPattern is invalid
327    */

328   public String JavaDoc getDecimalFormated(String JavaDoc sKey, String JavaDoc sPattern)
329     throws ClassCastException JavaDoc, NumberFormatException JavaDoc,NullPointerException JavaDoc,
330            IllegalArgumentException JavaDoc {
331
332     BigDecimal JavaDoc oDec = getDecimal(sKey);
333
334     if (oDec==null)
335       return null;
336     else {
337       return new DecimalFormat JavaDoc(sPattern).format(oDec.doubleValue());
338     }
339   } // getDecimalFormated
340

341   /**
342    * <p>Get double formated as a String using the given pattern and the symbols for the default locale</p>
343    * @param sKey Field Name
344    * @param sPattern A non-localized pattern string, for example: "#0.00"
345    * @return String decimal value formated according to sPatern or <b>null</b>
346    * @throws ClassCastException
347    * @throws NumberFormatException
348    * @throws NullPointerException
349    * @throws IllegalArgumentException
350    */

351   public String JavaDoc getDoubleFormated(String JavaDoc sKey, String JavaDoc sPattern)
352       throws ClassCastException JavaDoc, NumberFormatException JavaDoc,NullPointerException JavaDoc,
353              IllegalArgumentException JavaDoc {
354     if (isNull(sKey))
355         return null;
356       else
357         return new DecimalFormat JavaDoc(sPattern).format(getDouble(sKey));
358   }
359
360   /**
361    * <p>Get float formated as a String using the given pattern and the symbols for the default locale</p>
362    * @param sKey Field Name
363    * @param sPattern A non-localized pattern string, for example: "#0.00"
364    * @return String decimal value formated according to sPatern or <b>null</b>
365    * @throws ClassCastException
366    * @throws NumberFormatException
367    * @throws NullPointerException
368    * @throws IllegalArgumentException
369    */

370   public String JavaDoc getFloatFormated(String JavaDoc sKey, String JavaDoc sPattern)
371     throws ClassCastException JavaDoc, NumberFormatException JavaDoc,NullPointerException JavaDoc,
372            IllegalArgumentException JavaDoc {
373     if (isNull(sKey))
374       return null;
375     else
376       return new DecimalFormat JavaDoc(sPattern).format(getFloat(sKey));
377   }
378
379   /**
380    * <p>Get value of a VARCHAR field that holds a money+currency amount<p>
381    * Money values are stored with its currency sign embedded inside,
382    * like "26.32 USD" or "$48.3" or "35.44 �"
383    * @param sKey Field Name
384    * @return com.knowgate.math.Money
385    * @throws NumberFormatException
386    * @since 3.0
387    */

388   public Money getMoney(String JavaDoc sKey)
389     throws NumberFormatException JavaDoc {
390     Object JavaDoc oVal = AllVals.get(sKey);
391     if (null!=oVal)
392       if (oVal.toString().length()>0)
393         return Money.parse(oVal.toString());
394       else
395         return null;
396     else
397       return null;
398   } // getMoney
399

400   /**
401    * <p>Get value for a CHAR, VARCHAR or LONGVARCHAR field<p>
402    * @param sKey Field Name
403    * @return Field value or <b>null</b>.
404    * @throws NullPointerException if field is <b>null</b> or no field with
405    * such name was found at internal value collection.
406    */

407   public String JavaDoc getString(String JavaDoc sKey) throws NullPointerException JavaDoc {
408     return AllVals.get(sKey).toString();
409   }
410
411   /**
412    * <p>Get value for a CHAR, VARCHAR or LONGVARCHAR field replacing <b>null</b>
413    * with a default value.<p>
414    * @param sKey Field Name
415    * @param sDefault Value to be returned if field is null. sDefault may itself
416    * be <b>null</b>, provinding a null safe version of getString() method.
417    * @return Field value or default value.
418    */

419
420   public String JavaDoc getStringNull(String JavaDoc sKey, String JavaDoc sDefault) {
421     Object JavaDoc oVal;
422     if (AllVals.containsKey(sKey)) {
423       oVal = AllVals.get(sKey);
424       if (null==oVal)
425         return sDefault;
426       else
427         return oVal.toString();
428     }
429     else
430       return sDefault;
431   }
432
433   /**
434    * <p>Get value for SQL92 TIME field</p>
435    * @param sKey Field Name
436    * @return java.sql.Time
437    * @since 3.0
438    */

439   public Time JavaDoc getTimeOfDay(String JavaDoc sKey) {
440     Object JavaDoc oTm = AllVals.get(sKey);
441     if (null!=oTm)
442       return (Time JavaDoc) oTm;
443     else
444       return null;
445   } // getTimeOfDay
446

447   /**
448    * <p>Get value for a SMALLINT field<p>
449    * @param sKey Field Name
450    * @return Field value.
451    * @throws NullPointerException if field is <b>null</b> or no field with
452    * such name was found at internal value collection.
453    */

454
455   public short getShort(String JavaDoc sKey) throws java.lang.NullPointerException JavaDoc {
456     Object JavaDoc oVal = AllVals.get(sKey);
457
458     if (oVal==null) throw new NullPointerException JavaDoc(sKey + " is null");
459
460     return Short.parseShort(oVal.toString());
461   }
462
463   /**
464    * <p>Get value for a DOUBLE or NUMBER([1..28],m) field<p>
465    * @param sKey Field Name
466    * @return Field value.
467    * @throws NullPointerException if field is <b>null</b> or no field with
468    * such name was found at internal value collection.
469    * @throws NumberFormatException
470    */

471
472   public double getDouble(String JavaDoc sKey)
473     throws NullPointerException JavaDoc, NumberFormatException JavaDoc {
474     Object JavaDoc oVal = AllVals.get(sKey);
475     Class JavaDoc oCls;
476     double dRetVal;
477
478     if (oVal==null) throw new NullPointerException JavaDoc(sKey + " is null");
479
480     oCls = oVal.getClass();
481
482     try {
483       if (oCls.equals(Short.TYPE))
484         dRetVal = (double) ((Short JavaDoc) oVal).shortValue();
485       else if (oCls.equals(Integer.TYPE))
486         dRetVal = (double) ((Integer JavaDoc) oVal).intValue();
487       else if (oCls.equals(Class.forName("java.math.BigDecimal")))
488         dRetVal = ((java.math.BigDecimal JavaDoc) oVal).doubleValue();
489       else if (oCls.equals(Float.TYPE))
490         dRetVal = ((Float JavaDoc) oVal).floatValue();
491       else if (oCls.equals(Double.TYPE))
492         dRetVal = ((Double JavaDoc) oVal).doubleValue();
493       else
494         dRetVal = new Double JavaDoc(oVal.toString()).floatValue();
495     } catch (ClassNotFoundException JavaDoc cnfe) { /* never thrown */ dRetVal = 0d; }
496
497     return dRetVal;
498   } // getDouble
499

500   /**
501    * <p>Get value for a FLOAT or NUMBER([1..28],m) field<p>
502    * @param sKey Field Name
503    * @return Field value.
504    * @throws NullPointerException if field is <b>null</b> or no field with
505    * such name was found at internal value collection.
506    * @throws NumberFormatException
507    */

508
509   public float getFloat(String JavaDoc sKey)
510     throws NullPointerException JavaDoc, NumberFormatException JavaDoc {
511     Object JavaDoc oVal = AllVals.get(sKey);
512     Class JavaDoc oCls;
513     float fRetVal;
514
515     if (oVal==null) throw new NullPointerException JavaDoc(sKey + " is null");
516
517     oCls = oVal.getClass();
518
519     try {
520       if (oCls.equals(Short.TYPE))
521         fRetVal = (float) ((Short JavaDoc) oVal).shortValue();
522       else if (oCls.equals(Integer.TYPE))
523         fRetVal = (float) ((Integer JavaDoc) oVal).intValue();
524       else if (oCls.equals(Class.forName("java.math.BigDecimal")))
525         fRetVal = ((java.math.BigDecimal JavaDoc) oVal).floatValue();
526       else if (oCls.equals(Float.TYPE))
527         fRetVal = ((Float JavaDoc) oVal).floatValue();
528       else if (oCls.equals(Double.TYPE))
529         fRetVal = ((Double JavaDoc) oVal).floatValue();
530       else
531         fRetVal = new Float JavaDoc(oVal.toString()).floatValue();
532     } catch (ClassNotFoundException JavaDoc cnfe) { /* never thrown */ fRetVal = 0f; }
533
534     return fRetVal;
535
536   } // getFloat
537

538   /**
539    * <p>Get value for a INTEGER or NUMBER([1..11]) field<p>
540    * @param sKey Field Name
541    * @return Field value.
542    * @throws NullPointerException if field is <b>null</b> or no field with
543    * such name was found at internal value collection.
544    * @throws NumberFormatException
545    */

546
547   public int getInt(String JavaDoc sKey)
548     throws NullPointerException JavaDoc, NumberFormatException JavaDoc {
549     int iRetVal;
550     Object JavaDoc oInt = AllVals.get(sKey);
551
552     if (Integer.TYPE.equals(oInt.getClass()))
553       iRetVal = ((Integer JavaDoc)(oInt)).intValue();
554     else
555       iRetVal = Integer.parseInt(oInt.toString());
556
557     return iRetVal;
558   } // getInt
559

560   /**
561    * <p>Get value for a INTEGER or NUMBER([1..11]) field<p>
562    * @param sKey Field Name
563    * @return Field value or <b>null</b>.
564    * @throws NumberFormatException
565    */

566
567   public Integer JavaDoc getInteger(String JavaDoc sKey) throws NumberFormatException JavaDoc {
568     Object JavaDoc oInt = AllVals.get(sKey);
569
570     if (null!=oInt)
571       if (Integer.TYPE.equals(oInt.getClass()))
572         return (Integer JavaDoc) oInt;
573       else
574         return new Integer JavaDoc(oInt.toString());
575     else
576       return null;
577   } // getInteger
578

579   /**
580    * <p>Get value for a DATE field<p>
581    * @param sKey Field Name
582    * @return Field value or <b>null</b>.
583    * @throws ClassCastException if sKey field is not of type DATE
584    */

585
586   public Date JavaDoc getDate(String JavaDoc sKey) throws ClassCastException JavaDoc {
587     Object JavaDoc oDt = AllVals.get(sKey);
588     if (null!=oDt)
589       return (Date JavaDoc) oDt;
590     else
591       return null;
592   } // getDate
593

594   /**
595    * <p>Get DATE formated as ccyy-MM-dd<p>
596    * @param sKey Field Name
597    * @throws ClassCastException if sKey field is not of type DATE
598    * @return String value for Date or <b>null</b>.
599    */

600
601   public String JavaDoc getDateShort(String JavaDoc sKey)
602     throws ClassCastException JavaDoc {
603     Object JavaDoc oDt = AllVals.get(sKey);
604     if (null!=oDt) {
605       java.util.Date JavaDoc dDt = (java.util.Date JavaDoc) oDt;
606       int y = dDt.getYear()+1900, m=dDt.getMonth()+1, d=dDt.getDate();
607       return String.valueOf(y)+"-"+(m<10 ? "0" : "")+String.valueOf(m)+"-"+(d<10 ? "0" : "")+String.valueOf(d);
608     }
609     else
610       return null;
611   } // getDate
612

613   /**
614    * <p>Get value for a DATE, DATETIME or TIMESTAMP field formated a String<p>
615    * @param sKey Field Name
616    * @param sFormat Date Format (like "yyyy-MM-dd HH:mm:ss")
617    * @return Formated date or <b>null</b>.
618    * @throws ClassCastException if sKey field is not of type DATE, DATETIME or TIMESTAMP
619    * @see java.text.SimpleDateFormat
620    */

621
622   public String JavaDoc getDateFormated(String JavaDoc sKey, String JavaDoc sFormat)
623     throws ClassCastException JavaDoc {
624     Object JavaDoc oDt = AllVals.get(sKey);
625     SimpleDateFormat JavaDoc oSimpleDate;
626
627     if (null!=oDt) {
628       oSimpleDate = new SimpleDateFormat JavaDoc(sFormat);
629       return oSimpleDate.format((java.util.Date JavaDoc) oDt);
630     }
631     else
632       return null;
633   } // getDateFormated()
634

635   /**
636    * <p>Get value for a DATE, DATETIME or TIMESTAMP field formated a yyyy-MM-dd hh:mm:ss<p>
637    * @param sKey String Field Name
638    * @return String Formated date or <b>null</b>.
639    * @throws ClassCastException if sKey field is not of type DATE
640    * @since 3.0
641    */

642   public String JavaDoc getDateTime(String JavaDoc sKey) {
643     return getDateFormated(sKey, "yyyy-MM-dd hh:mm:ss");
644   } // getDateTime
645

646   /**
647    * <p>Get value for a DATE, DATETIME or TIMESTAMP field formated a yyyy-MM-dd HH:mm:ss<p>
648    * @param sKey String Field Name
649    * @return String Formated date or <b>null</b>.
650    * @throws ClassCastException if sKey field is not of type DATE, DATETIME or TIMESTAMP
651    * @since 3.0
652    */

653   public String JavaDoc getDateTime24(String JavaDoc sKey) {
654     return getDateFormated(sKey, "yyyy-MM-dd HH:mm:ss");
655   } // getDateTime24()
656

657
658   /**
659    * <p>Get value for a DATE field<p>
660    * @param sKey Field Name
661    * @return java.sql.Date
662    * @throws ClassCastException if sKey field is not of type DATE, DATETIME or TIMESTAMP
663    * @since 3.0
664    */

665   public java.sql.Date JavaDoc getSQLDate(String JavaDoc sKey)
666     throws ClassCastException JavaDoc {
667     java.sql.Date JavaDoc oRetVal;
668     Object JavaDoc oObj = AllVals.get(sKey);
669
670     if (oObj==null) {
671       oRetVal = null;
672     } else {
673       String JavaDoc sCls = oObj.getClass().getName();
674       if (sCls.equals("java.sql.Date"))
675         oRetVal = (java.sql.Date JavaDoc) oObj;
676       else if (sCls.equals("java.util.Date"))
677         oRetVal = new java.sql.Date JavaDoc(((java.util.Date JavaDoc)oObj).getTime());
678       else if (sCls.equals("java.sql.Timestamp"))
679         oRetVal = new java.sql.Date JavaDoc(((java.sql.Timestamp JavaDoc)oObj).getTime());
680       else
681         throw new ClassCastException JavaDoc("DBPersist.getSQLDate() Cannot cast "+sCls+" to java.sql.Date");
682     }
683     return oRetVal;
684   } // getSQLDate
685

686   /**
687    * <p>Get value for a TIME field<p>
688    * @param sKey Field Name
689    * @return java.sql.Time
690    * @throws ClassCastException
691    * @since 3.0
692    */

693   public Time JavaDoc getSQLTime(String JavaDoc sKey)
694     throws ClassCastException JavaDoc {
695     java.sql.Time JavaDoc oRetVal;
696     Object JavaDoc oObj = AllVals.get(sKey);
697
698     if (oObj==null) {
699       oRetVal = null;
700     } else {
701       String JavaDoc sCls = oObj.getClass().getName();
702       if (sCls.equals("java.sql.Time"))
703         oRetVal = (java.sql.Time JavaDoc) oObj;
704       else if (sCls.equals("java.util.Date"))
705         oRetVal = new java.sql.Time JavaDoc(((java.util.Date JavaDoc)oObj).getTime());
706       else if (sCls.equals("java.sql.Timestamp"))
707         oRetVal = new java.sql.Time JavaDoc(((java.sql.Timestamp JavaDoc)oObj).getTime());
708       else
709         throw new ClassCastException JavaDoc("DBPersist.getSQLTime() Cannot cast "+sCls+" to java.sql.Time");
710     }
711     return oRetVal;
712   } // getSQLTime
713

714   /**
715    * <p>Get time part of date as a String</p>
716    * @param sKey Field Name
717    * @return String HH24:MI:SS or <b>null</b>
718    * @throws ClassCastException if sKey field is not of type DATE
719    */

720   public String JavaDoc getTime(String JavaDoc sKey)
721     throws ClassCastException JavaDoc {
722     Object JavaDoc oObj = AllVals.get(sKey);
723
724     if (oObj!=null) {
725       java.util.Date JavaDoc oDt = (java.util.Date JavaDoc) oObj;
726       return (oDt.getHours()<10 ? "0" : "")+String.valueOf(oDt.getHours())+":"+(oDt.getMinutes()<10 ? "0" : "")+String.valueOf(oDt.getMinutes())+(oDt.getSeconds()<10 ? "0" : "")+":"+String.valueOf(oDt.getSeconds());
727     }
728     else {
729       return null;
730     }
731   } // getTime
732

733   /**
734    * <p>Get a part of an interval value</p>
735    * This function only works for PostgreSQL
736    * @param sKey String String Field Name
737    * @param sPart String Currently, only "days" is allowed as interval part
738    * @return int Number of days in the given interval
739    * @throws NullPointerException if interval is <b>null</b>
740    * @throws IllegalArgumentException is sPart is not "days"
741    * @throws NumberFormatException if interval has no days
742    * @since 3.0
743    */

744   public int getIntervalPart(String JavaDoc sKey, String JavaDoc sPart)
745     throws NullPointerException JavaDoc, NumberFormatException JavaDoc, IllegalArgumentException JavaDoc {
746     if (sPart==null) throw new IllegalArgumentException JavaDoc("DBPersist.getIntervalPart() interval part to get cannot be null");
747     if (!sPart.equalsIgnoreCase("days")) throw new IllegalArgumentException JavaDoc("DBPersist.getIntervalPart() interval part to get must be 'days'");
748     Object JavaDoc oObj = AllVals.get(sKey);
749     if (oObj==null) throw new NullPointerException JavaDoc("DBPersist.getIntervalPart() value of interval is null");
750     String JavaDoc sTI = oObj.toString().toLowerCase();
751     int iMons = sTI.indexOf("mons")<0 ? 0 : sTI.indexOf("mons")+4;
752     int iDays = sTI.indexOf("days");
753     if (iDays<0) return 0;
754     return Integer.parseInt(Gadgets.removeChars(sTI.substring(iMons,iDays), " "));
755   } // getIntervalPart
756

757   /**
758    * <p>Get value for a DATETIME or TIMESTAMP field<p>
759    * @param sKey Field Name
760    * @return Field value or <b>null</b>.
761    */

762
763   public Timestamp JavaDoc getTimestamp(String JavaDoc sKey) {
764     Object JavaDoc oDt = AllVals.get(sKey);
765
766     if (null!=oDt)
767       return new Timestamp JavaDoc(((java.util.Date JavaDoc) oDt).getTime());
768     else
769       return null;
770   } // getTimestamp
771

772   /**
773    * @return Field Names Set
774    * @deprecated Use keySet() instead
775    */

776   public Set JavaDoc getItems() {
777     return AllVals.keySet();
778   }
779
780   /**
781    * @return Field Names Set
782    * @since 2.2
783    */

784   public Set JavaDoc keySet() {
785     return AllVals.keySet();
786   }
787
788   /**
789    * @return Values Map
790    */

791   public HashMap JavaDoc getItemMap() {
792     return AllVals;
793   }
794
795   /**
796    * @return Values Collection
797    * @since 2.2
798    */

799   public Collection JavaDoc values() {
800     return AllVals.values();
801   }
802
803   /**
804    * @return Field Values Set
805    * @since 2.2
806    */

807   public Set JavaDoc entrySet() {
808     return AllVals.entrySet();
809   }
810
811   /**
812    * @return Iterator for values stored in-memory at this DBPersist.
813    */

814
815   public Iterator JavaDoc iterator() {
816     return AllVals.values().iterator();
817   }
818
819   /**
820    * Get audit class name
821    * @return Name of base table for this DBPersist
822    */

823
824   public String JavaDoc getAuditClassName() {
825     return sAuditCls;
826   }
827
828   /**
829    * Get base table name
830    * @return Name of base table for this DBPersist
831    */

832
833   public String JavaDoc getTableName() {
834     return sTable;
835   }
836
837   /**
838    * @return {@link DBTable} object where data is stored
839    * or <b>null</b> if the table does not exist at the database.
840    * @deprecated Use {@link #getTable(JDCConnection) getTable(JDCConnection)} instead
841    */

842
843   public DBTable getTable() {
844     if (null==oTable) {
845       oTable = DBBind.getTable(sTable);
846     }
847     return oTable;
848   } // getTable()
849

850   /**
851    * Get DBTable object witch holds this DBPersist registers.
852    * @param oConn JDBC Database Connection
853    * @return {@link DBTable} object where data is stored
854    * or <b>null</b> if the table does not exist at the database.
855    * @throws IllegalStateException DBPersist uses the internal static table map
856    * from DBBind. The internal DBBind table map is loaded upon first call to
857    * a DBBind constructor. Thus, if a DBPersist object is instantiated before
858    * instantiating any DBBind object, the internal table map will not be
859    * preloaded and an IllegalStateException will be raised.
860    * @since 2.0
861    */

862   public DBTable getTable(JDCConnection oConn)
863     throws SQLException JavaDoc, IllegalStateException JavaDoc {
864
865     if (null==oTable) {
866       JDCConnectionPool oPool = oConn.getPool();
867
868       if (null==oPool) {
869         if (oConn.getDataBaseProduct()==JDCConnection.DBMS_POSTGRESQL)
870           oTable = new DBTable(oConn.getCatalog(), null, sTable, 1);
871         else
872           oTable = new DBTable(oConn.getCatalog(), oConn.getSchemaName(), sTable, 1);
873
874         oTable.readColumns(oConn, oConn.getMetaData());
875       }
876       else {
877         DBBind oBind = (DBBind) oPool.getDatabaseBinding();
878
879         if (null==oBind)
880           throw new IllegalStateException JavaDoc("Connection Pool for " + sAuditCls + " is not binded to the database.");
881         else
882          oTable = oBind.getDBTable(sTable);
883       }
884     }
885     return oTable;
886   }
887
888   /**
889    * Test is a readed field was null.
890    * @param sKey Field Name
891    * @return <b>true</b> if readed field was null or if no field with given name
892    * was found at internal collection.
893    */

894
895   public boolean isNull(String JavaDoc sKey) {
896     boolean bIsNull = !AllVals.containsKey(sKey);
897     if (!bIsNull)
898       bIsNull = AllVals.get(sKey)==null;
899     return bIsNull;
900   }
901
902   /**
903    * <p>Load the internal value set from a register at a database table</p>
904    * @param oConn Database Connection
905    * @param PKVals Primary key values in order of appearance
906    * @return <b>true</b> if a register was found, <b>false</b> if no register was
907    * found with such primary key.
908    * @throws SQLException
909    */

910
911   public boolean load(JDCConnection oConn, Object JavaDoc[] PKVals) throws SQLException JavaDoc {
912     if (oTable==null) {
913       oTable = getTable(oConn);
914       if (null==oTable) throw new SQLException JavaDoc("Table not found "+sTable,"42S02", 42002);
915       return oTable.loadRegister(oConn, PKVals, AllVals);
916     } else
917       return oTable.loadRegister(oConn, PKVals, AllVals);
918   }
919
920   /**
921    * <p>Load the internal value set from a register at a database table</p>
922    * @param oConn JDCConnection
923    * @param sKey String Primary key value
924    * @return <b>true</b> if a register was found, <b>false</b> if no register was
925    * found with such primary key.
926    * @throws SQLException
927    * @since 3.0
928    */

929   public boolean load(JDCConnection oConn, String JavaDoc sKey) throws SQLException JavaDoc {
930     if (oTable==null) {
931       oTable = getTable(oConn);
932       if (null==oTable) throw new SQLException JavaDoc("Table not found "+sTable,"42S02", 42002);
933       return oTable.loadRegister(oConn, new Object JavaDoc[]{sKey}, AllVals);
934     } else
935       return oTable.loadRegister(oConn, new Object JavaDoc[]{sKey}, AllVals);
936   }
937
938   /**
939    * <p>Set value at internal collection</p>
940    * If allcaps is set tu <b>true</b> then sVal is converted to uppercase
941    * @param sKey Field Name
942    * @param sVal Field Value
943    * @throws NullPointerException If sKey is <b>null</b>
944   */

945
946   public void put(String JavaDoc sKey, String JavaDoc sVal) throws NullPointerException JavaDoc {
947     if (sKey==null)
948       throw new NullPointerException JavaDoc("DBPersist.put(String,String) field name cannot be null");
949     if (null==sVal)
950       AllVals.put(sKey, null);
951     else if (bAllCaps)
952       AllVals.put(sKey, sVal.toUpperCase());
953     else
954       AllVals.put(sKey, sVal);
955   }
956
957   /**
958    * <p>Set value at internal collection</p>
959    * @param sKey Field Name
960    * @param oObj Field Value
961    * @throws NullPointerException If sKey is <b>null</b>
962    */

963
964   public void put(String JavaDoc sKey, Object JavaDoc oObj) throws NullPointerException JavaDoc {
965     if (sKey==null)
966       throw new NullPointerException JavaDoc("DBPersist.put(String,Object) field name cannot be null");
967     AllVals.put(sKey, oObj);
968   }
969
970   /**
971    * <p>Set value at internal collection</p>
972    * If internal collection previously contained a mapping for this key, the old value is replaced.
973    * @param sKey Field Name
974    * @param oObj Field Value
975    * @return previous value associated with specified key, or null if there was no mapping for key
976    * @throws NullPointerException If sKey is <b>null</b>
977    * @since 2.2
978    */

979
980   public Object JavaDoc put(Object JavaDoc sKey, Object JavaDoc oObj) throws NullPointerException JavaDoc {
981     Object JavaDoc oPrevious;
982     if (sKey==null)
983       throw new NullPointerException JavaDoc("DBPersist.put(Object,Object) field name cannot be null");
984     if (AllVals.containsKey(sKey)) {
985       oPrevious = AllVals.get(sKey);
986       AllVals.remove(sKey);
987     } else {
988       oPrevious = null;
989     }
990     AllVals.put(sKey, oObj);
991     return oPrevious;
992   }
993
994   /**
995    * <p>Set value at internal collection</p>
996    * @param sKey Field Name
997    * @param iVal Field Value
998    */

999
1000  public void put(String JavaDoc sKey, int iVal) {
1001    AllVals.put(sKey, new Integer JavaDoc(iVal));
1002  }
1003
1004  /**
1005   * <p>Set value at internal collection</p>
1006   * @param sKey Field Name
1007   * @param iVal Field Value
1008   */

1009
1010  public void put(String JavaDoc sKey, short iVal) {
1011    AllVals.put(sKey, new Short JavaDoc(iVal));
1012  }
1013
1014  /**
1015   * <p>Set value at internal collection</p>
1016   * @param sKey Field Name
1017   * @param dtVal Field Value
1018   */

1019
1020  public void put(String JavaDoc sKey, Date JavaDoc dtVal) {
1021    AllVals.put(sKey, dtVal);
1022  }
1023
1024  /**
1025   * <p>Set value at internal collection</p>
1026   * @param sKey Field Name
1027   * @param tmVal Field Value
1028   * @since 3.0
1029   */

1030
1031  public void put(String JavaDoc sKey, Time JavaDoc tmVal) {
1032    AllVals.put(sKey, tmVal);
1033  }
1034
1035  /**
1036   * Put Date value using specified format
1037   * @param sKey String Field Name
1038   * @param sDate String Field Value as String
1039   * @param oPattern SimpleDateFormat Date format to be used
1040   * @since 3.0
1041   */

1042  public void put(String JavaDoc sKey, String JavaDoc sDate, SimpleDateFormat JavaDoc oPattern)
1043    throws ParseException JavaDoc {
1044    AllVals.put(sKey, oPattern.parse(sDate));
1045  }
1046
1047  /**
1048   * <p>Put double value at internal collection</p>
1049   * @param sKey Field Name
1050   * @param dVal Field Value
1051   */

1052
1053  public void put(String JavaDoc sKey, double dVal) {
1054    AllVals.put(sKey, new Double JavaDoc(dVal));
1055  }
1056
1057  /**
1058   * <p>Put BigDecimal value at internal collection</p>
1059   * @param sKey Field Name
1060   * @param oDecVal Field Value
1061   */

1062
1063  public void put(String JavaDoc sKey, BigDecimal JavaDoc oDecVal) {
1064    AllVals.put(sKey, oDecVal);
1065  }
1066
1067  /**
1068   * Parse BigDecimal value and put it at internal collection
1069   * @param sKey String Field Name
1070   * @param sDecVal Field Name as String
1071   * @param oPattern DecimalFormat
1072   * @throws ParseException
1073   * @since 3.0
1074   */

1075  public void put(String JavaDoc sKey, String JavaDoc sDecVal, DecimalFormat JavaDoc oPattern)
1076    throws ParseException JavaDoc {
1077    AllVals.put(sKey, oPattern.parse(sDecVal));
1078  }
1079
1080  /**
1081   * <p>Set value at internal collection</p>
1082   * @param sKey Field Name
1083   * @param fVal Field Value
1084   */

1085
1086  public void put(String JavaDoc sKey, float fVal) {
1087    AllVals.put(sKey, new Float JavaDoc(fVal));
1088  }
1089
1090  /**
1091   * <p>Set value at internal collection</p>
1092   * @param sKey Field Name
1093   * @param mVal Field Value
1094   * @since 3.0
1095   */

1096
1097  public void put(String JavaDoc sKey, Money mVal) {
1098    if (null==mVal)
1099      AllVals.put(sKey, null);
1100    else
1101      AllVals.put(sKey, mVal.toString());
1102  }
1103
1104  /**
1105   * <p>Set reference to a binary file for a long field</p>
1106   * @param sKey Field Name
1107   * @param oFile File Object
1108   * @throws FileNotFoundException
1109   */

1110
1111  public void put(String JavaDoc sKey, File JavaDoc oFile) throws FileNotFoundException JavaDoc {
1112    if (!bHasLongVarBinaryData) LongVarBinaryValsLen = new HashMap JavaDoc();
1113
1114    LongVarBinaryValsLen.put(sKey, new Long JavaDoc(oFile.length()));
1115
1116    AllVals.put(sKey, oFile);
1117
1118    bHasLongVarBinaryData = true;
1119  } // put
1120

1121  /**
1122   * <p>Set reference to a byte array for a long field</p>
1123   * <p>Use this method only for binding LONGVARBINARY or BLOB fields</p>
1124   * @param sKey Field Name
1125   * @param aBytes byte array
1126   */

1127
1128  public void put(String JavaDoc sKey, byte[] aBytes) {
1129    if (!bHasLongVarBinaryData) LongVarBinaryValsLen = new HashMap JavaDoc();
1130
1131    LongVarBinaryValsLen.put(sKey, new Long JavaDoc(aBytes.length));
1132
1133    AllVals.put(sKey, aBytes);
1134
1135    bHasLongVarBinaryData = true;
1136  } // put
1137

1138  /**
1139   * <p>Set reference to a character array for a long field</p>
1140   * <p>Use this method only for binding LONGVARCHAR or CLOB fields</p>
1141   * @param sKey Field Name
1142   * @param aChars char array
1143   */

1144
1145  public void put(String JavaDoc sKey, char[] aChars) {
1146    if (!bHasLongVarBinaryData) LongVarBinaryValsLen = new HashMap JavaDoc();
1147
1148    LongVarBinaryValsLen.put(sKey, new Long JavaDoc(aChars.length));
1149
1150    AllVals.put(sKey, aChars);
1151
1152    bHasLongVarBinaryData = true;
1153  } // put
1154

1155  /**
1156   * <p>Set value at internal collection</p>
1157   * @param sKey Field Name
1158   * @param sData Field Value as a String. If iSQLType is BLOB or LONGVARBINARY
1159   * then sData is interpreted as a full file path uri.
1160   * @param iSQLType SQL Type for field
1161   * @throws NullPointerException If sKey is <b>null</b>
1162   * @throws IllegalArgumentException If SQL Type is not recognized.
1163   * Recognized types are { CHAR, VARCHAR, LONGVARCHAR, CLOB, INTEGER, SMALLINT,
1164   * DATE, TIMESTAMP, DOUBLE, FLOAT, REAL, DECIMAL, NUMERIC, BLOB, LONGVARBINARY }
1165   */

1166
1167  public void put(String JavaDoc sKey, String JavaDoc sData, int iSQLType)
1168    throws FileNotFoundException JavaDoc, IllegalArgumentException JavaDoc, NullPointerException JavaDoc {
1169    int iDecDot;
1170
1171    if (sKey==null)
1172      throw new NullPointerException JavaDoc("DBPersist.put(String,String,int) field name cannot be null");
1173
1174    switch (iSQLType) {
1175      case java.sql.Types.VARCHAR:
1176      case java.sql.Types.LONGVARCHAR:
1177      case java.sql.Types.CHAR:
1178      case java.sql.Types.CLOB:
1179        if (null==sData)
1180          AllVals.put(sKey, null);
1181        else if (bAllCaps)
1182          AllVals.put(sKey, sData.toUpperCase());
1183        else
1184          AllVals.put(sKey, sData);
1185        break;
1186      case java.sql.Types.INTEGER:
1187        AllVals.put(sKey, new Integer JavaDoc(sData));
1188        break;
1189      case java.sql.Types.SMALLINT:
1190        AllVals.put(sKey, new Short JavaDoc(sData));
1191        break;
1192      case java.sql.Types.DATE:
1193        if (null != sData)
1194          AllVals.put(sKey, java.sql.Date.valueOf(sData));
1195        else
1196          AllVals.put(sKey, null);
1197        break;
1198      case java.sql.Types.TIME:
1199        if (null != sData)
1200          AllVals.put(sKey, java.sql.Time.valueOf(sData));
1201        else
1202          AllVals.put(sKey, null);
1203        break;
1204      case java.sql.Types.TIMESTAMP:
1205        if (null != sData)
1206          AllVals.put(sKey, new java.sql.Timestamp JavaDoc(java.util.Date.parse(sData)));
1207        else
1208          AllVals.put(sKey, null);
1209        break;
1210      case java.sql.Types.DOUBLE:
1211      case java.sql.Types.FLOAT:
1212        AllVals.put(sKey, new Double JavaDoc(sData));
1213        break;
1214      case java.sql.Types.REAL:
1215        AllVals.put(sKey, new Float JavaDoc(sData));
1216        break;
1217      case java.sql.Types.DECIMAL:
1218      case java.sql.Types.NUMERIC:
1219        iDecDot = sData.indexOf(".");
1220        if (iDecDot < 0) iDecDot = sData.indexOf(",");
1221        if (iDecDot < 0)
1222          AllVals.put(sKey, new BigDecimal JavaDoc(sData));
1223        else
1224          AllVals.put(sKey,
1225                      BigDecimal.valueOf(Long.parseLong(sData.substring(0, iDecDot)),
1226                                         Integer.parseInt(sData.substring(iDecDot +
1227              1))));
1228        break;
1229      case java.sql.Types.LONGVARBINARY:
1230      case java.sql.Types.BLOB:
1231        if (!bHasLongVarBinaryData) LongVarBinaryValsLen = new HashMap JavaDoc();
1232
1233        File JavaDoc oFile = new File JavaDoc(sData);
1234        if (oFile.exists()) {
1235          LongVarBinaryValsLen.put(sKey, new Long JavaDoc(oFile.length()));
1236          AllVals.put(sKey, oFile);
1237        }
1238        bHasLongVarBinaryData = true;
1239        break;
1240      case 1111: // PostgreSQL interval
1241
if (DebugFile.trace) DebugFile.writeln("Binding interval "+sData);
1242        try {
1243          Class JavaDoc cPGIntval = Class.forName("org.postgresql.util.PGInterval");
1244          java.lang.reflect.Constructor JavaDoc cNewPGInt = null;
1245          Object JavaDoc oPGIntval;
1246          try {
1247            cNewPGInt = cPGIntval.getConstructor(new Class JavaDoc[]{String JavaDoc.class});
1248          } catch (NoSuchMethodException JavaDoc neverthrown) {}
1249          try {
1250            oPGIntval = cNewPGInt.newInstance(new Object JavaDoc[]{sData});
1251            AllVals.put(sKey, oPGIntval);
1252          } catch (InstantiationException JavaDoc neverthrown) {}
1253            catch (IllegalAccessException JavaDoc neverthrown) {}
1254            catch (java.lang.reflect.InvocationTargetException JavaDoc neverthrown) {}
1255        } catch (ClassNotFoundException JavaDoc cnfe) {
1256          throw new IllegalArgumentException JavaDoc("ClassNotFoundException org.postgresql.util.PGInterval");
1257        }
1258        if (DebugFile.trace) DebugFile.writeln("Interval successfully binded");
1259        break;
1260    } // end switch
1261
} // put
1262

1263  /**
1264   * <p>Load values from a Properties object</p>
1265   */

1266
1267  public void putAll(Properties JavaDoc oPropsCollection) throws FileNotFoundException JavaDoc {
1268    Iterator JavaDoc oIter = this.getTable().getColumns().iterator();
1269    DBColumn oDBCol;
1270    String JavaDoc sColName;
1271    String JavaDoc sPropValue;
1272
1273    while (oIter.hasNext()) {
1274      oDBCol = (DBColumn) oIter.next();
1275      sColName = oDBCol.getName();
1276      sPropValue = oPropsCollection.getProperty(sColName);
1277
1278      if (null!=sPropValue) {
1279        if (sPropValue.trim().length()>0) {
1280          switch(oDBCol.getSqlType()) {
1281            case java.sql.Types.INTEGER:
1282              replace(sColName, new Integer JavaDoc(sPropValue));
1283              break;
1284            case java.sql.Types.SMALLINT:
1285              replace(sColName, new Short JavaDoc(sPropValue));
1286              break;
1287            case java.sql.Types.DOUBLE:
1288            case java.sql.Types.REAL:
1289              replace(sColName, new Double JavaDoc(sPropValue));
1290              break;
1291            case java.sql.Types.FLOAT:
1292              replace(sColName, new Float JavaDoc(sPropValue));
1293              break;
1294            case java.sql.Types.NUMERIC:
1295            case java.sql.Types.DECIMAL:
1296              replace(sColName, new java.math.BigDecimal JavaDoc(sPropValue));
1297              break;
1298            default:
1299              put(sColName, sPropValue, oDBCol.getSqlType());
1300          } // end switch
1301
} // fi (s!="")
1302
else if (!isNull(sColName))
1303          replace(sColName, null);
1304      } // fi (s!=null)
1305
} // wend
1306
} // putAll()
1307

1308  /**
1309   * <p>Put values from a Map into this DBPersist instance</p>
1310   * allcaps has no effect on input data when calling this method
1311   * @param oMap
1312   * @since 2.2
1313   */

1314  public void putAll(Map JavaDoc oMap) {
1315    Iterator JavaDoc oIter = oMap.keySet().iterator();
1316    while (oIter.hasNext()){
1317      String JavaDoc sKey = oIter.next().toString();
1318      AllVals.put(sKey, oMap.get(sKey));
1319    } // wend
1320
} // putAll
1321

1322  /**
1323   * <p>Remove a value from internal collection</p>
1324   * @param sKey Field Name
1325   */

1326
1327  public void remove(String JavaDoc sKey) {
1328    if (AllVals.containsKey(sKey)) AllVals.remove(sKey);
1329  }
1330
1331  /**
1332   * <p>Remove a value from internal collection</p>
1333   * @param oKey Field Name
1334   * @return Object previos value associated with given field name
1335   * @since 2.2
1336   */

1337
1338  public Object JavaDoc remove(Object JavaDoc oKey) {
1339    Object JavaDoc oPrevious;
1340    if (AllVals.containsKey(oKey)) {
1341      oPrevious = AllVals.get(oKey);
1342      AllVals.remove(oKey);
1343    } else {
1344      oPrevious = null;
1345    }
1346    return oPrevious;
1347  }
1348
1349  /**
1350   * <p>Replace a value from internal collection</p>
1351   * @param sKey Field Name
1352   * @param oObj New Value
1353   */

1354  public void replace(String JavaDoc sKey, Object JavaDoc oObj) {
1355    remove(sKey);
1356
1357    AllVals.put(sKey, oObj);
1358  }
1359
1360  /**
1361   * <p>Replace a value from internal collection</p>
1362   * @param sKey Field Name
1363   * @param iVal New int value
1364   */

1365
1366  public void replace(String JavaDoc sKey, int iVal) {
1367    Integer JavaDoc oObj = new Integer JavaDoc(iVal);
1368
1369    remove(sKey);
1370
1371    AllVals.put(sKey, oObj);
1372  }
1373
1374  /**
1375   * <p>Replace a value from internal collection</p>
1376   * @param sKey Field Name
1377   * @param iVal New short value
1378   */

1379
1380  public void replace(String JavaDoc sKey, short iVal) {
1381    Short JavaDoc oObj = new Short JavaDoc(iVal);
1382
1383    remove(sKey);
1384
1385    AllVals.put(sKey, oObj);
1386  }
1387
1388  /**
1389   * <p>Replace a value from internal collection</p>
1390   * @param sKey Field Name
1391   * @param iVal New float value
1392   */

1393
1394  public void replace(String JavaDoc sKey, float fVal) {
1395    Float JavaDoc oObj = new Float JavaDoc(fVal);
1396
1397    remove(sKey);
1398
1399    AllVals.put(sKey, oObj);
1400  }
1401
1402  /**
1403   * Convert value kept with given key to lowercase
1404   * @param sKey String
1405   * @since 3.0
1406   */

1407
1408  public void toLowerCase(String JavaDoc sKey) {
1409    if (!isNull(sKey))
1410      replace (sKey, getString(sKey).toLowerCase());
1411  }
1412
1413  /**
1414   * Convert value kept with given key to uppercase
1415   * @param sKey String
1416   * @since 3.0
1417   */

1418
1419  public void toUpperCase(String JavaDoc sKey) {
1420    if (!isNull(sKey))
1421      replace (sKey, getString(sKey).toUpperCase());
1422  }
1423
1424  /**
1425   * <p>Store a register at database representing this instance of DBPersist</p>
1426   * <p><b>Insertions and updates</b> : The store method automatically manages
1427   * register insertions and updates. If the stored object already exists at
1428   * database then it is updated, if it does not exists then it is inserted.
1429   * A primary key violation error is never thrown so ther is no need to call
1430   * delete() method before re-writing an existing object.</p>
1431   * <p><b>NULL fields</b> : All values not set calling put() methods for DBPersist
1432   * will be assumed to be NULL. If a not nullable field is not set then an
1433   * SQLException will be raised.<br>
1434   * On storing an already existing object all values will we overwrited,
1435   * so is a DBPersist is not fully loaded before storing it, values not set
1436   * by calling put() methods that already were present at database will be lost.</p>
1437   * @param oConn Database Connection
1438   * @return boolean <b>true</b> if register was stored for the first time,
1439   * <b>false</b> if register already existed.
1440   * @throws SQLException
1441   */

1442
1443  public boolean store(JDCConnection oConn) throws SQLException JavaDoc {
1444    boolean bRetVal;
1445
1446    if (bHasLongVarBinaryData) {
1447      try {
1448        if (oTable==null) {
1449          oTable = getTable(oConn);
1450          if (null==oTable) throw new SQLException JavaDoc("Table not found "+sTable,"42S02", 42002);
1451          bRetVal = oTable.storeRegisterLong(oConn, AllVals, LongVarBinaryValsLen);
1452        } else
1453          bRetVal = oTable.storeRegisterLong(oConn, AllVals, LongVarBinaryValsLen);
1454      }
1455      catch (IOException JavaDoc ioe) {
1456        throw new SQLException JavaDoc(ioe.getMessage(),"40001",40001);
1457      }
1458      finally {
1459        LongVarBinaryValsLen.clear();
1460        bHasLongVarBinaryData = false;
1461      }
1462    }
1463    else
1464      if (oTable==null) {
1465        oTable = getTable(oConn);
1466        if (null==oTable) throw new SQLException JavaDoc("Table not found "+sTable,"42S02", 42002);
1467        bRetVal = oTable.storeRegister(oConn, AllVals);
1468      } else
1469        bRetVal = oTable.storeRegister(oConn, AllVals);
1470
1471    return bRetVal;
1472  } // store()
1473

1474  /**
1475   * <p>Delete a register from database</p>
1476   * <p>The deleted register will be the one matching this DBPersist primary key,
1477   * as set at constructor or load() method.</p>
1478   * @param oConn Database connection
1479   * @return <b>true</b> if register was successfully erased, <b>false</b> if not.
1480   * @throws SQLException
1481   */

1482
1483  public boolean delete(JDCConnection oConn) throws SQLException JavaDoc {
1484    boolean bRetVal;
1485
1486    if (null==oTable) {
1487      oTable = getTable(oConn);
1488      if (null==oTable) throw new SQLException JavaDoc("Table not found "+sTable,"42S02", 42002);
1489      bRetVal = oTable.deleteRegister(oConn, AllVals);
1490    } else
1491      bRetVal = oTable.deleteRegister(oConn, AllVals);
1492
1493    return bRetVal;
1494  } // delete()
1495

1496  /**
1497   * <p>Find out whether or not a particular register exists at database</p>
1498   * @param oConn database connection
1499   * @return <b>true</b> if a register exists a DBPersist base table witch
1500   * primary key coincides with the one set in memory for the DBPersist.
1501   * @throws SQLException
1502   */

1503
1504  public boolean exists(JDCConnection oConn) throws SQLException JavaDoc {
1505    if (null==oTable) {
1506      oTable = getTable(oConn);
1507      if (null==oTable) throw new SQLException JavaDoc("Table not found "+sTable,"42S02", 42002);
1508      return oTable.existsRegister(oConn, AllVals);
1509    } else
1510      return oTable.existsRegister(oConn, AllVals);
1511  }
1512
1513  /**
1514   * <p>Get an XML dump for the DBPersist values</p>
1515   * @param sIdent Number of blank spaces for left padding at every line.
1516   * @param sDelim Line delimiter (usually "\n" or "\r\n")
1517   * @param oAttrs Map of values to be added as attributes of the toplevel node
1518   * @return XML String
1519   * @throws IllegalStateException If XML method is invoked before DBPersist object is loaded
1520   * @since 3.0
1521   */

1522
1523  protected String JavaDoc toXML(String JavaDoc sIdent, String JavaDoc sDelim, HashMap JavaDoc oAttrs)
1524
1525    throws IllegalStateException JavaDoc {
1526
1527    if (null==oTable)
1528      throw new IllegalStateException JavaDoc("DBPersist.toXML() method invoked before load() method was called");
1529
1530    StringBuffer JavaDoc oBF = new StringBuffer JavaDoc(80*oTable.columnCount());
1531    ListIterator JavaDoc oIT = oTable.getColumns().listIterator();
1532    DBColumn oColumn;
1533    Object JavaDoc oColValue;
1534    String JavaDoc sColName;
1535    String JavaDoc sStartElement = sIdent + sIdent + "<";
1536    String JavaDoc sEndElement = ">" + sDelim;
1537    Class JavaDoc oColClass, ClassString = null, ClassDate = null;
1538    SimpleDateFormat JavaDoc oXMLDate = new SimpleDateFormat JavaDoc("yyyy-MM-dd'T'hh:mm:ss");
1539
1540    try {
1541      ClassString = Class.forName("java.lang.String");
1542      ClassDate = Class.forName("java.util.Date");
1543    } catch (ClassNotFoundException JavaDoc ignore) { }
1544
1545    if (null==oAttrs) {
1546      oBF.append(sIdent + "<" + sAuditCls + ">" + sDelim);
1547    } else {
1548      oBF.append(sIdent + "<" + sAuditCls);
1549      Iterator JavaDoc oNames = oAttrs.keySet().iterator();
1550      while (oNames.hasNext()) {
1551        Object JavaDoc oName = oNames.next();
1552        oBF.append(" "+oName+"=\""+oAttrs.get(oName)+"\"");
1553      } // wend
1554
oBF.append(">" + sDelim);
1555    } // fi
1556

1557    while (oIT.hasNext()) {
1558      oColumn = (DBColumn) oIT.next();
1559      sColName = oColumn.getName();
1560      oColValue = AllVals.get(sColName);
1561
1562      oBF.append(sStartElement);
1563      oBF.append(sColName);
1564      oBF.append(">");
1565      if (null!=oColValue) {
1566        oColClass = oColValue.getClass();
1567        if (oColClass.equals(ClassString))
1568          oBF.append("<![CDATA[" + oColValue + "]]>");
1569        else if (oColClass.equals(ClassDate))
1570          oBF.append(oXMLDate.format((java.util.Date JavaDoc) oColValue));
1571        else
1572          oBF.append(oColValue);
1573      }
1574      oBF.append("</");
1575      oBF.append(sColName);
1576      oBF.append(sEndElement);
1577    } // wend
1578

1579    oBF.append(sIdent + "</" + sAuditCls + ">");
1580
1581    return oBF.toString();
1582  } // toXML
1583

1584  /**
1585   * <p>Get an XML dump for the DBPersist values</p>
1586   * @param sIdent Number of blank spaces for left padding at every line.
1587   * @param sDelim Line delimiter (usually "\n" or "\r\n")
1588   * @return XML String
1589   @ @throws IllegalStateException If XML method is invoked before DBPersist object is loaded
1590   */

1591
1592  public String JavaDoc toXML(String JavaDoc sIdent, String JavaDoc sDelim)
1593    throws IllegalStateException JavaDoc {
1594    return toXML(sIdent, sDelim, null);
1595  }
1596
1597  /**
1598   * <p>Get an XML dump for the DBPersist values.</p>
1599   * <p>Lines are delimited by a single Line Feed CHR(10) '\n' character.</p>
1600   * @param sIdent Number of blank spaces for left padding at every line.
1601   * @return XML String
1602   */

1603
1604  public String JavaDoc toXML(String JavaDoc sIdent) {
1605    return toXML(sIdent, "\n", null);
1606  }
1607
1608  /**
1609   * <p>Get an XML dump for the DBPersist values.</p>
1610   * <p>No left padding is placed to the left of each line.</p>
1611   * <p>Lines are delimited by a single Line Feed CHR(10) '\n' character.</p>
1612   * @return XML String
1613   */

1614
1615  public String JavaDoc toXML() {
1616    return toXML("", "\n", null);
1617  }
1618
1619  /**
1620   * <p>Load an XML String into DBPersist internal collection.</p>
1621   * <p>Each tag <field>...</field> found will be stored as a DBPersist value.</p>
1622   * <p>Example of input file:<br>
1623   * &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;<br>
1624   * &lt;ACLUser&gt;<br>
1625   * &nbsp;&nbsp;&lt;gu_user&gt;32f4f56fda343a5898c15a021203dd82&lt;/gu_user&gt;<br>
1626   * &nbsp;&nbsp;&lt;id_domain&gt;1026&lt;/id_domain&gt;<br>
1627   * &nbsp;&nbsp;&lt;nm_user&gt;The 7th Guest&lt;/nm_user&gt;<br>
1628   * &nbsp;&nbsp;&lt;tx_pwd&gt;123456&lt;/tx_pwd&gt;<br>
1629   * &nbsp;&nbsp;&lt;tx_main_email&gt;guest7@domain.com&lt;/tx_main_email&gt;<br>
1630   * &nbsp;&nbsp;&lt;tx_alt_email&gt;admin@hipergate.com&lt;/tx_alt_email&gt;<br>
1631   * &nbsp;&nbsp;&lt;dt_last_updated&gt;Fri, 29 Aug 2003 13:30:00 GMT+0130&lt;/dt_last_updated&gt;<br>
1632   * &nbsp;&nbsp;&lt;tx_comments&gt;&lt;![CDATA[S�me �asti & �nternational chars stuff]]&gt;&lt;/tx_comments&gt;<br>
1633   * &lt;/ACLUser&gt;</p>
1634   * @param sXMLFilePath XML Path to XML file to parse
1635   * @throws SAXException
1636   * @throws SAXNotRecognizedException
1637   * @throws SAXNotSupportedException
1638   * @throws SAXParseException
1639   * @throws IOException
1640   * @throws ClassNotFoundException
1641   * @throws IllegalAccessException
1642   * @throws InstantiationException
1643   */

1644
1645  public void parseXML(String JavaDoc sXMLFilePath) throws SAXException JavaDoc,SAXNotRecognizedException JavaDoc,SAXNotSupportedException JavaDoc,SAXParseException JavaDoc,IOException JavaDoc,ClassNotFoundException JavaDoc,IllegalAccessException JavaDoc,InstantiationException JavaDoc {
1646    DBSaxHandler oHandler = new DBSaxHandler(this);
1647    oHandler.parse(sXMLFilePath);
1648  }
1649
1650  /**
1651   * Compares two objects and returns a Map of their differences
1652   * @param oOldInstance DBPersist
1653   * @return HashMap
1654   */

1655  protected HashMap JavaDoc changelog(DBPersist oOldInstance) {
1656    Object JavaDoc oKey, oOld, oNew;
1657    HashMap JavaDoc oLog = new HashMap JavaDoc(size()*2);
1658
1659    // Iterate throught this instance and see what keys are different at oOldInstance
1660
Iterator JavaDoc oKeys = keySet().iterator();
1661    while (oKeys.hasNext()) {
1662      oKey = oKeys.next();
1663      oNew = get(oKey);
1664      oOld = oOldInstance.get(oKey);
1665      if (null!=oNew) {
1666        if (!oNew.equals(oOld)) oLog.put(oKey, oOld);
1667      } else if (oOld!=null) {
1668        oLog.put(oKey, oOld);
1669      }
1670    } // wend
1671

1672    // Iterate throught oOldInstance and see what keys are different at this instance
1673
oKeys = oOldInstance.keySet().iterator();
1674    while (oKeys.hasNext()) {
1675      oKey = oKeys.next();
1676      if (!containsKey(oKey)) {
1677        oOld = oOldInstance.get(oKey);
1678        oLog.put(oKey, oOld);
1679      }
1680    } // wend
1681
return oLog;
1682  } // changelog
1683

1684  /**
1685   * <p>Internal method for being called by inherited classes</p>
1686   * <p>Searches an object instance GUID from its unique name</p>
1687   * @param oConn Database Connection
1688   * @param iDomainId Domain Identifier
1689   * @param sInstanceNm Instance Name
1690   * @param sStoredProc Stored Procedure or PL/pgSQL Function Name
1691   * @return Global Unique Identifier of instance been searched or <n>null</n>
1692   * if no instance was found with such name.
1693   * @throws SQLException
1694   */

1695
1696  protected static String JavaDoc getUIdFromName(JDCConnection oConn, Integer JavaDoc iDomainId, String JavaDoc sInstanceNm, String JavaDoc sStoredProc) throws SQLException JavaDoc {
1697    CallableStatement JavaDoc oCall;
1698    PreparedStatement JavaDoc oStmt;
1699    ResultSet JavaDoc oRSet;
1700
1701    String JavaDoc sInstanceId;
1702
1703    if (null==iDomainId) {
1704      if (JDCConnection.DBMS_POSTGRESQL==oConn.getDataBaseProduct()) {
1705        if (DebugFile.trace)
1706          DebugFile.writeln("Connection.prepareStatement(SELECT " + sStoredProc + "('" + sInstanceNm + "')");
1707
1708        oStmt = oConn.prepareStatement("SELECT " + sStoredProc + "(?)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
1709        oStmt.setString(1, sInstanceNm);
1710        oRSet = oStmt.executeQuery();
1711        if (oRSet.next())
1712          sInstanceId = oRSet.getString(1);
1713        else
1714          sInstanceId = null;
1715        oRSet.close();
1716        oStmt.close();
1717      }
1718      else {
1719        if (DebugFile.trace)
1720          DebugFile.writeln("Connection.prepareCall({ call " + sStoredProc + " ('" + sInstanceNm + "',?)})");
1721
1722        oCall = oConn.prepareCall("{ call " + sStoredProc + " (?,?)}");
1723        try {
1724          oCall.setQueryTimeout(15);
1725        }
1726        catch (SQLException JavaDoc sqle) {}
1727
1728        oCall.setString(1, sInstanceNm);
1729        oCall.registerOutParameter(2, java.sql.Types.CHAR);
1730
1731        oCall.execute();
1732
1733        sInstanceId = oCall.getString(2);
1734
1735        if (JDCConnection.DBMS_ORACLE==oConn.getDataBaseProduct() && null!=sInstanceId)
1736          sInstanceId = sInstanceId.trim();
1737
1738        oCall.close();
1739        oCall = null;
1740      }
1741    }
1742    else {
1743      if (JDCConnection.DBMS_POSTGRESQL==oConn.getDataBaseProduct()) {
1744        if (DebugFile.trace)
1745          DebugFile.writeln("Connection.prepareStatement(SELECT " + sStoredProc + "(" + iDomainId.toString() + ",'" + sInstanceNm + "')");
1746
1747        oStmt = oConn.prepareStatement("SELECT " + sStoredProc + "(?,?)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
1748        oStmt.setInt(1, iDomainId.intValue());
1749        oStmt.setString(2, sInstanceNm);
1750        oRSet = oStmt.executeQuery();
1751        if (oRSet.next())
1752          sInstanceId = oRSet.getString(1);
1753        else
1754          sInstanceId = null;
1755        oRSet.close();
1756        oStmt.close();
1757      }
1758      else {
1759        if (DebugFile.trace)
1760          DebugFile.writeln("Connection.prepareCall({ call " + sStoredProc + " (" + iDomainId.toString() + ",'" + sInstanceNm + "',?)})");
1761
1762        oCall = oConn.prepareCall("{ call " + sStoredProc + " (?,?,?) }");
1763        try {
1764          oCall.setQueryTimeout(15);
1765        }
1766        catch (SQLException JavaDoc sqle) {}
1767
1768        oCall.setInt(1, iDomainId.intValue());
1769        oCall.setString(2, sInstanceNm);
1770        oCall.registerOutParameter(3, java.sql.Types.CHAR);
1771
1772        oCall.execute();
1773
1774        sInstanceId = oCall.getString(3);
1775
1776        if (null!=sInstanceId) sInstanceId = sInstanceId.trim();
1777
1778        oCall.close();
1779        oCall = null;
1780      }
1781    }
1782
1783    return sInstanceId;
1784  } // getUIdFromName
1785

1786  protected HashMap JavaDoc AllVals;
1787  protected String JavaDoc sAuditCls;
1788  protected String JavaDoc sAuditUsr;
1789  protected String JavaDoc sTransactId;
1790  private boolean bAllCaps;
1791  private boolean bHasLongVarBinaryData;
1792  private HashMap JavaDoc LongVarBinaryValsLen;
1793  private DBTable oTable;
1794  private String JavaDoc sTable;
1795} //DBPersist
1796
Free Books   Free Magazines  
Popular Tags