KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > JtObject


1
2 package Jt;
3
4 import java.io.*;
5 import java.util.*;
6 import java.text.*;
7 import java.lang.reflect.*;
8 import java.beans.*;
9
10
11
12 /**
13   * Root class of the Jt Class hierarchy; it implements the functionality
14   * required by the Jt Messaging pattern.
15   */

16
17
18 public class JtObject implements Serializable, JtInterface {
19
20    private static String JavaDoc version = "1.5 - 11/01/06"; // Framework version
21
private Hashtable objTable = null; // Children of this object
22
private static Hashtable resTable = null; // Attribute values
23
private static int initted = 0;
24    private static int log = 0;
25    private static String JavaDoc logFile = null; // Log file
26
private static PrintWriter logStream = null;
27    private static String JavaDoc resourceFile = ".Jtrc"; // Resource file
28
private String JavaDoc objName = null; // Qualified object name
29
private int objTrace = 0; // Enable/disable trace messages
30
private Object JavaDoc objException; // Exception
31
private int objStatus = 0; // Status
32

33    // The following attributes are being deprecated or changed
34
private long objId; // ID
35
private String JavaDoc objStore = ".Jt"; // Directory where the
36
// object should
37
// be stored
38

39    private String JavaDoc objPath = null;
40
41
42    
43
44    public JtObject () {
45
46     //objId = id++;
47

48         if (initted == 0) {
49            initialize ();
50            initted = 1;
51         }
52     if (log == 1)
53            setObjTrace (1);
54     }
55
56
57    /**
58     * Creates a Jt object of the specified class. The object is assigned the ID passed as parameter.
59     * The new object is a child of this object.
60     * If another child with the same ID already exists, an error is produced.
61     * After creating the object, it sets its attributes using the Jt resource file.
62     * @param class_name class name
63     * @param id object id
64     * @return object created or null
65     */

66
67    public Object JavaDoc createObject (Object JavaDoc class_name, Object JavaDoc id) {
68       Object JavaDoc obj, tmp = null;
69       Class JavaDoc jtclass;
70     
71
72     handleTrace ("JtObject.createObject:" + class_name + "," + id);
73
74     if (class_name == null || id == null) {
75        handleError ("JtObject.createObject: invalid paramenters");
76        return (null);
77     }
78
79
80 /*
81         if (objTable == null)
82           objTable = new Hashtable ();
83 */

84
85     obj = lookupObject (id);
86
87     // check for duplicates
88
if (obj != null) {
89            if (log == 0)
90          handleWarning
91         ("JtObject.createObject: unable to create a duplicate entry " + id);
92            else
93          handleError
94         ("JtObject.createObject: unable to create a duplicate entry " + id);
95        return (null);
96     }
97
98     try {
99        jtclass = Class.forName ((String JavaDoc) class_name);
100     } catch (Exception JavaDoc e) {
101        handleException (e);
102        return (null);
103     }
104
105     // Create a new instance of the object
106

107         try {
108
109
110            if (JtSingleton.class.isAssignableFrom (jtclass)) {
111              obj = JtSingleton.getInstance ();
112              if (obj == null) {
113                obj = jtclass.newInstance ();
114                JtSingleton.setInstance (obj);
115                tmp = JtSingleton.getInstance ();
116                // Although unlikely, another thread may create the Singleton instance
117
// first. In this case, an error should be produced.
118
if (tmp != obj) {
119                  handleError
120                  ("JtObject.createObject: attempt to create another instance of a Singleton (" +
121                  class_name + ")");
122                  return (null);
123                }
124
125
126              } else {
127                handleError
128                ("JtObject.createObject: attempt to create another instance of a Singleton (" +
129                  class_name + ")");
130                return (null);
131              }
132            } else
133              obj = jtclass.newInstance ();
134
135            if (obj instanceof JtObject) {
136            ((JtObject)obj).setObjName (absolute_name ((String JavaDoc) id));
137        if (log == 1)
138               ((JtObject)obj).setObjTrace (1);
139        else
140               ((JtObject)obj).setObjTrace (this.getObjTrace ());
141            }
142
143            // ((JtObject)obj).setObjSession (this.getObjSession ());
144
// add the new object to the object table
145
add (absolute_name ((String JavaDoc) id), obj);
146            load_object_resources (obj, class_name);
147          } catch (Exception JavaDoc e) {
148             handleException (e);
149      }
150
151
152      return (obj);
153    }
154
155
156
157    // absolute_name: determine the absolute name of the object
158

159    String JavaDoc absolute_name (String JavaDoc name) {
160     if (name == null)
161        return (null);
162     
163     if (name.indexOf (".") > 0)
164        return (name);
165
166     if (this.getObjName () == null)
167        return (name);
168
169
170     return (this.getObjName () + "." + name);
171
172    }
173
174
175    String JavaDoc calculateAbsoluteName (Object JavaDoc id) {
176      String JavaDoc name;
177
178     if (id == null)
179        return (null);
180
181         if (id instanceof JtObject) {
182           if (((JtObject) id).getObjName () == null)
183             handleWarning ("calculateAbsoluteName:JObject is missing name" +
184               ((JtObject) id).getObjName ());
185           return (((JtObject) id).getObjName ());
186         }
187
188         if (id instanceof String JavaDoc) {
189           name = (String JavaDoc) id;
190         } else
191           name = id.toString ();
192     
193     if (name.indexOf (".") > 0)
194        return (name);
195
196     if (this.getObjName () == null)
197        return (name);
198
199     return (this.getObjName () + "." + name);
200
201    }
202
203
204    /**
205     * Looks for an object based on its ID.
206     * @param id object ID
207     * @return object found or null
208     */

209
210    public Object JavaDoc lookupObject (Object JavaDoc id) {
211      String JavaDoc obj_id;
212      Hashtable ht;
213
214         if (!id.getClass().getName().equals ("java.lang.String"))
215             return (id); // check
216

217     
218     obj_id = absolute_name ((String JavaDoc) id);
219
220 // if (objSession == null) {
221

222           if (objTable == null)
223             return (null);
224
225       return (objTable.get (obj_id));
226 // }
227

228 /*
229         if (sessionTable == null)
230           return (null);
231
232         ht = (Hashtable) sessionTable.get (objSession);
233
234         if (ht == null)
235           return (null);
236         
237         return (ht.get (obj_id));
238 */

239    }
240
241
242
243   private boolean checkModifiers (Class JavaDoc cl, String JavaDoc prop) {
244
245     //Class cl;
246
Field field;
247     int mod;
248
249
250     if (cl == null || prop == null)
251       return (false);
252
253
254     field = null;
255     try {
256       field = cl.getDeclaredField (prop); // property dup property names
257
//System.out.println ("class:" + cl.getName ());
258

259     } catch (Exception JavaDoc e) {
260       
261       //handleException (e);
262

263       if (cl.getSuperclass () == null) {
264         handleException (e);
265         return (false);
266       }
267     }
268  
269     if (field == null) {
270       cl = cl.getSuperclass ();
271       return (checkModifiers (cl, prop));
272     }
273
274     mod = field.getModifiers ();
275
276     if (Modifier.isTransient (mod)) {
277       return (false);
278     }
279     if (Modifier.isStatic (mod)) {
280       return (false);
281     }
282     return (true);
283   }
284
285   private Object JavaDoc copyObject (Object JavaDoc obj, Object JavaDoc target) {
286    Object JavaDoc args[];
287    PropertyDescriptor[] prop;
288    Class JavaDoc p;
289    Method m;
290    BeanInfo info = null;
291    Object JavaDoc value, svalue = null;
292    int i;
293
294
295      if (obj == null || target == null)
296        return (null);
297
298      if (obj.getClass () != target.getClass ()) {
299        handleError
300          ("Jt.copyObject: object classes should be the same (source and target)");
301        return (null);
302      }
303
304      try {
305        info = Introspector.getBeanInfo(
306               obj.getClass (), java.lang.Object JavaDoc.class);
307      } catch(Exception JavaDoc e) {
308         handleException (e);
309         return (null); //check
310
}
311
312      prop = info.getPropertyDescriptors();
313
314
315      for(i = 0; i < prop.length; i++) {
316
317        if (!checkModifiers (obj.getClass (),prop[i].getName())) {
318          continue;
319        }
320
321        value = getValue (obj, prop[i].getName()); // check
322

323        svalue = null;
324        if (value instanceof Integer JavaDoc ||
325              value instanceof Long JavaDoc ||
326              value instanceof Float JavaDoc ||
327              value instanceof Byte JavaDoc ||
328              value instanceof Boolean JavaDoc ||
329              value instanceof Short JavaDoc ||
330              value instanceof Double JavaDoc) {
331          svalue = value.toString ();
332        } else
333          svalue = value;
334
335        
336        //if (svalue != null)
337
setValue (target, prop[i].getName(), svalue);
338
339      }
340
341       return (null); // check
342
}
343
344
345
346    /**
347      * Sets the value of an attribute.
348      * This method is able to convert the value from String to the correct type.
349      * Automatic convertion from String is done for the following types:
350      * byte, short, int, long, float, double, boolean and java.util.Date.
351      * @param id object id
352      * @param att attribute name
353      * @param value attribute value
354      */

355
356    public void setValue (Object JavaDoc id, Object JavaDoc att, Object JavaDoc value) {
357
358     Object JavaDoc obj;
359     Object JavaDoc args[];
360     PropertyDescriptor[] prop;
361     int i;
362     Class JavaDoc p;
363     Method m;
364     BeanInfo info = null;
365
366 /*
367         if (objSession != null)
368       handleTrace ("Session(" + objSession + "): JtObject.setValue:" + id + "," + att + "," + value);
369         else
370 */

371       handleTrace ("JtObject.setValue:" + id + "," + att + "," + value);
372
373     if (id == null | att == null) {
374        handleError ("JtObject.setValue: invalid paramenters");
375        return;
376     }
377
378         obj = lookupObject (id);
379
380         if (obj == null) {
381             handleError ("setValue: unable to find object: " + id);
382             return;
383         }
384
385 /*
386         if (obj instanceof JtValueObject) {
387           ((JtValueObject) obj).setValue (id, att, value);
388           return;
389         }
390 */

391
392         try {
393
394             info = Introspector.getBeanInfo(
395               obj.getClass (), java.lang.Object JavaDoc.class);
396         } catch(Exception JavaDoc e) {
397             handleException (e);
398             return;
399         }
400
401         prop = info.getPropertyDescriptors();
402         for(i = 0; i < prop.length; i++) {
403
404             if (prop[i].getName().equals ((String JavaDoc) att)) {
405
406               p = prop[i].getPropertyType();
407               args = new Object JavaDoc[1];
408               //System.out.println ("setValue:type" + p);
409
// if (value == null) {
410
// args[0] = value;
411

412               try {
413               if (p.getName().equals ("java.lang.String") ){
414                args[0] = value;
415               } else if (p.getName().equals ("byte") ){
416                args[0] = (value instanceof String JavaDoc)?Byte.valueOf ((String JavaDoc) value):value;
417               } else if (p.getName().equals ("short") ){
418                args[0] = (value instanceof String JavaDoc)?Short.valueOf ((String JavaDoc) value):value;
419               } else if (p.getName().equals ("int") ){
420                args[0] = (value instanceof String JavaDoc)?Integer.valueOf ((String JavaDoc) value):value;
421               //} else if (p.getName().equals ("java.lang.Long") ){
422
} else if (p.getName().equals ("long") ){
423                args[0] = (value instanceof String JavaDoc)?Long.valueOf ((String JavaDoc) value):value;
424           } else if (p.getName().equals ("float") ){
425                args[0] = (value instanceof String JavaDoc)?Float.valueOf ((String JavaDoc) value):value;
426           } else if (p.getName().equals ("double") ){
427                args[0] = (value instanceof String JavaDoc)?Double.valueOf ((String JavaDoc) value):value;
428           } else if (p.getName().equals ("boolean") ){
429                args[0] = (value instanceof String JavaDoc)?Boolean.valueOf ((String JavaDoc) value):value;
430           } else if (p.getName().equals ("java.util.Date") ){
431                DateFormat df = DateFormat.getDateInstance();
432                //SimpleDateFormat df;
433
if (value instanceof String JavaDoc)
434                try {
435                  //df = new SimpleDateFormat ((String) value);
436
args[0] = df.parse ((String JavaDoc) value);
437                  //args[0] = new SimpleDateFormat ((String) value);
438
} catch (Exception JavaDoc e) {
439                  handleException (e);
440                  return;
441                }
442                else
443                 args[0] = value;
444           } else
445            args[0] = value;
446               } catch (Exception JavaDoc e) {
447                  handleException (e);
448                  return;
449               }
450
451               try {
452                m = prop[i].getWriteMethod ();
453                if (m == null) {
454                  handleError
455                   ("JtObject.setValue failed:missing setter for attribute " + att);
456                  return;
457                }
458                m.invoke (obj, args);
459               } catch (Exception JavaDoc e) {
460                handleException (e);
461               }
462               return;
463
464         }
465     }
466
467         handleError ("JtObject.setValue: invalid attribute:"+ att);
468
469
470    }
471
472
473    /**
474      * Gets the value of an attribute. An object is always returned.
475      * For primitive types, the corresponding object type is returned.
476      * For instance, Integer is returned if
477      * the attribute is of type int.
478      *
479      * @param id object id
480      * @param att attribute name
481      * @return attribute value
482      */

483
484    public Object JavaDoc getValue (Object JavaDoc id, Object JavaDoc att) {
485    Object JavaDoc obj;
486    Method m;
487    Class JavaDoc p;
488    BeanInfo info = null;
489    PropertyDescriptor[] prop;
490    int i;
491
492     handleTrace ("JtObject.getValue: " + id + "," + att);
493
494     if (id == null || att == null) {
495        handleError ("JtObject.getValue: invalid paramenters");
496        return (null);
497     }
498
499     obj = lookupObject (id);
500
501         if (obj == null) {
502            handleError ("getValue: unable to find object " + id);
503            return (null);
504         }
505 /*
506         if (obj instanceof JtValueObject) {
507           return (((JtValueObject) obj).getValue (id, att));
508         }
509 */

510
511         try {
512
513           info = Introspector.getBeanInfo(obj.getClass (),
514              java.lang.Object JavaDoc.class);
515
516         } catch(Exception JavaDoc e) {
517             handleException (e);
518             return (null);
519         }
520
521         prop = info.getPropertyDescriptors();
522
523         for(i = 0; i < prop.length; i++) {
524
525
526          if (prop[i].getName().equals ((String JavaDoc) att)) {
527
528                 try {
529                   m = prop[i].getReadMethod ();
530                   if (m == null) {
531                     handleError
532             ("JtObject.getValue: getReadMethod returned null");
533                     return (null);
534                   }
535                   return (m.invoke (obj, null));
536                 } catch (Exception JavaDoc e) {
537                   handleException(e);
538                   return (null);
539                 }
540      }
541     }
542         handleError ("JtObject.getValue:invalid attribute:" + att);
543         return (null);
544        
545     }
546
547
548    /**
549     * Removes an object. The object is removed from the table of children kept by
550     * its parent object. A JtREMOVE message is sent to the object. All Jt objects
551     * should process JtREMOVE and release any resources that were allocated
552     * (sockets, Database connections, etc.).
553     * @param id object id
554     */

555    
556    public void removeObject (Object JavaDoc id) {
557       Object JavaDoc obj;
558
559     handleTrace ("JtObject.removeObject: " + id);
560
561     if (id == null) {
562        handleError
563         ("JtObject.removeObject: invalid paramenters");
564        return;
565     }
566     
567     obj = lookupObject (id);
568
569     if (obj == null) {
570            handleError ("JtObject.removeObject: object not found: "+
571         id);
572        return;
573     }
574
575         sendMessage (obj, new JtMessage ("JtREMOVE"));
576
577         //if (id instanceof String)
578
if (remove (calculateAbsoluteName (id)) == null)
579         handleError
580         ("JtObject.removeObject: unable to remove object " + id);
581
582    }
583
584    /**
585     * Destroys an object (deprecated).
586     * @param id object id
587     */

588
589   
590    public void destroyObject (Object JavaDoc id) {
591       Object JavaDoc obj;
592         handleWarning
593           ("JtObject.destroyObject has been deprecated. Please use removeObject");
594         removeObject (id);
595
596 /*
597     handleTrace ("JtObject.destroyObject: " + id);
598
599     if (id == null) {
600        handleError
601         ("JtObject.destroyObject: invalid paramenters");
602        return;
603     }
604     
605     obj = lookupObject (id);
606
607     if (obj == null) {
608            handleError ("JtObject.destroyObject: object not found: "+
609         id);
610        return;
611     }
612
613         sendMessage (obj, new JtMessage ("JtDESTROY"));
614
615     if (remove (absolute_name ((String) id)) == null)
616        handleError
617         ("JtObject.destroyObject: unable to remove object " + id);
618 */

619    }
620
621    // realizeObject: realize an object (being deprecated)
622

623    void realizeObject (Object JavaDoc id) {
624       Object JavaDoc obj;
625
626         handleTrace ("JtObject.realizeObject:" + id);
627
628         if (id == null) {
629            handleError
630                 ("JtObject.realizeObject: invalid paramenters");
631            return;
632         }
633
634         obj = lookupObject (id);
635
636         if (obj == null) {
637            handleError ("JtObject.realizeObject: object not found:"+
638                 id);
639            return;
640         }
641
642         ((JtObject) obj).realize ();
643    }
644
645
646    // activateObject: activate an object (being deprecated)
647

648    void activateObject (Object JavaDoc id) {
649       Object JavaDoc obj;
650
651     handleTrace ("JtObject.activateObject: " + id);
652
653     if (id == null) {
654        handleError
655         ("JtObject.activateObject: invalid parameters");
656        return;
657     }
658     
659     obj = lookupObject (id);
660
661     if (obj == null) {
662            handleError ("JtObject.activateObject: object not found: "+
663         id);
664        return;
665     }
666
667     ((JtObject) obj).activate ();
668    }
669
670
671    // Save Object (being deprecated)
672

673    void save () {
674     ObjectOutputStream p = null;
675     BufferedOutputStream ostream = null;
676     String JavaDoc fpath = null;
677
678     if (objPath == null) {
679
680     if (this.getObjName () != null) {
681     fpath = ".Jt/" + this.getObjName ();
682     } else {
683     fpath = ".Jt/" + this.getObjId ();
684     }
685
686     } else
687     fpath = objPath;
688
689     // Try to create the directory if it is not already there
690
create_dir (fpath);
691
692     try {
693
694         ostream = new BufferedOutputStream (new FileOutputStream (fpath));
695
696         p = new ObjectOutputStream(ostream);
697     } catch (Exception JavaDoc e) {
698         handleException (e);
699         return;
700     }
701
702
703     try {
704         p.writeObject(this);
705         p.flush();
706         p.close();
707     } catch (Exception JavaDoc e) {
708         handleException (e);
709     }
710   }
711
712
713   // restore_object: restore an object (being deprecated)
714

715   Object JavaDoc restore () {
716     ObjectInputStream p = null;
717     BufferedInputStream istream = null;
718     String JavaDoc fpath;
719     Object JavaDoc obj = null;
720     File file = null;
721
722     
723     if (objPath == null)
724        if (this.getObjName () != null) {
725     fpath = ".Jt/" + this.getObjName ();
726        } else {
727     fpath = ".Jt/" + this.getObjId ();
728        }
729     else
730        fpath = objPath;
731
732     handleTrace ("Jt.restore: " + fpath);
733
734     if (fpath == null)
735         return (null);
736
737     file = new File (fpath);
738
739     if (!file.exists ()) {
740     handleTrace ("Jt.restore: " + fpath + " does not exists");
741     return (null);
742     }
743
744     // check file
745
try {
746         istream = new BufferedInputStream (new FileInputStream
747                 (fpath));
748
749         p = new ObjectInputStream(istream);
750     } catch (Exception JavaDoc e) {
751         handleException (e);
752         return (null);
753     }
754
755     try {
756         obj = p.readObject();
757         p.close();
758     } catch (Exception JavaDoc e) {
759         handleException (e);
760     }
761
762     return (obj);
763
764    }
765
766
767
768    // handle_message_trace:
769

770    private void handle_message_trace (JtMessage msg) {
771
772         String JavaDoc nl = System.getProperty("line.separator");
773     String JavaDoc tmp;
774
775
776     
777     tmp = "JtMessage.MsgId:" + msg.getMsgId ();
778         if (msg.getMsgSubject () != null)
779        tmp +=nl+ "JtMessage.MsgSubject:"+ msg.getMsgSubject();
780         if (msg.getMsgContent () != null)
781        tmp += nl + "JtMessage.MsgContent:"+ msg.getMsgContent();
782     handleTrace (tmp);
783
784    }
785
786    private Object JavaDoc object_name (Object JavaDoc obj) {
787      String JavaDoc name;
788
789      if (!(obj instanceof JtObject))
790        return (obj);
791
792      name = ((JtObject) obj).getObjName ();
793      if (name == null)
794        return (obj);
795
796      return (name);
797    }
798
799    /**
800      * Sends a Jt Message to another object.
801      *
802      * @param id object ID
803      * @param msgid message ID
804      */

805
806    public Object JavaDoc sendMessage (Object JavaDoc id, Object JavaDoc msgid) {
807    Object JavaDoc obj;
808    Object JavaDoc msg;
809    Object JavaDoc reply;
810
811
812 /*
813      if (objSession != null)
814        handleTrace ("Session(" + objSession + "): JtObject.sendMessage:"+
815           object_name (id) + ", "+ object_name (msgid) + " ...");
816      else
817 */

818        handleTrace ("JtObject.sendMessage:"+
819           object_name (id) + ", "+ object_name (msgid) + " ...");
820
821      if (id == null || msgid == null) {
822     handleError ("JtObject.sendMessage: invalid paramenters");
823     return (null);
824      }
825
826      obj = lookupObject (id);
827
828      if (obj == null) {
829     handleError ("JtObject.sendMessage: unable to find object " + id);
830     return (null);
831      }
832     
833      msg = lookupObject (msgid);
834
835      if (msg == null) {
836     handleError ("JtObject.sendMessage: unable to find object " + msgid);
837     return (null);
838      }
839     
840      if (msg instanceof JtMessage)
841     handle_message_trace ((JtMessage) msg);
842
843      // If the recipient object is running in a separate/independent thread,
844
// enqueue the message (Asynchronuos processing)
845

846      if (obj instanceof JtThread)
847        reply = ((JtThread) obj).enqueueMessage ((Object JavaDoc) msg);
848      else
849        reply = ((JtInterface) obj).processMessage ((Object JavaDoc) msg);
850      return (reply);
851
852    }
853
854
855    private Object JavaDoc encodeObject (Object JavaDoc obj) {
856
857      ByteArrayOutputStream stream = new ByteArrayOutputStream ();
858      XMLEncoder e;
859      Object JavaDoc result = null;
860
861
862      if (obj == null)
863        return (null);
864
865      try {
866
867        e = new XMLEncoder(
868                           new BufferedOutputStream(stream));
869        e.writeObject(obj);
870        e.close();
871        result = stream.toString ();
872
873      } catch (Exception JavaDoc ex) {
874        handleException (ex);
875        return (null);
876      }
877      return (result);
878
879    }
880
881    private Object JavaDoc decodeObject (Object JavaDoc obj) {
882
883      ByteArrayInputStream stream;
884      Object JavaDoc result = null;
885      XMLDecoder d;
886      
887
888      if (obj == null)
889        return (null);
890
891      stream = new ByteArrayInputStream (((String JavaDoc) obj).getBytes ());
892
893      try {
894
895        d = new XMLDecoder(
896                           new BufferedInputStream(stream));
897        result = d.readObject();
898        d.close();
899
900      } catch (Exception JavaDoc ex) {
901        handleException (ex);
902      }
903      return (result);
904
905    }
906
907    /**
908      * Process a Jt Message. This is the only method required by the Jt interface (Jt Interface).
909      *
910      *
911      * @param message Jt Message
912      */

913
914
915    public Object JavaDoc processMessage (Object JavaDoc message) {
916
917      String JavaDoc msgid;
918      JtMessage msg = (JtMessage) message;
919
920      // handleTrace ("JtObject.processMessage called");
921
if (msg == null)
922        return (null);
923
924      msgid = (String JavaDoc) msg.getMsgId ();
925
926      if (msgid == null)
927        return (null);
928
929      // Remove this object
930
if (msgid.equals ("JtREMOVE")) {
931        return (null);
932      }
933
934      if (msgid.equals ("JtSET_VALUE")) {
935        setValue (msg.getMsgSubject (),
936                  msg.getMsgContent (),
937                  msg.getMsgData());
938        return (null);
939      }
940
941      if (msgid.equals ("JtGET_VALUE")) {
942        if (msg.getMsgSubject () == null)
943          return (getValue (this,
944                  msg.getMsgContent ()));
945        else
946          return (getValue (msg.getMsgSubject (),
947                  msg.getMsgContent ()));
948
949      }
950
951      if (msgid.equals ("JtCREATE_OBJECT")) {
952        createObject (msg.getMsgContent (),
953                  msg.getMsgData());
954        return (null);
955      }
956
957      if (msgid.equals ("JtREMOVE_OBJECT")) {
958        removeObject (msg.getMsgContent ());
959        return (null);
960      }
961
962      if (msgid.equals ("JtSEND_MESSAGE")) {
963        return (sendMessage (msg.getMsgContent (),
964                     msg.getMsgData ()));
965
966      }
967
968      if (msgid.equals ("JtCOPY_OBJECT")) {
969        return (copyObject (msg.getMsgContent (),
970                     msg.getMsgData ()));
971
972      }
973
974      // Encode Object (XML format)
975

976      if (msgid.equals ("JtENCODE_OBJECT")) {
977        return (encodeObject (msg.getMsgContent ()));
978      }
979
980      if (msgid.equals ("JtDECODE_OBJECT")) {
981        return (decodeObject (msg.getMsgContent ()));
982      }
983
984      if (msgid.equals ("JtPRINT_OBJECT")) {
985        System.out.println (encodeObject (this));
986        return (this);
987      }
988
989      handleError ("JtObject.processMessage: invalid msg ID:"
990      + msg.getMsgId ());
991      return (null);
992    }
993
994    // Open log file
995

996    private void open_logfile () {
997      FileOutputStream fs;
998
999           if (logFile == null || logFile.equals (""))
1000            return;
1001
1002          if (logFile.equals ("stderr")) { // stderr
1003
logStream = null;
1004            return;
1005          }
1006
1007          try {
1008            fs = new FileOutputStream (logFile);
1009            logStream = new PrintWriter (fs);
1010          } catch (Exception JavaDoc e) {
1011            logStream = null;
1012            handleException (e);
1013            return;
1014          }
1015
1016          handleTrace ("JtObject.open_logfile: opened log file ... " +
1017            logFile);
1018          //handleTrace ("JtObject.open_logfile:user.dir:" +
1019
// System.getProperty ("user.dir"));
1020
//handleTrace ("JtObject.open_logfile:user.home:" +
1021
// System.getProperty ("user.home"));
1022
}
1023
1024   // Initialize: initialize Jt
1025

1026   void initialize () {
1027
1028      String JavaDoc rfile;
1029
1030      logFile = System.getProperty ("Log");
1031      rfile = System.getProperty ("Resources");
1032
1033      if (rfile != null)
1034        setResourceFile (rfile);
1035
1036      if (logFile != null) {
1037    log = 1; // show debugging messages
1038
this.setObjTrace (1);
1039        open_logfile ();
1040      }
1041      //if (logFile != null)
1042
//open_logfile ();
1043

1044      handleTrace ("Initializing Jt " + version + "...");
1045      load_resources ();
1046    
1047   }
1048
1049
1050   // realize
1051
void realize () {
1052
1053   }
1054
1055   // activate
1056
void activate () {
1057
1058   }
1059
1060
1061   // destroy
1062
void destroy () {
1063
1064   }
1065
1066   /**
1067     * Handles exceptions. Jt provides a consistent way of handling exceptions:
1068     * The exception is stored using the objException attribute.
1069     * The exception message and the stack trace are sent to the screen or a log file.
1070     * This method should be called each time an exception is detected.
1071     * Overide this method if your application requires special exception handling.
1072     * @param e exception
1073     */

1074
1075   public void handleException (Throwable JavaDoc e) {
1076
1077    // An exception has occured. Update the objException attribute
1078
objException = e;
1079    e.printStackTrace ();
1080
1081        if (logStream == null)
1082           return;
1083
1084        logStream.println (e);
1085        logStream.flush ();
1086   }
1087
1088
1089   /**
1090     * Handles trace messages. This method should be called each time a
1091     * message needs to be logged. Trace messages are send to the screen or a log file
1092     * depending on the logFile attribute. The objTrace attribute is used to enable/disable
1093     * logging. Override this method if your application requires special logging capabilities.
1094     * @param msg trace message
1095     */

1096   
1097   public void handleTrace (String JavaDoc msg) {
1098
1099    if (objTrace <= 0)
1100          return;
1101
1102        if (logStream == null) {
1103       System.err.println (msg);
1104           return;
1105        }
1106
1107        logStream.println (msg);
1108        logStream.flush ();
1109   }
1110
1111   /**
1112     * Handles warning messages. This method should be called each time a warning
1113     * message needs to be logged. Trace messages are send to the screen or a log file
1114     * depending on the logFile attribute. Warning messages are always logged regardless
1115     * of the value of the objTrace attribute.
1116     * @param msg trace message
1117     */

1118
1119   public void handleWarning (String JavaDoc msg) {
1120
1121/*
1122        if (objTrace > 0)
1123*/

1124           
1125        if (logStream == null) {
1126           System.err.println (msg);
1127           return;
1128        }
1129
1130        logStream.println (msg);
1131        logStream.flush ();
1132   }
1133
1134   // handleError: handle error messages
1135

1136   /**
1137     * Handles error messages. This method generates a JtException which
1138     * is handled by the handleException method.
1139     * This causes the error message and the stack trace to be sent to the screen or a log file.
1140     * This method should be called each time an error is detected.
1141     * Override this method if your application requires special error handling.
1142     * @param msg error message
1143     */

1144
1145   public void handleError (String JavaDoc msg) {
1146    try {
1147
1148      // generate a JtException
1149
throw new JtException (msg);
1150    
1151    } catch (JtException e) {
1152
1153       handleException (e);
1154    }
1155
1156   }
1157
1158
1159
1160   // add: add an object to the Object table
1161

1162   private void add (String JavaDoc id, Object JavaDoc obj) {
1163   //private synchronized void add (String id, Object obj) {
1164

1165     Hashtable ht;
1166
1167    if (id == null || obj == null)
1168       return;
1169
1170
1171// if (objSession == null) {
1172

1173          if (objTable == null)
1174            objTable = new Hashtable ();
1175          objTable.put (id, obj);
1176// handleTrace ("JtObject.add:" + id + ":" + obj);
1177
return;
1178// }
1179

1180/*
1181        if (sessionTable == null)
1182          sessionTable = new Hashtable ();
1183
1184   
1185        ht = (Hashtable) sessionTable.get (objSession);
1186
1187        if (ht == null) {
1188          
1189          ht = new Hashtable ();
1190          sessionTable.put (objSession, ht);
1191          //handleTrace ("JtObject.add: new session: " + objSession);
1192        }
1193 
1194
1195        ht.put (id, obj);
1196*/

1197   }
1198
1199   // remove: remove an object from the object table
1200

1201   //private synchronized Object remove (String id) {
1202
private Object JavaDoc remove (Object JavaDoc id) {
1203
1204     Hashtable ht;
1205
1206    if (id == null)
1207       return (null);
1208
1209// if (objSession == null) {
1210

1211          if (objTable == null)
1212            return (null);
1213
1214          if (objTable.get (id) == null)
1215            handleError ("JtObject.remove: unable to remove object (not found):" +
1216              id);
1217
1218          return (objTable.remove (id));
1219// }
1220

1221/*
1222        if (sessionTable == null)
1223          return (null);
1224
1225        ht = (Hashtable) sessionTable.get (objSession);
1226
1227        if (ht == null) {
1228          handleError ("JtObject.remove: invalid session table");
1229          return (null);
1230        }
1231
1232        return (ht.remove (id));
1233*/

1234   }
1235
1236
1237
1238   /**
1239     * Gets the name of the file used for logging purposes (logFile).
1240     */

1241
1242
1243   public String JavaDoc getLogFile() {
1244    return logFile;
1245   }
1246
1247
1248   /**
1249     * Specifies the file to be used for logging purposes (logFile).
1250     * @param newLogFile name of the log file
1251     */

1252
1253   public void setLogFile(String JavaDoc newLogFile) {
1254
1255    if (newLogFile != null && logFile != null)
1256      if (newLogFile.equals(logFile))
1257        return;
1258
1259    logFile = newLogFile;
1260
1261    log = 1;
1262    this.setObjTrace (1);
1263    if (logFile != null)
1264      open_logfile ();
1265
1266   }
1267
1268
1269   /**
1270     * Gets the name of the Jt resource file. The default value for this attribute is '.Jtrc'.
1271     * Attribute values are loaded from this resource file just after the object is created.
1272     */

1273
1274   public String JavaDoc getResourceFile() {
1275    return resourceFile;
1276   }
1277
1278
1279   /**
1280     * Specifies the file to be used as the Jt resource file. The default value for this attribute is '.Jtrc'.
1281     * Attribute values are loaded from this resource file just after the object is created.
1282     * @param newResourceFile Jt resource file
1283     */

1284
1285   public void setResourceFile(String JavaDoc newResourceFile) {
1286    resourceFile = newResourceFile;
1287
1288    if (resourceFile != null)
1289      load_resources ();
1290
1291   }
1292
1293
1294   /**
1295     * Gets the value of the object ID. This attribute contains the qualified name of the object.
1296     */

1297
1298   public String JavaDoc getObjName() {
1299    return objName;
1300   }
1301
1302
1303   /**
1304     * Sets the value of the object ID. This attribute contains the qualified name of the object.
1305     */

1306
1307   public void setObjName(String JavaDoc newObjName) {
1308    objName = newObjName;
1309   }
1310
1311   // Object Id (Being
1312

1313
1314   long getObjId() {
1315    return objId;
1316   }
1317
1318   void setObjId(long newObjId) {
1319    objId = newObjId;
1320   }
1321
1322
1323
1324   /**
1325     * Gets the value of objTrace. This attribute enables/disables the logging of trace messages.
1326     */

1327
1328   public int getObjTrace() {
1329    return objTrace;
1330   }
1331
1332   /**
1333     * Gets the value of objTrace. This attribute enables/disables the logging of trace messages.
1334     */

1335
1336   public void setObjTrace(int newObjTrace) {
1337    objTrace = newObjTrace;
1338   }
1339
1340
1341   /**
1342     * Gets the object status (objStatus). Some framework classes use this attribute in order
1343     * to store status information.
1344     */

1345
1346   public int getObjStatus() {
1347    return objStatus;
1348   }
1349
1350
1351   /**
1352     * Sets the object status (objStatus). Some framework classes use this attribute in order
1353     * to store status information.
1354     */

1355
1356   public void setObjStatus(int newObjStatus) {
1357    objStatus = newObjStatus;
1358   }
1359
1360   // Object path
1361

1362/*
1363   public String getObjPath() {
1364    return objPath;
1365   }
1366
1367   public void setObjPath(String newObjPath) {
1368    objPath = newObjPath;
1369   }
1370*/

1371
1372   /**
1373     * Gets the value of objException. This attribute is used to store exceptions detected
1374     * while processing messages. The handleException method updates this attribute.
1375     * Since handleError invokes handleException, it also updates this attribute.
1376     */

1377
1378   public Object JavaDoc getObjException() {
1379    return objException;
1380   }
1381
1382   /**
1383     * Sets the value of objException. This attribute is used to store exceptions detected
1384     * while processing messages. The handleException method updates this attribute.
1385     * Since handleError invokes handleException, it also updates this attribute.
1386     */

1387
1388   public void setObjException(Object JavaDoc newObjException) {
1389    objException = newObjException;
1390   }
1391
1392
1393   // Session
1394

1395/*
1396   public Object getObjSession() {
1397    return objSession;
1398   }
1399*/

1400
1401/*
1402   public void setObjSession(Object newObjSession) {
1403
1404    //handleTrace ("JtObject.setObjSession:" + newObjSession);
1405    objSession = newObjSession;
1406   }
1407*/

1408
1409  // create_dir: create the parent directory
1410

1411  void create_dir (String JavaDoc name) {
1412   File file;
1413   String JavaDoc parentpath;
1414
1415        if (name == null)
1416           return;
1417
1418        file = new File (name);
1419        if (file == null) {
1420           handleError ("JtFile: unable to create File object:" + name);
1421           return;
1422        }
1423
1424        parentpath = file.getParent ();
1425        if (parentpath == null)
1426           return;
1427
1428        //file = file.getParentFile ();
1429
file = new File (parentpath);
1430        if (file == null) {
1431           handleError ("JtFile: unable to get parent File:" + name);
1432           return;
1433        }
1434
1435        if (!file.exists ())
1436             if (!file.mkdirs ())
1437                     handleError ("JtFile: unable to create directories:" +
1438                                parentpath);
1439  }
1440
1441
1442  JtResource parse_resource (String JavaDoc line) {
1443
1444    String JavaDoc resource_class, tmp;
1445    int index;
1446    int length;
1447    JtResource res;
1448
1449    if (line == null)
1450      return (null);
1451
1452    length = line.length ();
1453
1454    if (length == 0)
1455      return (null);
1456
1457    index = line.indexOf (":");
1458
1459    if (index < 0)
1460      return (null);
1461    
1462    if (index == length - 1)
1463      return (null);
1464
1465    res = new JtResource ();
1466
1467    res.value = line.substring (index+1, length);
1468
1469    tmp = line.substring (0, index);
1470
1471    index = tmp.lastIndexOf (".");
1472
1473    if (index == -1)
1474      return (null);
1475
1476    if (index == tmp.length () - 1)
1477      return (null); // ends with a dot ?
1478

1479    res.rclass = tmp.substring (0, index);
1480    res.name = tmp.substring (index + 1);
1481
1482    handleTrace ("Jt Resource: " + "(" +
1483       res.rclass + "," + res.name + "," + res.value
1484       + ")");
1485   
1486    return (res);
1487
1488  }
1489
1490  private void load_object_resources (Object JavaDoc obj,
1491    Object JavaDoc class_name) {
1492
1493    Hashtable ht;
1494    Enumeration rnames;
1495    Object JavaDoc resource;
1496
1497 
1498    if (resTable == null)
1499      resTable = new Hashtable ();
1500
1501    if (obj == null || class_name == null)
1502       return;
1503
1504    ht = (Hashtable) resTable.get (class_name);
1505
1506    if (ht == null)
1507      return; // check
1508

1509    rnames = ht.keys ();
1510    if (rnames == null)
1511      return;
1512
1513    handleTrace ("Jt: Loading Jt resources into object ...");
1514    while (rnames.hasMoreElements ()) {
1515      resource = rnames.nextElement ();
1516      setValue (obj, resource, ht.get (resource));
1517    }
1518    handleTrace ("Jt: Loaded Jt resources");
1519  }
1520
1521  private void update_resources (JtResource res) {
1522    Hashtable ht;
1523
1524    if (res == null)
1525      return;
1526
1527    if (res.rclass == null)
1528      return;
1529
1530    if (resTable == null)
1531      resTable = new Hashtable ();
1532
1533    if (resTable.get (res.rclass) == null) {
1534      resTable.put (res.rclass, new Hashtable ());
1535    }
1536
1537    ht = (Hashtable) resTable.get (res.rclass);
1538
1539    if (ht == null)
1540      return; // check
1541

1542    ht.put (res.name, res.value);
1543  }
1544    
1545  void load_resources ( ) {
1546    String JavaDoc line;
1547    JtResource res;
1548    File file;
1549
1550    if (resourceFile == null)
1551      return;
1552
1553    file = new File (resourceFile);
1554
1555    if (!file.exists ())
1556      return;
1557
1558    handleTrace ("Jt: reading resources from " +
1559     resourceFile + " ...");
1560    try {
1561      BufferedReader d = new BufferedReader
1562        (new FileReader (resourceFile));
1563
1564      while ((line = d.readLine ()) != null) {
1565        //System.out.println ("JtFile.read_lines:" + line);
1566
if (line.startsWith ("!") ||
1567          line.startsWith ("//"))
1568          continue;
1569        res = parse_resource (line);
1570
1571        if (res != null)
1572          update_resources (res);
1573      }
1574
1575    } catch (Exception JavaDoc ex) {
1576      handleException (ex);
1577    }
1578  }
1579
1580  /**
1581   * Unit tests the messages processed by JtObject
1582   */

1583
1584  public static void main(String JavaDoc[] args) {
1585
1586    JtObject main = new JtObject ();
1587    JtMessage msg;
1588    String JavaDoc tmp;
1589    JtObject main1;
1590
1591    //main.setObjTrace (1);
1592
//main.setResourceFile (".Jtrc1");
1593
//main.setLogFile ("log.txt");
1594

1595
1596    // Create the object
1597

1598    msg = (JtMessage) main.createObject ("Jt.JtMessage", "message");
1599
1600
1601
1602    if (main.lookupObject ("message") != null)
1603    System.out.println ("Jt.createObject: GO");
1604    else
1605    System.out.println ("Jt.createObject: FAILED");
1606
1607    // Set Value
1608

1609    main.setValue ("message", "msgId", "JtTestId");
1610
1611    if (msg.getMsgId () != null)
1612    if (msg.getMsgId().equals ("JtTestId"))
1613       System.out.println ("Jt.setValue: GO");
1614    else
1615       System.out.println ("Jt.setValue: FAILED");
1616    else
1617       System.out.println ("Jt.setValue: FAILED");
1618
1619
1620    //main.sendMessage (main, "message");
1621

1622    // Get value
1623

1624    tmp = (String JavaDoc) main.getValue ("message", "msgId");
1625
1626    if (tmp != null)
1627    if (tmp.equals ("JtTestId"))
1628       System.out.println ("Jt.getValue: GO");
1629    else
1630       System.out.println ("Jt.getValue: FAILED");
1631    else
1632       System.out.println ("Jt.getValue: FAILED");
1633
1634    main.removeObject ("message");
1635
1636    if (main.lookupObject ("message") == null) {
1637    System.out.println ("Jt.removeObject: GO");
1638    } else
1639    System.out.println ("Jt.removeObject: FAILED");
1640 
1641    // qualified names
1642

1643    main.setObjName ("main");
1644    msg = (JtMessage) main.createObject ("Jt.JtMessage", "message");
1645
1646    if (main.lookupObject ("main.message") != null) {
1647    System.out.println ("Jt.createObject (main.message): GO");
1648    } else
1649    System.out.println ("Jt.createObject (main.message): FAILED");
1650
1651    if (main.lookupObject ("message") != null) {
1652    System.out.println ("Jt.lookupObject (main.message): GO");
1653    } else
1654    System.out.println ("Jt.lookupObject (main.message): FAILED");
1655
1656    main.removeObject ("message");
1657
1658    if (main.lookupObject ("message") == null
1659    && main.lookupObject ("main.message") == null) {
1660    System.out.println ("Jt.removeObject (main.message): GO");
1661    } else
1662    System.out.println ("Jt.removeObject (main.message): FAILED");
1663
1664
1665/*
1666    msg = (JtMessage) main.createObject ("Jt.JtMessage", "main.message");
1667
1668    main.setValue ("message", "msgContent", "hello");
1669    main.setValue ("message", "objPath", "kk/message");
1670    msg.save ();
1671    JtMessage obj = new JtMessage ();
1672    obj.setObjPath ("kk/message");
1673 
1674    obj = (JtMessage) obj.restore ();
1675
1676    System.out.println ("JtObject after restore (name):" + obj.getMsgContent ());
1677*/

1678
1679    // handleWarning
1680

1681    //main.handleWarning ("JtObject: this is a warning");
1682
main.handleTrace ("JtObject: this is a trace");
1683
1684
1685
1686  }
1687}
1688
Popular Tags