KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > JtDAO


1
2
3 package Jt;
4 import java.io.*;
5 import java.sql.*;
6 import java.text.*;
7 import java.lang.reflect.*;
8 import java.beans.*;
9 import java.util.*;
10
11
12 /**
13   * Implements the Data Access Object pattern (DAO)
14   */

15
16 public class JtDAO extends JtObject {
17   private String JavaDoc user;
18   private String JavaDoc password;
19   private String JavaDoc url;
20   private String JavaDoc driver = "sun.jdbc.odbc.JdbcOdbcDriver";
21   private transient Connection connection = null;
22   private String JavaDoc base;
23   //private Object reply_to;
24
int n = 0;
25   JtObject db = null;
26   String JavaDoc insert_query = null;
27   //Hashtable attr;
28
Hashtable attr;
29   private Object JavaDoc key = null; // key field
30
private String JavaDoc table;
31   private Hashtable map_table = null;
32   private String JavaDoc configFile = null;
33
34
35   public JtDAO () {
36
37   }
38
39   void map_attribute (String JavaDoc at, String JavaDoc column) {
40     if (at == null || column == null)
41       return;
42     if (map_table == null)
43       map_table = new Hashtable ();
44
45     if (!validateAttribute (at)) {
46       handleError ("JtDAO.map_attribute: invalid attribute mapping:"
47       + at);
48
49       return;
50     }
51
52     map_table.put (at, column);
53   }
54
55   String JavaDoc getMapping (String JavaDoc at) {
56     String JavaDoc column;
57
58     if (at == null)
59       return (null);
60
61     if (map_table == null)
62       return (null);
63        
64     column = (String JavaDoc) map_table.get (at);
65 /*
66     if (column == null)
67       return (at);
68 */

69     return (column);
70   }
71
72   private Object JavaDoc closeConnection () {
73     if (db == null) {
74         handleWarning ("closeConnection: database object is null");
75     } else
76         handleTrace ("closeConnection: closing a db connection");
77     return (sendMessage (db, new JtMessage ("JtCLOSE")));
78   }
79   
80
81   // When dealing with DataSources, close the connection
82

83   private void closeDataSourceConnection () {
84     String JavaDoc datasource;
85
86     if (db == null)
87       return;
88     datasource = (String JavaDoc) getValue (db, "datasource");
89     if (datasource != null)
90       sendMessage (db, new JtMessage ("JtCLOSE"));
91       
92   }
93
94   /**
95     * Process object messages.
96     * <ul>
97     * <li> JtINSERT - Insert an object
98     * <li> JtFIND - Find an object
99     * <li> JtUPDATE - Update an object
100     * <li> JtDELETE - Delete an object
101     * <li> JtMAP_ATTRIBUTE - Map attribute to database column
102     * <li> JtREMOVE - Remove the JtDAO. Release resources including the database connection
103     * </ul>
104     */

105
106   public Object JavaDoc processMessage (Object JavaDoc event) {
107   String JavaDoc content;
108   String JavaDoc query;
109   JtMessage e = (JtMessage) event;
110   Object JavaDoc reply;
111
112       if (e == null || (e.getMsgId() == null))
113           return (null);
114
115       resetExceptions ();
116
117       // establish a connection
118
if (e.getMsgId().equals("JtREALIZE")) {
119     realize ();
120     return (null);
121       }
122
123       // insert record
124
if (e.getMsgId().equals("JtINSERT")) {
125     reply = insert ();
126
127         closeDataSourceConnection ();
128         return (reply);
129       }
130
131       if (e.getMsgId().equals("JtFIND")) {
132         clear ();
133     reply = find ();
134         // When dealing with DataSources, close the connection after
135
// each operation
136

137         closeDataSourceConnection ();
138         return (reply);
139       }
140
141       if (e.getMsgId().equals("JtUPDATE")) {
142         reply = update ();
143
144         closeDataSourceConnection ();
145         return (reply);
146       }
147
148       if (e.getMsgId().equals("JtCLEAR")) {
149         clear ();
150     return (null);
151       }
152
153       if (e.getMsgId().equals("JtPRINT")) {
154         print ();
155     return (null);
156       }
157
158       if (e.getMsgId().equals("JtMAP_ATTRIBUTE")) {
159         map_attribute ((String JavaDoc) e.getMsgContent (),
160                        (String JavaDoc) e.getMsgData ());
161         return (null);
162       }
163
164       if (e.getMsgId().equals("JtDELETE")) {
165     reply = delete ();
166
167         closeDataSourceConnection ();
168         return (reply);
169       }
170       
171       if (e.getMsgId().equals("JtCALCULATE_KEY")) {
172         reply = calculateKey ();
173
174         closeDataSourceConnection ();
175         return (reply);
176       }
177       
178       if (e.getMsgId().equals("JtCLOSE_CONNECTION")) {
179         return (closeConnection ());
180       }
181
182       if (e.getMsgId().equals("JtREMOVE")) {
183         destroy ();
184         return (null);
185       }
186
187       handleError
188     ("processMessageEvent: invalid message id:"+
189         e.getMsgId());
190       return (null);
191   }
192
193
194   // build_select_query: build select query
195

196   private String JavaDoc build_select_query () {
197     StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
198     String JavaDoc value;
199     //Object tmp;
200
Enumeration keys;
201     String JavaDoc att, tmp;
202     String JavaDoc key_column;
203
204     if (map_table == null)
205       return (null);
206
207     if (key == null || table == null)
208       return (null);
209
210     if (attr == null)
211       return (null);
212
213     value = (String JavaDoc) attr.get (key);
214
215     if (value == null) {
216       handleError ("build_select_query: invalid key (null)");
217       return (null);
218     }
219
220     key_column = getMapping ((String JavaDoc) key);
221
222     if (key_column == null) {
223       handleError ("build_select_query: invalid mapping for "
224        + key);
225       return (null);
226     }
227 // query.append ("Select * from "
228
// + table + " where "); //check
229

230
231 // if (map_table == null)
232
// keys = attr.keys ();
233
// else
234
keys = map_table.keys ();
235
236     if (!keys.hasMoreElements ())
237       return (null);
238
239     query.append ("Select ");
240  
241     while (keys.hasMoreElements ()) {
242       att = (String JavaDoc) keys.nextElement ();
243       tmp = getMapping (att);
244
245       if (tmp == null) {
246        handleError ("build_select_query: invalid mapping for "
247        + att);
248        return (null);
249       }
250
251       query.append (tmp);
252
253       if (keys.hasMoreElements ())
254         query.append (",");
255
256     }
257
258     query.append (" from " + table + " where ");
259
260     query.append (key_column);
261     query.append ("=");
262     query.append (value);
263     
264     handleTrace ("query:" + query);
265
266     return (query.toString ());
267
268   }
269
270   // build_delete_query: build delete query
271

272   private String JavaDoc build_delete_query () {
273     StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
274     Object JavaDoc value;
275     Object JavaDoc tmp;
276     String JavaDoc key_column;
277
278     if (attr == null)
279       return (null);
280
281     if (key == null || table == null)
282       return (null);
283
284     if (map_table == null)
285       return (null);
286
287     value = attr.get (key);
288     //value = (Object) getValue (this, key);
289

290     if (value == null) {
291       handleError ("build_delete_query: invalid key (null)");
292       return (null);
293     }
294
295     key_column = getMapping ((String JavaDoc) key);
296
297     if (key_column == null) {
298       handleError ("build_delete_query: invalid mapping for "
299        + key);
300       return (null);
301     }
302
303     query.append ("Delete from "
304      + table + " where "); //check
305

306     query.append (key_column);
307     //query.append (key);
308
query.append ("=");
309     query.append (value);
310     
311     handleTrace ("query:" + query);
312
313     return (query.toString ());
314
315   }
316
317   // build_update_query: build update query
318

319   private String JavaDoc build_update_query () {
320     StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
321     Enumeration keys;
322     String JavaDoc att;
323     String JavaDoc value;
324     Object JavaDoc tmp;
325     String JavaDoc column;
326     String JavaDoc key_column;
327     boolean first = true;
328
329     if (attr == null)
330       return (null);
331     if (key == null || table == null)
332       return (null);
333
334     if (map_table == null)
335       return (null);
336
337     keys = map_table.keys ();
338
339     if (!keys.hasMoreElements ())
340       return (null);
341
342     query.append ("Update " + table + " Set ");
343
344     while (keys.hasMoreElements ()) {
345       att = (String JavaDoc) keys.nextElement ();
346       
347       if (att.equals (key))
348         continue; // check
349

350       tmp = (Object JavaDoc) attr.get (att);
351
352       if (!((tmp == null) || tmp instanceof String JavaDoc ||
353             tmp instanceof java.util.Date JavaDoc)) {
354         handleError ("build_update_query:invalid type for "
355         + att);
356         return (null);
357       }
358
359       column = getMapping (att);
360
361       if (column == null) {
362         handleError ("build_update_query: invalid mapping for " +
363           att);
364         return (null);
365       }
366
367       if (first) {
368         first = false;
369       } else
370         query.append (", ");
371
372       query.append (column);
373
374       if (tmp == null) {
375         query.append ("="+null);
376       } else if (tmp instanceof String JavaDoc) {
377         value = (String JavaDoc) attr.get (att);
378         query.append ("="+value);
379       } else if (tmp instanceof java.util.Date JavaDoc) {
380         query.append ("= ?");
381       }
382
383 /*
384       if (keys.hasMoreElements ())
385        query.append (",");
386 */

387
388       //value = (String) attr.get (key);
389

390     }
391
392     query.append (" where ");
393
394     value = (String JavaDoc) attr.get (key);
395
396     if (value == null) {
397       handleError ("build_update_query: invalid key (null)");
398       return (null);
399     }
400
401     key_column = getMapping ((String JavaDoc) key);
402
403     if (key_column == null) {
404       handleError ("build_update_query: invalid mapping for "
405        + key);
406       return (null);
407     }
408
409     query.append (key_column + "=" + value);
410     
411     handleTrace ("query:" + query);
412
413     return (query.toString ());
414
415   }
416
417
418   void setParameters (PreparedStatement pst)
419   {
420
421     Enumeration keys;
422     String JavaDoc att;
423     String JavaDoc value;
424     Object JavaDoc tmp;
425     int i;
426     java.sql.Date JavaDoc tmp1;
427
428     if (pst == null)
429       return;
430
431     if (map_table == null)
432       return;
433
434     if (attr == null)
435       return;
436
437 // keys = attr.keys ();
438
keys = map_table.keys ();
439
440     i = 1;
441     while (keys.hasMoreElements ()) {
442       att = (String JavaDoc) keys.nextElement ();
443       
444       if (att.equals (key))
445         continue;
446
447       tmp = (Object JavaDoc) attr.get (att);
448
449       if (tmp instanceof java.util.Date JavaDoc) {
450
451         tmp1 = new
452         java.sql.Date JavaDoc (((java.util.Date JavaDoc)tmp).getTime ());
453         try {
454           pst.setDate (i, tmp1);
455         } catch (Exception JavaDoc ex) {
456           handleException (ex);
457         }
458         i++;
459       }
460
461     }
462
463   }
464
465
466   // build_insert_query: build insert query
467

468   private String JavaDoc build_insert_query () {
469     StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
470     Enumeration keys;
471     String JavaDoc key;
472     String JavaDoc value;
473     Object JavaDoc tmp;
474     String JavaDoc attn;
475
476     if (attr == null || table == null)
477       return (null);
478
479     if (map_table == null)
480       return (null);
481
482     keys = map_table.keys ();
483
484     if (!keys.hasMoreElements ())
485       return (null);
486
487     query.append ("Insert into " + table + " (");
488
489     while (keys.hasMoreElements ()) {
490       key = (String JavaDoc) keys.nextElement ();
491       
492       //attn = (String) map_table.get (key);
493
attn = getMapping (key);
494
495       if (attn == null) {
496         handleError ("build_update_query: invalid mapping for " +
497           attn);
498         return (null);
499       }
500       
501       query.append (attn);
502         
503       if (keys.hasMoreElements ())
504        query.append (",");
505       //value = (String) attr.get (key);
506

507     }
508     query.append (") values (");
509
510     keys = map_table.keys ();
511
512     while (keys.hasMoreElements ()) {
513
514       key = (String JavaDoc) keys.nextElement ();
515
516       tmp = attr.get (key);
517
518       if (tmp == null) {
519         query.append ("null");
520       } else if (tmp instanceof String JavaDoc) {
521         value = (String JavaDoc) attr.get (key); // check
522
query.append (value);
523       } else if (tmp instanceof java.util.Date JavaDoc) {
524         query.append ("?");
525       }
526
527       //value = (String) attr.get (key);
528

529       //query.append (value);
530

531       if (keys.hasMoreElements ())
532        query.append (",");
533
534     }
535     query.append (")");
536
537     handleTrace ("query:" + query);
538
539     return (query.toString ());
540
541   }
542
543   // find: find record
544

545   private JtObject find () {
546      JtMessage msg;
547      String JavaDoc query;
548      Object JavaDoc conn;
549      ResultSet res;
550      JtObject jout;
551
552      msg = new JtMessage ();
553
554      if (db == null)
555        realize ();
556
557      attr = getAttributes (); // check
558

559      query = build_select_query ();
560
561      if (query == null || db == null)
562        return (null);
563
564      conn = this.getValue (db, "connection");
565
566      // Connect to the data source
567

568      if (conn == null) {
569        msg.setMsgId ("JtCONNECT");
570        this.sendMessage (db, msg);
571        if (propagateException (db) != null)
572          return (null);
573      }
574
575      msg.setMsgId ("JtEXECUTE_QUERY");
576      msg.setMsgContent (query);
577
578      if (propagateException (db) != null)
579          return (null);
580
581      res = (ResultSet) this.sendMessage (db, msg);
582
583      if (res == null)
584        return (null);
585
586      try {
587        if (!res.next()) // check
588
return (null);
589      } catch (Exception JavaDoc e){
590        handleException (e);
591        return (null);
592      }
593
594      jout = map (res);
595
596      try {
597        res.close ();
598      }
599      catch (Exception JavaDoc ex) {
600        handleException (ex);
601      }
602
603      return (jout);
604   }
605
606
607   // delete: delete record
608

609   private Object JavaDoc delete () {
610      JtMessage msg;
611      String JavaDoc query;
612      Object JavaDoc conn;
613      ResultSet res;
614      Object JavaDoc out;
615
616      msg = new JtMessage ();
617
618      if (db == null)
619        realize ();
620
621      attr = getAttributes (); // check
622

623      query = build_delete_query ();
624
625      if (query == null || db == null)
626        return (null);
627
628      conn = this.getValue (db, "connection");
629
630      // Connect to the data source
631

632      if (conn == null) {
633        msg.setMsgId ("JtCONNECT");
634        this.sendMessage (db, msg);
635        //return (propagateException (db));
636
}
637
638      msg.setMsgId ("JtUPDATE");
639      msg.setMsgContent (query);
640
641      out = this.sendMessage (db, msg);
642      propagateException (db);
643
644      if (out instanceof Integer JavaDoc) {
645        if (((Integer JavaDoc) out).intValue () != 1)
646          return (null);
647        else
648          return (this);
649      } else
650        return (null);
651
652   }
653
654   private String JavaDoc getRSValue (ResultSet rs, String JavaDoc column)
655   {
656     String JavaDoc value = null;
657
658     if (rs == null || column == null)
659       return (null);
660
661     try {
662       value = rs.getString (column);
663     } catch (Exception JavaDoc e) {
664       handleException (e);
665     }
666     return (value);
667   }
668
669   // getRSDateValue
670

671   private String JavaDoc getRSDateValue (ResultSet rs, String JavaDoc column)
672   {
673     String JavaDoc value = null;
674     DateFormat df = DateFormat.getDateInstance();
675
676     if (rs == null || column == null)
677       return (null);
678
679     try {
680       java.sql.Date JavaDoc date = rs.getDate (column);
681       if (date == null)
682         return (null); // check
683
value = df.format (date); // check
684
//value = rs.getString (column);
685
} catch (Exception JavaDoc e) {
686       handleException (e);
687     }
688     return (value);
689   }
690
691   private String JavaDoc getRSBooleanValue (ResultSet rs, String JavaDoc column)
692   {
693     String JavaDoc value = null;
694
695     if (rs == null || column == null)
696       return (null);
697
698     try {
699       boolean b = rs.getBoolean (column);
700       //if (b == null)
701
// return (null); // check
702

703       if (b)
704         return ("true");
705       else
706         return ("false");
707
708       //value = b.toString ();
709
} catch (Exception JavaDoc e) {
710       handleException (e);
711     }
712     return (value);
713   }
714
715
716   private JtObject map (ResultSet rs) {
717
718    Object JavaDoc args[];
719    PropertyDescriptor[] prop;
720    int i;
721    Class JavaDoc p;
722    BeanInfo info = null;
723    String JavaDoc value; // check
724
String JavaDoc column;
725
726      try {
727
728        info = Introspector.getBeanInfo(
729               this.getClass (), this.getClass ().getSuperclass());
730      } catch(Exception JavaDoc e) {
731         handleException (e);
732         return (null);
733      }
734
735      prop = info.getPropertyDescriptors();
736      for(i = 0; i < prop.length; i++) {
737        //System.out.print ("Attribute:" +
738
//prop[i].getName());
739
p = prop[i].getPropertyType();
740
741        column = getMapping (prop[i].getName());
742
743        if (column == null) {
744          continue;
745        }
746
747        if (p.getName().equals ("java.util.Date") ){
748          value = getRSDateValue (rs, column);
749        } else if (p.getName().equals ("boolean") ){
750          value = getRSBooleanValue (rs, column);
751        } else // check
752
value = getRSValue (rs, column);
753
754        setValue (this, prop[i].getName(), value);
755  
756      }
757      return (this);
758   }
759
760
761   private void clear () {
762
763    Object JavaDoc args[];
764    PropertyDescriptor[] prop;
765    int i;
766    BeanInfo info = null;
767    Class JavaDoc p;
768    String JavaDoc value = null;
769
770      try {
771
772        info = Introspector.getBeanInfo(
773               this.getClass (), this.getClass ().getSuperclass());
774      } catch(Exception JavaDoc e) {
775         handleException (e);
776         return;
777      }
778
779      prop = info.getPropertyDescriptors();
780      for(i = 0; i < prop.length; i++) {
781
782        if (prop[i].getName().equals (key))
783          continue;
784
785
786        //handleTrace ("JtDAO.clear:" + prop[i].getName());
787

788        p = prop[i].getPropertyType();
789        if (p.getName().equals ("java.lang.String") ){
790          value = null;
791        } else if (p.getName().equals ("int") ||
792                   p.getName().equals ("float") ||
793                   p.getName().equals ("double") ||
794                   p.getName().equals ("long") ||
795                   p.getName().equals ("short") ||
796                   p.getName().equals ("byte")) {
797          value = "0";
798        } else if (p.getName().equals ("java.util.Date")) {
799          value = null;
800        } else if (p.getName().equals ("boolean")) {
801          value = "false";
802        } else {
803          handleWarning ("JtDAO.clear:unknown type:" +
804            p.getName());
805          continue;
806        }
807        setValue (this, prop[i].getName(), value); // check
808

809      }
810
811   }
812
813
814  // update: update record
815

816   private Object JavaDoc update () {
817      JtMessage msg;
818      String JavaDoc query;
819      Object JavaDoc conn;
820      Object JavaDoc out;
821
822      msg = new JtMessage ();
823      PreparedStatement pst = null;
824      
825      if (db == null)
826        realize ();
827
828      attr = getAttributes ();
829      query = build_update_query ();
830
831      if (query == null || db == null)
832        return (null);
833
834      conn = this.getValue (db, "connection");
835
836      // Connect to the data source
837

838      if (conn == null) {
839        msg.setMsgId ("JtCONNECT");
840        this.sendMessage (db, msg);
841      }
842
843 /*
844      msg.setMsgId ("JtUPDATE");
845      msg.setMsgContent (query);
846
847      this.sendMessage (db, msg);
848 */

849      msg.setMsgId ("JtPREPARE_STATEMENT");
850      msg.setMsgContent (query);
851
852      pst = (PreparedStatement) this.sendMessage (db, msg);
853
854      if (propagateException (db) != null)
855        return (null);
856
857      if (pst == null)
858        return (null); // check
859

860      setParameters (pst);
861
862      if (propagateException (db) != null)
863        return (null);
864
865      msg.setMsgId ("JtEXECUTE_PREPARED_UPDATE");
866      msg.setMsgContent (pst);
867      out = this.sendMessage (db, msg);
868
869      try {
870        pst.close ();
871      }
872      catch (Exception JavaDoc ex) {
873        handleException (ex);
874      }
875
876      if (propagateException (db) != null)
877        return (null);
878
879      if (out instanceof Integer JavaDoc) {
880        if (((Integer JavaDoc) out).intValue () != 1)
881          return (null);
882        else
883          return (this);
884      } else
885        return (null);
886
887   }
888
889
890   // propagateException:
891

892   private Exception JavaDoc propagateException (JtObject obj)
893   {
894     Exception JavaDoc ex;
895
896     if (obj == null)
897       return null;
898
899     ex = (Exception JavaDoc)
900      getValue (obj, "objException");
901
902     if (ex != null)
903       setValue (this, "objException", ex);
904
905     return (ex);
906   }
907  
908   // resetExceptions:
909

910   private void resetExceptions ()
911   {
912
913     setValue (this, "objException", null);
914     if (db != null)
915       setValue (db, "objException", null);
916
917   }
918  
919
920   // insert: insert record
921

922   private Object JavaDoc insert () {
923      JtMessage msg;
924      String JavaDoc query;
925      Object JavaDoc conn;
926      PreparedStatement pst;
927      Object JavaDoc out = null;
928
929      msg = new JtMessage ();
930
931      if (db == null)
932        realize ();
933
934      attr = getAttributes ();
935      query = build_insert_query ();
936
937      if (query == null || db == null)
938        return (null);
939
940      conn = this.getValue (db, "connection");
941
942      // Connect to the data source
943

944      if (conn == null) {
945        msg.setMsgId ("JtCONNECT");
946        this.sendMessage (db, msg);
947        if (propagateException (db) != null)
948          return (null);
949      }
950
951      msg.setMsgId ("JtPREPARE_STATEMENT");
952      msg.setMsgContent (query);
953
954      pst = (PreparedStatement) this.sendMessage (db, msg);
955
956      if (pst == null)
957        return (null); // check
958

959      setParameters (pst);
960
961      msg.setMsgId ("JtEXECUTE_PREPARED_UPDATE");
962      msg.setMsgContent (pst);
963      out = this.sendMessage (db, msg);
964        
965
966 /*
967      msg.setMsgId ("JtUPDATE");
968      msg.setMsgContent (query);
969
970      this.sendMessage (db, msg);
971 */

972
973      try {
974        pst.close ();
975      }
976      catch (Exception JavaDoc ex) {
977        handleException (ex);
978      }
979      
980      propagateException (db);
981
982      if (out == null)
983        return (null);
984
985      if (out instanceof Integer JavaDoc) {
986        if (((Integer JavaDoc) out).intValue () != 1)
987          return (null);
988        else
989          return (this);
990      } else
991        return (null);
992
993
994   }
995
996   /**
997    * Specifies the Database Connection.
998    */

999
1000  public void setConnection (Connection newConnection) {
1001    connection = newConnection;
1002  }
1003
1004
1005  /**
1006   * Returns the Database Connection.
1007   */

1008
1009  public Connection getConnection () {
1010    return (connection);
1011  }
1012
1013
1014  /**
1015   * Specifies the name of the configuration file.
1016   */

1017
1018  public void setConfigFile (String JavaDoc configFile) {
1019    this.configFile = configFile;
1020  }
1021
1022  /**
1023   * Returns the name of the configuration file.
1024   */

1025
1026  public String JavaDoc getConfigFile () {
1027    return (configFile);
1028  }
1029  private Hashtable getAttributes () {
1030
1031   Object JavaDoc args[];
1032   PropertyDescriptor[] prop;
1033   int i;
1034   Class JavaDoc p;
1035   Method m;
1036   BeanInfo info = null;
1037   Object JavaDoc value;
1038   Hashtable attr;
1039
1040     attr = new Hashtable ();
1041
1042     if (map_table == null) {
1043       handleError
1044       ("JtDAO.getAttributes: attributes/database mapping is missing");
1045       return (null);
1046     }
1047
1048     try {
1049       info = Introspector.getBeanInfo(
1050              this.getClass (), this.getClass ().getSuperclass());
1051     } catch(Exception JavaDoc e) {
1052        handleException (e);
1053        return (null);
1054     }
1055
1056     prop = info.getPropertyDescriptors();
1057     for(i = 0; i < prop.length; i++) {
1058// System.out.print ("Attribute:" +
1059
// prop[i].getName());
1060
p = prop[i].getPropertyType();
1061       
1062       try {
1063         m = prop[i].getReadMethod ();
1064         if (m == null) {
1065           handleError
1066         ("JtDAO: getReadMethod returned null");
1067             return (null);
1068         }
1069
1070         if (getMapping (prop[i].getName()) == null)
1071           continue;
1072
1073         value = m.invoke (this, null);
1074         if (value == null) {
1075// attr.put (prop[i].getName(), value);
1076
continue;
1077         }
1078
1079         if (value instanceof String JavaDoc) {
1080           attr.put (prop[i].getName(), "'" + value + "'");
1081           //System.out.println ("=" + value);
1082
continue;
1083         }
1084
1085         if (value instanceof Integer JavaDoc ||
1086             value instanceof Long JavaDoc ||
1087             value instanceof Float JavaDoc ||
1088             value instanceof Byte JavaDoc ||
1089             value instanceof Boolean JavaDoc ||
1090             value instanceof Short JavaDoc ||
1091             value instanceof Double JavaDoc) {
1092           attr.put (prop[i].getName(), value.toString () );
1093           //System.out.println ("=" + value);
1094
continue;
1095         }
1096
1097         if (value instanceof java.util.Date JavaDoc) {
1098           attr.put (prop[i].getName(), value);
1099           continue;
1100         }
1101
1102        } catch (Exception JavaDoc e) {
1103         handleException(e);
1104         return (null);
1105        }
1106      }
1107
1108      return (attr);
1109   }
1110
1111  private boolean validateAttribute (String JavaDoc att_name) {
1112
1113
1114   PropertyDescriptor[] prop;
1115   int i;
1116// Class p;
1117

1118   BeanInfo info = null;
1119
1120     if (att_name == null)
1121       return (false);
1122
1123     try {
1124
1125       info = Introspector.getBeanInfo(
1126              this.getClass (), this.getClass ().getSuperclass());
1127     } catch(Exception JavaDoc e) {
1128        handleException (e);
1129        return (false);
1130     }
1131
1132     prop = info.getPropertyDescriptors();
1133     for(i = 0; i < prop.length; i++) {
1134// System.out.print ("Attribute:" +
1135
// prop[i].getName());
1136
// p = prop[i].getPropertyType();
1137
if ((prop[i].getName()).equals (att_name))
1138         return (true);
1139     }
1140     return (false);
1141   }
1142
1143  private void print () {
1144
1145   Object JavaDoc args[];
1146   PropertyDescriptor[] prop;
1147   int i;
1148   Class JavaDoc p;
1149   Method m;
1150   BeanInfo info = null;
1151   Object JavaDoc value;
1152
1153
1154     try {
1155
1156       info = Introspector.getBeanInfo(
1157              this.getClass (), this.getClass ().getSuperclass());
1158     } catch(Exception JavaDoc e) {
1159        handleException (e);
1160        return;
1161     }
1162
1163     prop = info.getPropertyDescriptors();
1164     for(i = 0; i < prop.length; i++) {
1165// System.out.print ("Attribute:" +
1166
// prop[i].getName());
1167
p = prop[i].getPropertyType();
1168       
1169       try {
1170         m = prop[i].getReadMethod ();
1171         if (m == null) {
1172           handleError
1173         ("JtDAO: getReadMethod returned null");
1174             return;
1175         }
1176
1177         value = m.invoke (this, null);
1178
1179         System.out.println (this.getClass ().getName () + "." +
1180             prop[i].getName() + ":" + value);
1181
1182
1183        } catch (Exception JavaDoc e) {
1184         handleException(e);
1185        }
1186      }
1187
1188   }
1189
1190  /**
1191   * Specifies the attribute to be used as the database key.
1192   */

1193
1194  public void setKey (Object JavaDoc key) {
1195    this.key = key;
1196  }
1197
1198 /**
1199   * Returns the attribute to be used as the database key.
1200   */

1201
1202  public Object JavaDoc getKey () {
1203    return (key);
1204  }
1205
1206
1207  /**
1208   * Specifies the name of the database table.
1209   */

1210
1211  public void setTable (String JavaDoc table) {
1212    this.table = table;
1213  }
1214
1215
1216  /**
1217   * Returns the name of the database table.
1218   */

1219
1220  public String JavaDoc getTable () {
1221    return (table);
1222  }
1223
1224  private void readConfigFile () {
1225    JtMessage msg;
1226    JtObject cf;
1227
1228    if (configFile == null)
1229      return;
1230
1231    msg= new JtMessage ();
1232
1233    msg.setMsgId ("JtPARSE");
1234    msg.setMsgReplyTo (this);
1235
1236    cf = (JtObject) createObject ("Jt.xml.JtXMLMsgReader", "configFile");
1237    setValue (cf, "uri", configFile);
1238
1239    sendMessage (cf, msg);
1240
1241  }
1242  private String JavaDoc build_key_query () {
1243      StringBuffer JavaDoc query = new StringBuffer JavaDoc ();
1244      String JavaDoc value;
1245      //Object tmp;
1246
Enumeration keys;
1247      String JavaDoc att, tmp;
1248      String JavaDoc key_column;
1249
1250      if (key == null || table == null)
1251        return (null);
1252
1253      if (attr == null)
1254        return (null);
1255
1256      value = (String JavaDoc) attr.get (key);
1257
1258      if (value == null) {
1259        handleError ("build_key_query: invalid key (null)");
1260        return (null);
1261      }
1262
1263      key_column = getMapping ((String JavaDoc) key);
1264
1265      if (key_column == null) {
1266        handleError ("build_key_query: invalid mapping for "
1267         + key);
1268        return (null);
1269      }
1270
1271
1272      query.append ("Select Max (" + key_column + ") from " + table);
1273      
1274      handleTrace ("query:" + query);
1275
1276      return (query.toString ());
1277
1278    }
1279  
1280  // calculateKey: calculate a new key
1281

1282  private Object JavaDoc calculateKey () {
1283     JtMessage msg;
1284     String JavaDoc query;
1285     Object JavaDoc conn;
1286     ResultSet res;
1287     Object JavaDoc out;
1288     long ltmp = 0L;
1289     Exception JavaDoc ex1;
1290
1291     msg = new JtMessage ();
1292
1293     if (db == null)
1294       realize ();
1295
1296     attr = getAttributes (); // check
1297

1298     query = build_key_query ();
1299
1300     if (query == null || db == null)
1301       return (null);
1302
1303     conn = this.getValue (db, "connection");
1304
1305     // Connect to the data source
1306

1307     if (conn == null) {
1308       msg.setMsgId ("JtCONNECT");
1309       this.sendMessage (db, msg);
1310       //return (propagateException (db));
1311
}
1312
1313     msg.setMsgId ("JtEXECUTE_QUERY");
1314     msg.setMsgContent (query);
1315
1316     res = (ResultSet) this.sendMessage (db, msg);
1317     ex1 = propagateException (db);
1318     
1319     if (ex1 != null)
1320         return (new Long JavaDoc (-1L));
1321     
1322     try
1323    {
1324      if (res.next()) {
1325         ltmp = res.getLong(1);
1326      }
1327    }
1328    catch (Exception JavaDoc ex)
1329    {
1330      handleException (ex);
1331      return (new Long JavaDoc (-1L));
1332    }
1333     return (new Long JavaDoc(ltmp+1));
1334     
1335  }
1336  
1337  void realize () {
1338    JtMessage msg;
1339
1340    handleTrace ("JtDAO:realize");
1341
1342    if (db != null)
1343      return;
1344
1345    msg = new JtMessage ();
1346
1347    db = (JtObject) this.createObject ("Jt.JtJDBCAdapter", "db");
1348    // this.setValue (db, "objTrace", "1"); // check
1349

1350    if (configFile != null)
1351      readConfigFile ();
1352  }
1353
1354  void destroy () {
1355    if (db == null)
1356      return;
1357    //sendMessage (db, new JtMessage ("JtCLOSE"));
1358
closeConnection ();
1359    db = null;
1360
1361  }
1362
1363  private static void test () {
1364    JtObject main;
1365    String JavaDoc query;
1366    JtMessage msg;
1367
1368    main = new JtObject ();
1369// main.setValue (main, "objTrace", "1");
1370
main.createObject ("Jt.JtMessage", "message");
1371    msg = new JtMessage ();
1372
1373    main.createObject ("Jt.JtDAO", "dao");
1374// main.setValue ("dao", "objTrace", "1");
1375

1376    msg.setMsgId ("JtREALIZE");
1377    main.sendMessage ("dao", msg);
1378  }
1379
1380  /**
1381    * Unit tests the messages processed by JtDAO.
1382    */

1383
1384  public static void main (String JavaDoc[] args) {
1385     
1386     test ();
1387  }
1388}
Popular Tags