KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > syncclient > demo > MainWindow


1 /**
2  * Copyright (C) 2003-2005 Funambol
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18
19 package sync4j.syncclient.demo;
20
21 import java.awt.BorderLayout JavaDoc;
22 import java.awt.CardLayout JavaDoc;
23 import java.awt.Frame JavaDoc;
24 import java.awt.Image JavaDoc;
25 import java.awt.Panel JavaDoc;
26 import java.awt.Toolkit JavaDoc;
27 import java.awt.event.WindowAdapter JavaDoc;
28 import java.awt.event.WindowEvent JavaDoc;
29
30 import java.io.File JavaDoc;
31 import java.io.FileInputStream JavaDoc;
32 import java.io.FileOutputStream JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.io.PrintStream JavaDoc;
35
36 import java.text.SimpleDateFormat JavaDoc;
37
38 import java.util.Arrays JavaDoc;
39 import java.util.Date JavaDoc;
40 import java.util.HashMap JavaDoc;
41 import java.util.Hashtable JavaDoc;
42 import java.util.Properties JavaDoc;
43 import java.util.Vector JavaDoc;
44
45 import sync4j.foundation.pdi.contact.Contact;
46 import sync4j.foundation.pdi.converter.Converter;
47 import sync4j.foundation.pdi.converter.ConverterException;
48 import sync4j.foundation.pdi.event.Calendar;
49 import sync4j.foundation.pdi.parser.*;
50
51 import sync4j.syncclient.common.SourceUtils;
52 import sync4j.syncclient.common.logging.Logger;
53
54 import sync4j.syncclient.demo.logging.PanelHandler;
55
56 import sync4j.syncclient.spdm.DMException;
57 import sync4j.syncclient.spdm.ManagementNode;
58 import sync4j.syncclient.spdm.SimpleDeviceManager;
59
60 import sync4j.syncclient.spds.SyncManager;
61
62 import sync4j.syncclient.spds.event.SyncEvent;
63 import sync4j.syncclient.spds.event.SyncItemEvent;
64 import sync4j.syncclient.spds.event.SyncSourceEvent;
65 import sync4j.syncclient.spds.event.SyncStatusEvent;
66 import sync4j.syncclient.spds.event.SyncTransportEvent;
67 import sync4j.syncclient.spds.event.SyncListener;
68 import sync4j.syncclient.spds.event.SyncItemListener;
69 import sync4j.syncclient.spds.event.SyncSourceListener;
70 import sync4j.syncclient.spds.event.SyncStatusListener;
71 import sync4j.syncclient.spds.event.SyncTransportListener;
72
73 import com.funambol.commons.io.FileTools;
74
75 import org.xml.sax.SAXException JavaDoc;
76
77 /**
78  * The main window for the SyncClient Demo GUI.
79  *
80  * @author Fabio Maggi @ Funambol
81  * @author Alessandro Morandi, Giorgio Orsi
82  * @version $Id: MainWindow.java,v 1.32 2005/07/14 16:03:24 nichele Exp $
83  *
84  */

85 public class MainWindow
86 extends Frame JavaDoc
87 implements
88 ConfigurationParameters ,
89 SyncItemListener ,
90 SyncListener ,
91 SyncSourceListener ,
92 SyncStatusListener ,
93 SyncTransportListener {
94
95     // --- Folders Tree ---
96
//
97
// + (root)
98
// |+ config
99
// ||+ spds
100
// |||+ sources
101
// ||||- contact.properties
102
// ||||- calendar.properties
103
// |||
104
// |||- syncml.properties
105
// ||
106
// ||+ xml
107
// |||- init.xml
108
// |||- map.xml
109
// |||- mod.xml
110
// ||
111
// ||- application.properties
112
// |
113
// |+ db
114
// |+ contacts
115
// |+ calendar
116

117     //---------------------------------------------------------- Constants
118

119     public static final String JavaDoc DIR_CONTACTS = "contacts" ;
120     public static final String JavaDoc DIR_CALENDAR = "calendar" ;
121     public static final String JavaDoc DM_VALUE_PATH = "spds/syncml" ;
122     public static final String JavaDoc DM_VALUE_CONTACT_PATH = "spds/sources/contact" ;
123     public static final String JavaDoc DM_VALUE_CALENDAR_PATH = "spds/sources/calendar" ;
124
125     public static final String JavaDoc PROP_CHARSET = "spds.charset" ;
126     public static final String JavaDoc PROP_WD = "wd" ;
127
128     public static final String JavaDoc DATE_FORMAT = "yyyyMMdd'T'HHmmss" ;
129
130     public static final String JavaDoc ROOT_DIRECTORY = "config" ;
131
132     public static final String JavaDoc VALUE_UTF8 = "UTF8" ;
133
134     public static final String JavaDoc XML_VERSION
135         = "<?xml version=\"1.0\" encoding=\"" +
136           System.getProperty("file.encoding") +
137           "\"?>" ;
138
139     //---------------------------------------------------------- Protected data
140

141     /**
142      * A list of Contact objects
143      */

144     protected Vector JavaDoc contacts ;
145
146     /**
147      * A list of Calendar objects
148      */

149     protected Vector JavaDoc calendars ;
150
151     //---------------------------------------------------------- Private data
152

153     /**
154      * DM root node
155      */

156     private ManagementNode rootNode = null ;
157
158     /**
159      * DM values from DM_VALUE_PATH
160      */

161     private Hashtable JavaDoc syncmlValues = null ;
162
163     /**
164      * DM values from DM_VALUE_CONTACT_PATH
165      */

166     private Hashtable JavaDoc xmlContactValues = null ;
167
168     /**
169      * DM values from DM_VALUE_CALENDAR_PATH
170      */

171     private Hashtable JavaDoc xmlCalendarValues = null ;
172
173     /**
174      * Current index in the contacts Vector
175      */

176     private Integer JavaDoc currentIndex = null ;
177
178     /**
179      * The root directory
180      */

181     private String JavaDoc rootDirectory = null ;
182
183     /**
184      * The source directory
185      */

186     private String JavaDoc sourceDirectory = "db" ;
187
188     private CardLayout JavaDoc cardLayout = null ;
189     private Panel JavaDoc mainPanel = null ;
190     private DemoMenuBar menubar = null ;
191     private CalendarNew calNew = null ;
192     private CalendarList calList = null ;
193     private CalendarModify calendarModify = null ;
194     private ContactNew contNew = null ;
195     private ContactList contList = null ;
196     private ContactModify contactModify = null ;
197
198     private PanelHandler panelHandler = null ;
199     private Configuration config = null ;
200
201     private Language ln = new Language() ;
202     private Logger logger = new Logger () ;
203
204     //---------------------------------------------------------- Public methods
205

206     /**
207      * Creates a new main window. This constructor also initializes the logger,
208      * the DeviceManager and fetches synchronization and contacts informations
209      * from the filesystem
210      */

211     public MainWindow() {
212
213         super ();
214         setTitle (ln.getString("sync4j_sync_client_pim_demo"));
215
216         Image JavaDoc icon = Toolkit.getDefaultToolkit().getImage(FRAME_ICONNAME);
217
218         setIconImage(icon);
219
220         Panel JavaDoc bottomPanel = null ;
221         Properties JavaDoc props = null ;
222
223         contacts = new Vector JavaDoc () ;
224         calendars = new Vector JavaDoc () ;
225
226         rootDirectory = System.getProperty(PROP_WD);
227
228         props = System.getProperties();
229         if (System.getProperty(SimpleDeviceManager.PROP_DM_DIR_BASE) == null) {
230             props.put(SimpleDeviceManager.PROP_DM_DIR_BASE ,
231                       buildPath(rootDirectory, ROOT_DIRECTORY));
232             System.setProperties(props);
233         }
234         props = System.getProperties();
235         props.put(PROP_CHARSET, VALUE_UTF8);
236         System.setProperties(props);
237
238         sourceDirectory = buildPath(rootDirectory,sourceDirectory);
239
240         //
241
// --- Device Manager ---
242
//
243
rootNode = SimpleDeviceManager.getDeviceManager().getManagementTree();
244
245         try {
246             syncmlValues = rootNode.getNodeValues ( DM_VALUE_PATH ) ;
247             xmlContactValues = rootNode.getNodeValues ( DM_VALUE_CONTACT_PATH ) ;
248             xmlCalendarValues = rootNode.getNodeValues ( DM_VALUE_CALENDAR_PATH ) ;
249         } catch (DMException exc) {
250
251             if (logger.isLoggable(Logger.DEBUG)) {
252                 logger.debug(ln.getString ("cannot_find_devicemanager_values") +
253                              " " +
254                              exc.getMessage() );
255             }
256
257         }
258
259         //
260
// --- Layout Creation ---
261
//
262
setSize(440,495);
263         setLocation(400,200);
264
265         setLayout(new BorderLayout JavaDoc());
266         mainPanel = new Panel JavaDoc();
267
268         //
269
// A little trick to add blank space on the bottom of the window
270
//
271
bottomPanel = new Panel JavaDoc();
272         bottomPanel.setSize(240, 5);
273
274         cardLayout = new CardLayout JavaDoc();
275         mainPanel.setLayout(cardLayout);
276
277         menubar = new DemoMenuBar(this) ;
278         contList = new ContactList(this) ;
279
280         refresh();
281
282         contactModify = new ContactModify (this) ;
283         calendarModify = new CalendarModify (this) ;
284         contNew = new ContactNew (this) ;
285         panelHandler = new PanelHandler (this) ;
286         config = new Configuration (this) ;
287
288         calList = new CalendarList(this);
289         calNew = new CalendarNew(this);
290
291         //
292
// Add a menu and all the components to the card layout
293
//
294
setMenuBar(menubar);
295
296         mainPanel.add(contList , KEY_CONTACTLIST ) ;
297         mainPanel.add(contactModify , KEY_CONTACTMODIFY ) ;
298         mainPanel.add(calendarModify , KEY_CALENDARMODIFY ) ;
299         mainPanel.add(contNew , KEY_CONTACTNEW ) ;
300         mainPanel.add(panelHandler , KEY_SYNC ) ;
301         mainPanel.add(config , KEY_CONFIG ) ;
302         mainPanel.add(calList , KEY_CALENDARLIST ) ;
303         mainPanel.add(calNew , KEY_CALENDARNEW ) ;
304
305         add(mainPanel,BorderLayout.CENTER);
306         add(bottomPanel,BorderLayout.SOUTH);
307
308         // Default card
309
cardLayout.show(mainPanel, KEY_CONTACTLIST);
310
311         // Add the listeners
312
addWindowListener(new WindowAdapter JavaDoc() {
313             public void windowClosing(WindowEvent JavaDoc evt) {
314                 exit();
315             }
316         } );
317     }
318
319     /**
320      * Refreshes the contact list reading the local vCard files
321      */

322     public void refresh() {
323         contacts = getContacts();
324         contList.fillList();
325         show(KEY_CONTACTLIST);
326     }
327
328
329     /**
330      * Notify Synchronization begin
331      *
332      * @param event
333      */

334     public void syncBegin(SyncEvent event) {
335         if (logger.isLoggable(Logger.DEBUG)) {
336             logger.debug("SyncEvent - Sync begin - date: " +
337                          event.getDate() );
338         }
339     }
340
341     /**
342      * Notify Synchronization end
343      *
344      * @param event
345      */

346     public void syncEnd(SyncEvent event) {
347         if (logger.isLoggable(Logger.DEBUG)) {
348             logger.debug("SyncEvent - Sync end - date: " +
349                          event.getDate() );
350         }
351     }
352
353     /**
354      * Notify send initialization message
355      *
356      * @param event
357      */

358     public void sendInitialization(SyncEvent event) {
359         if (logger.isLoggable(Logger.DEBUG)) {
360             logger.debug("SyncEvent - Send initialization - date: " +
361                          event.getDate() );
362         }
363     }
364
365     /**
366      * Notify send modification message
367      *
368      * @param event
369      */

370     public void sendModification(SyncEvent event) {
371         if (logger.isLoggable(Logger.DEBUG)) {
372             logger.debug("SyncEvent - Send modification - date: " +
373                          event.getDate() );
374         }
375     }
376
377     /**
378      * Notify send finalization message
379      *
380      * @param event
381      */

382     public void sendFinalization(SyncEvent event) {
383         if (logger.isLoggable(Logger.DEBUG)) {
384             logger.debug("SyncEvent - Send finalization - date: " +
385                          event.getDate() );
386         }
387     }
388
389     /**
390      * Notify that the engine encountered a not blocking error
391      *
392      * @param event
393      */

394     public void syncError(SyncEvent event) {
395         if (logger.isLoggable(Logger.DEBUG)) {
396             logger.debug("SyncEvent - Sync error - date: " +
397                          event.getDate () +
398                          " - message: " +
399                          event.getMessage () +
400                          " - cause: " +
401                          event.getCause().getMessage() );
402         }
403     }
404
405     /**
406      * Notify a syncSource begin synchronization
407      *
408      * @param event
409      */

410     public void syncBegin(SyncSourceEvent event) {
411         if (logger.isLoggable(Logger.DEBUG)) {
412             logger.debug("SyncSourceEvent - Sync begin - date: " +
413                          event.getDate () +
414                          " - sourceUri: " +
415                          event.getSourceUri () +
416                          " - sync mode: " +
417                          event.getSyncMode () );
418         }
419     }
420
421     /**
422      * Notify a syncSource end synchronization
423      *
424      * @param event
425      */

426     public void syncEnd(SyncSourceEvent event) {
427         if (logger.isLoggable(Logger.DEBUG)) {
428             logger.debug("SyncSourceEvent - Sync end - date: " +
429                          event.getDate () +
430                          " - sourceUri: " +
431                          event.getSourceUri () +
432                          " - sync mode: " +
433                          event.getSyncMode () );
434         }
435     }
436
437     /**
438      * Notify SyncStransport begin send data
439      *
440      * @param event
441      */

442     public void sendDataBegin(SyncTransportEvent event) {
443         if (logger.isLoggable(Logger.DEBUG)) {
444             logger.debug
445                 ("SyncTransportEvent - Send data begin - data length: " +
446                   event.getData() );
447         }
448     }
449
450     /**
451      * Notify SyncStransport end send data
452      *
453      * @param event
454      */

455     public void sendDataEnd(SyncTransportEvent event) {
456         if (logger.isLoggable(Logger.DEBUG)) {
457             logger.debug
458                 ("SyncTransportEvent - Send data end - data length: " +
459                  event.getData() );
460         }
461     }
462
463     /**
464      * Notify SyncStransport begin receive data
465      *
466      * @param event
467      */

468     public void receiveDataBegin(SyncTransportEvent event) {
469         if (logger.isLoggable(Logger.DEBUG)) {
470             logger.debug
471                 ("SyncTransportEvent - Receive data begin - data length: " +
472                  event.getData() );
473         }
474     }
475
476     /**
477      * Notify SyncStransport receiving data
478      *
479      * @param event
480      */

481     public void dataReceived(SyncTransportEvent event) {
482         if (logger.isLoggable(Logger.DEBUG)) {
483             logger.debug
484                 ("SyncTransportEvent - Data received - data length: " +
485                  event.getData() );
486         }
487     }
488
489     /**
490      * Notify SyncStransport end receive data
491      *
492      * @param event
493      */

494     public void receiveDataEnd(SyncTransportEvent event) {
495         if (logger.isLoggable(Logger.DEBUG)) {
496             logger.debug
497                 ("SyncTransportEvent - Received data end - data length: " +
498                  event.getData() );
499         }
500     }
501
502     /**
503      * Notify an item added by the server
504      *
505      * @param event
506      */

507     public void itemAddedByServer(SyncItemEvent event) {
508         if (logger.isLoggable(Logger.DEBUG)) {
509             logger.debug
510                 ("SyncItemEvent - Item added by server - sourceUri: " +
511                  event.getSourceUri() +
512                  " - key: " +
513                  event.getItemKey().getKeyAsString() );
514         }
515     }
516
517     /**
518      * Notify an item deleted by the server
519      *
520      * @param event
521      */

522     public void itemDeletedByServer(SyncItemEvent event) {
523         if (logger.isLoggable(Logger.DEBUG)) {
524             logger.debug
525                 ("SyncItemEvent - Item deleted by server - sourceUri: " +
526                  event.getSourceUri() +
527                  " - key: " +
528                  event.getItemKey().getKeyAsString() );
529         }
530     }
531
532     /**
533      * Notify an item updated by the server
534      *
535      * @param event
536      */

537     public void itemUpdatedByServer(SyncItemEvent event) {
538         if (logger.isLoggable(Logger.DEBUG)) {
539             logger.debug
540                 ("SyncItemEvent - Item updated by server - sourceUri: " +
541                  event.getSourceUri() +
542                  " - key: " +
543                   event.getItemKey().getKeyAsString() );
544         }
545     }
546
547     /**
548      * Notify an item added by the client
549      *
550      * @param event
551      */

552     public void itemAddedByClient(SyncItemEvent event) {
553         if (logger.isLoggable(Logger.DEBUG)) {
554             logger.debug
555                 ("SyncItemEvent - Item added by client - sourceUri: " +
556                  event.getSourceUri() +
557                  " - key: " +
558                  event.getItemKey().getKeyAsString() );
559         }
560     }
561
562     /**
563      * Notify an item delete by the client
564      *
565      * @param event
566      */

567     public void itemDeletedByClient(SyncItemEvent event) {
568         if (logger.isLoggable(Logger.DEBUG)) {
569             logger.debug
570                 ("SyncItemEvent - Item deleted by client - sourceUri: " +
571                   event.getSourceUri() +
572                   " - key: " +
573                   event.getItemKey().getKeyAsString() );
574         }
575     }
576
577     /**
578      * Notify an item updated by the client
579      *
580      * @param event
581      */

582     public void itemUpdatedByClient(SyncItemEvent event) {
583         if (logger.isLoggable(Logger.DEBUG)) {
584             logger.debug
585                 ("SyncItemEvent - Item updated by client - sourceUri: " +
586                   event.getSourceUri() +
587                   " - key: " +
588                   event.getItemKey().getKeyAsString() );
589         }
590     }
591
592     /**
593      * Notify a status received from the server
594      *
595      * @param event
596      */

597     public void statusReceived (SyncStatusEvent event) {
598         if (logger.isLoggable(Logger.DEBUG)) {
599             logger.debug
600                 ("SyncStatusEvent - Received status - command: " +
601                  event.getCommand() +
602                  " - status: " +
603                  event.getStatusCode() +
604                  " - sourceUri: " +
605                  event.getSourceUri() +
606                  " - key: " +
607                  event.getItemKey().getKeyAsString() );
608         }
609     }
610
611     /**
612      * Notify create a status to send to the server
613      *
614      * @param event
615      */

616     public void statusToSend (SyncStatusEvent event) {
617         if (logger.isLoggable(Logger.DEBUG)) {
618             logger.debug
619                 ("SyncStatusEvent - Status to send - command: " +
620                  event.getCommand() +
621                  " - status: " +
622                  event.getStatusCode() +
623                  " - sourceUri: " +
624                  event.getSourceUri() +
625                  " - key: " +
626                  event.getItemKey().getKeyAsString() );
627         }
628
629     }
630
631     //---------------------------------------------------------- Protected methods
632

633     /**
634      * Closes the window and stops the application
635      */

636     protected void exit() {
637
638         //
639
// hide the Frame
640
//
641
setVisible(false);
642
643         dispose();
644
645         //
646
// tell windowing system to free resources
647
//
648
if (logger.isLoggable(Logger.INFO)) {
649             logger.info(ln.getString ("logging_stopped"));
650         }
651
652         System.exit(0);
653     }
654
655     /**
656      * Manages the contact synchronization, based on the configuration parameters
657      * provided by the DeviceManager
658      */

659     public void synchronize() {
660
661         panelHandler.setButton(false);
662
663         try {
664
665             if (logger.isLoggable(Logger.INFO)) {
666                 logger.info(ln.getString ("setting_up_sync_manager"));
667             }
668
669             Logger.setHandler(panelHandler);
670             SyncManager syncManager = SyncManager.getSyncManager("");
671
672             syncManager.addSyncItemListener (this) ;
673             syncManager.addSyncListener (this) ;
674             syncManager.addSyncSourceListener (this) ;
675             syncManager.addSyncStatusListener (this) ;
676             syncManager.addSyncTransportListener (this) ;
677
678             if (logger.isLoggable(Logger.INFO)) {
679                 logger.info(ln.getString ("synchronizing"));
680             }
681
682             syncManager.sync();
683
684             if (logger.isLoggable(Logger.INFO)) {
685                 logger.info(ln.getString ("done"));
686             }
687
688             panelHandler.setButton(true);
689
690         } catch (Exception JavaDoc exc) {
691             if (exc.getMessage()==null) {
692
693                 if (logger.isLoggable(Logger.INFO)) {
694                     logger.info(ln.getString ("synch_exception") +
695                                 " " +
696                                 exc );
697                 }
698
699             } else {
700                 if (logger.isLoggable(Logger.INFO)) {
701                     logger.info(exc.getMessage());
702                 }
703             }
704
705             if (logger.isLoggable(Logger.INFO)) {
706                 logger.info(this.getClass().getName() +
707                             " synchronize" +
708                             exc.getMessage() );
709             }
710
711             panelHandler.setButton(true);
712         }
713     }
714
715     /**
716      * Refreshes the calendar list reading the local calendar files
717      */

718     protected void refreshCalendar() {
719         calendars = getCalendars();
720         calList.fillList();
721     }
722
723     /**
724      * Refreshes the contact list reading the local contact files
725      */

726     protected void refreshContact() {
727
728         contacts = getContacts() ;
729
730         contacts = sortContacts(contacts);
731
732         contList.fillList();
733     }
734
735     /**
736      * Shows the specified card in the CardLayout.
737      * When showing the contact modification card, the method fills all the fields.
738      * When showing the configuration card, the method fills all the fields.
739      * When showing the new contact card, the method blanks all the fields.
740      * When showing the synchronization card, the method starts a new synchronization.
741      *
742      * @param card the card to be shown
743      */

744     protected void show(String JavaDoc card) {
745
746         cardLayout.show(mainPanel,card);
747
748         if (card.equals (KEY_CALENDARLIST )) {
749
750             refreshCalendar();
751
752         } else if (card.equals (KEY_CALENDARMODIFY )) {
753
754             calendarModify.fillFields(((DemoCalendar) calendars.
755                 elementAt(getCurrentIndex().intValue())).getCalendar());
756
757         } else if (card.equals (KEY_CALENDARNEW )) {
758
759             calNew.blankFields();
760
761         } else if (card.equals (KEY_CONFIG )) {
762
763             config.setAllFields
764                 (syncmlValues, xmlContactValues, xmlCalendarValues);
765
766         } else if (card.equals (KEY_CONTACTLIST )) {
767
768             refreshContact();
769
770         } if (card.equals (KEY_CONTACTMODIFY )) {
771
772             contactModify.fillFields(((DemoContact) contacts.
773                 elementAt(getCurrentIndex().intValue())).getContact());
774
775         } else if (card.equals (KEY_CONTACTNEW )) {
776
777             contNew.blankFields();
778
779         } else if (card.equals (KEY_SYNC )) {
780
781             synchronize();
782
783         }
784
785     }
786
787     /**
788      * Returns a vector of Contact elements containing the list of contacts
789      * found in the sourceDirectory
790      *
791      * @return a Vector of Contacts, or an empty vector if no contacts are found
792      */

793     protected Vector JavaDoc getContacts() {
794
795         try {
796
797             File JavaDoc curFile = null ;
798
799             Vector JavaDoc existingFiles = null ;
800             Vector JavaDoc contacts = null ;
801             Contact contact = null ;
802
803             contacts = new Vector JavaDoc();
804
805             existingFiles = getExistingFiles(DIR_CONTACTS);
806
807             for (int i=0, l = existingFiles.size(); i < l; i++) {
808
809                 curFile = (File JavaDoc) existingFiles.elementAt(i);
810
811                 try {
812
813                     if (logger.isLoggable(Logger.DEBUG)) {
814                         logger.debug(ln.getString ("parsing_file") +
815                                      " " +
816                                      curFile );
817                     }
818
819                     XMLContactParser xmlParser =
820                         new XMLContactParser(new FileInputStream JavaDoc(curFile));
821                     contact = (Contact)xmlParser.parse();
822                     contacts.addElement
823                         (new DemoContact(curFile.getName(),contact));
824
825                 } catch (SAXException JavaDoc e) {
826
827                     if (logger.isLoggable(Logger.DEBUG)) {
828                         logger.debug(ln.getString ("error_sax_exception") +
829                                      " " +
830                                      curFile +
831                                      ": " +
832                                      e.getMessage() );
833                     }
834
835                 }
836
837             }
838
839             return contacts;
840         } catch (IOException JavaDoc exc) {
841             if (logger.isLoggable(Logger.DEBUG)) {
842                 logger.debug(ln.getString ("error_reading_files") +
843                              " " +
844                              exc.getMessage() );
845             }
846
847         }
848
849         return new Vector JavaDoc();
850     }
851
852     /**
853      * Returns a vector of Calendar elements containing the list of calendar
854      * found in the sourceDirectory
855      *
856      * @return a Vector of Calendar, or an empty vector if no calendars are found
857      */

858     protected Vector JavaDoc getCalendars() {
859
860         try {
861
862             File JavaDoc curFile = null ;
863
864             Vector JavaDoc existingFiles = null ;
865             Vector JavaDoc calendars = null ;
866             Calendar calendar = null ;
867
868             calendars = new Vector JavaDoc();
869
870             existingFiles = getExistingFiles(DIR_CALENDAR);
871             for (int i=0, l = existingFiles.size(); i < l; i++) {
872
873                 curFile = (File JavaDoc) existingFiles.elementAt(i);
874
875                 try {
876
877                     if (logger.isLoggable(Logger.DEBUG)) {
878                         logger.debug(ln.getString ("parsing_file") +
879                                      " " +
880                                      curFile );
881                     }
882
883                     XMLEventParser xmlParser =
884                         new XMLEventParser(new FileInputStream JavaDoc(curFile));
885                     calendar = (Calendar)xmlParser.parse();
886                     calendars.addElement
887                         (new DemoCalendar(curFile.getName(), calendar));
888                 } catch (SAXException JavaDoc e) {
889
890                     if (logger.isLoggable(Logger.DEBUG)) {
891                         logger.debug(ln.getString ("error_sax_exception") +
892                                      " " +
893                                       curFile +
894                                      ": " +
895                                      e.getMessage() );
896                     }
897
898                 }
899
900             }
901
902             return calendars;
903
904         } catch (IOException JavaDoc exc) {
905             if (logger.isLoggable(Logger.DEBUG)) {
906                 logger.debug(ln.getString ("error_reading_files") +
907                              " " +
908                              exc.getMessage() );
909             }
910
911         }
912
913         return new Vector JavaDoc();
914     }
915
916     /**
917      * Overwrites the indexth contact with the specified contact
918      *
919      * @param contact the new contact
920      * @param index the index of the contact to be overwritten
921      */

922     protected void writeModContact(Contact contact, int index) {
923
924         File JavaDoc tmpFile = null ;
925         File JavaDoc f = null ;
926         FileOutputStream JavaDoc out = null ;
927         PrintStream JavaDoc ps = null ;
928
929         String JavaDoc output = null ;
930
931         HashMap JavaDoc hashMapFromFile = null ;
932         HashMap JavaDoc hashMap = null ;
933
934         try {
935
936             SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc(DATE_FORMAT);
937
938             contact.setRevision(sdf.format(new Date JavaDoc()));
939
940             Converter conv = new Converter((String JavaDoc)null, null);
941
942              //
943
// Conversion into XML. Modified way
944
//
945
output = conv.contactToXML(contact);
946
947             f = new File JavaDoc(buildPath(sourceDirectory,DIR_CONTACTS),
948                          ((DemoContact) contacts.
949                             elementAt(getCurrentIndex().intValue())).
950                                                         getFilename());
951
952             hashMapFromFile = SourceUtils.xmlToHashMap(new FileInputStream JavaDoc(f));
953
954             hashMap = SourceUtils.xmlToHashMap(output);
955
956             hashMapFromFile.putAll(hashMap);
957
958             //
959
// Delete old file
960
//
961
f.delete();
962
963             //
964
// Modify the contacts Vector
965
//
966
((DemoContact) contacts.elementAt(index)).setContact(contact);
967             contList.fillList();
968
969             //
970
// Write new file (same name as the old one)
971
//
972
tmpFile = new File JavaDoc(buildPath(sourceDirectory,DIR_CONTACTS),
973                                 ((DemoContact) contacts.
974                                         elementAt(index)).getFilename());
975
976             out = new FileOutputStream JavaDoc (tmpFile ) ;
977             ps = new PrintStream JavaDoc (out ) ;
978
979             String JavaDoc value = SourceUtils.hashMapToXml(hashMapFromFile);
980
981             if (value.indexOf(XML_VERSION) != -1) {
982                 ps.print(value);
983             } else {
984                 ps.print(XML_VERSION + value);
985             }
986
987         } catch (IOException JavaDoc exc) {
988
989             if (logger.isLoggable(Logger.DEBUG)) {
990                 logger.debug(ln.getString ("error_updating_file") +
991                              " " +
992                              exc.getMessage() );
993             }
994
995         } catch (Exception JavaDoc exc) {
996
997             if (logger.isLoggable(Logger.DEBUG)) {
998                 logger.debug(ln.getString ("error_updating_file") +
999                              " " +
1000                             exc.getMessage() );
1001            }
1002
1003        } finally {
1004            if (ps != null) {
1005                try { ps.close(); } catch (Exception JavaDoc e) { }
1006                ps = null;
1007            }
1008            if (out != null) {
1009                try { out.close(); } catch (Exception JavaDoc e) { }
1010                out = null;
1011            }
1012        }
1013    }
1014
1015    /**
1016     * Creates a new contact which will be inserted in the contacts list
1017     *
1018     * @param contact the new contact
1019     */

1020    protected void writeNewContact(Contact contact) {
1021
1022        Converter conv = null ;
1023
1024        SimpleDateFormat JavaDoc sdf = null ;
1025        Date JavaDoc tmpDate = null ;
1026
1027        String JavaDoc fileName = null ;
1028
1029        String JavaDoc output = null ;
1030
1031        File JavaDoc tmpFile = null ;
1032        FileOutputStream JavaDoc out = null ;
1033        PrintStream JavaDoc ps = null ;
1034
1035        try {
1036
1037            sdf = new SimpleDateFormat JavaDoc(DATE_FORMAT);
1038            tmpDate = new Date JavaDoc();
1039            contact.setRevision(sdf.format(tmpDate));
1040
1041            conv = new Converter((String JavaDoc)null, null);
1042
1043            fileName = String.valueOf(tmpDate.getTime());
1044
1045            //
1046
// Conversion into XML. Modified way
1047
//
1048
output = conv.contactToXML(contact);
1049
1050            //
1051
// Add to the contacts Vector
1052
//
1053
contacts.addElement(new DemoContact(fileName, contact));
1054            contList.fillList();
1055
1056            //
1057
// Write to filesystem
1058
//
1059
tmpFile = new File JavaDoc(buildPath(sourceDirectory, DIR_CONTACTS) ,
1060                               fileName );
1061
1062            out = new FileOutputStream JavaDoc (tmpFile ) ;
1063            ps = new PrintStream JavaDoc (out ) ;
1064
1065            //
1066
// work around about SyncConnectorDB, ID tag must be in message
1067
//
1068
output = output.substring(0, output.indexOf ("</contact>")) +
1069                     "<id>" +
1070                     fileName +
1071                     "</id>" +
1072                     output.substring(output.indexOf ("</contact>")) ;
1073
1074            ps.print(output);
1075
1076        } catch (IOException JavaDoc exc) {
1077
1078            if (logger.isLoggable(Logger.DEBUG)) {
1079                logger.debug(ln.getString ("error_creating_file") +
1080                             " " +
1081                             exc.getMessage() );
1082            }
1083        } catch (ConverterException e) {
1084            if (logger.isLoggable(Logger.DEBUG)) {
1085                logger.debug(ln.getString ("error_creating_file") +
1086                             " " +
1087                             e.getMessage() );
1088            }
1089        } finally {
1090            if (ps != null) {
1091                try { ps.close(); } catch (Exception JavaDoc e) { }
1092                ps = null;
1093            }
1094            if (out != null) {
1095                try { out.close(); } catch (Exception JavaDoc e) { }
1096                out = null;
1097            }
1098        }
1099    }
1100
1101    /**
1102     * Deletes the currently selected contact
1103     */

1104    protected void deleteContact() {
1105
1106        try {
1107            new File JavaDoc(buildPath(sourceDirectory,DIR_CONTACTS),
1108                     ((DemoContact) contacts.
1109                        elementAt(getCurrentIndex().intValue())).
1110                                                getFilename()).delete();
1111            refresh();
1112        } catch (NullPointerException JavaDoc exc) {
1113
1114            if (logger.isLoggable(Logger.DEBUG)) {
1115                logger.debug(ln.getString ("error_deleting_file") +
1116                             " " +
1117                             exc.getMessage() );
1118            }
1119
1120        }
1121    }
1122
1123    /**
1124     * Deletes the currently selected calendar
1125     */

1126    protected void deleteCalendar() {
1127        try {
1128            new File JavaDoc(buildPath(sourceDirectory,DIR_CALENDAR),
1129                     ((DemoCalendar) calendars.
1130                        elementAt(getCurrentIndex().intValue())).
1131                                                getFilename()).delete();
1132            refreshCalendar();
1133        } catch (NullPointerException JavaDoc exc) {
1134
1135            if (logger.isLoggable(Logger.DEBUG)) {
1136                logger.debug(ln.getString ("error_deleting_file") +
1137                             " " +
1138                             exc.getMessage() );
1139            }
1140
1141        }
1142    }
1143
1144    /**
1145     * Creates a new contact which will be inserted in the contacts list
1146     *
1147     * @param calendar the new contact
1148     */

1149    protected void writeNewCalendar(Calendar calendar) {
1150
1151        Converter conv = null ;
1152
1153        SimpleDateFormat JavaDoc sdf = null ;
1154        Date JavaDoc tmpDate = null ;
1155
1156        String JavaDoc output = null ;
1157        String JavaDoc fileName = null ;
1158
1159        File JavaDoc tmpFile = null ;
1160        FileOutputStream JavaDoc out = null ;
1161        PrintStream JavaDoc ps = null ;
1162
1163        try {
1164
1165            sdf = new SimpleDateFormat JavaDoc(DATE_FORMAT);
1166            tmpDate = new Date JavaDoc();
1167
1168            fileName = String.valueOf(tmpDate.getTime());
1169
1170            conv = new Converter((String JavaDoc)null, null);
1171
1172            //
1173
// Conversion into XML. Modified way
1174
//
1175
output = conv.calendarToXML(calendar);
1176
1177            //
1178
// Add to the calendars Vector
1179
//
1180
calendars.addElement(new DemoCalendar(fileName, calendar));
1181            calList.fillList();
1182
1183            //
1184
// Write to filesystem
1185
//
1186
tmpFile = new File JavaDoc(buildPath(sourceDirectory, DIR_CALENDAR ),
1187                               fileName );
1188
1189            out = new FileOutputStream JavaDoc (tmpFile );
1190            ps = new PrintStream JavaDoc (out );
1191
1192            //
1193
// work around about SyncConnectorDB, ID tag must be in message
1194
//
1195
output = output.substring(0, output.indexOf ("</appointment>")) +
1196                     "<id>" +
1197                     fileName +
1198                     "</id>" +
1199                     output.substring(output.indexOf ("</appointment>")) ;
1200
1201            ps.print(output);
1202
1203        } catch (IOException JavaDoc exc) {
1204
1205            if (logger.isLoggable(Logger.DEBUG)) {
1206                logger.debug(ln.getString ("error_creating_file") +
1207                             " " +
1208                             exc.getMessage() );
1209            }
1210        } catch (ConverterException e) {
1211            if (logger.isLoggable(Logger.DEBUG)) {
1212                logger.debug(ln.getString ("error_creating_file") +
1213                             " " +
1214                             e.getMessage() );
1215            }
1216        } finally {
1217            if (ps != null) {
1218                try { ps.close(); } catch (Exception JavaDoc e) { }
1219                ps = null;
1220            }
1221            if (out != null) {
1222                try { out.close(); } catch (Exception JavaDoc e) { }
1223                out = null;
1224            }
1225        }
1226
1227    }
1228
1229    /**
1230     * Overwrites the indexth contact with the specified contact
1231     *
1232     * @param calendar the new contact
1233     * @param index the index of the contact to be overwritten
1234     */

1235    protected void writeModCalendar(Calendar calendar, int index) {
1236
1237        Converter conv = null ;
1238
1239        String JavaDoc output = null ;
1240
1241        HashMap JavaDoc hashMapFromFile = null ;
1242        HashMap JavaDoc hashMap = null ;
1243
1244        File JavaDoc f = null ;
1245
1246        File JavaDoc tmpFile = null ;
1247        FileOutputStream JavaDoc out = null ;
1248        PrintStream JavaDoc ps = null ;
1249
1250        try {
1251
1252            conv = new Converter((String JavaDoc)null, null);
1253
1254            //
1255
// Conversion into XML. Modified way
1256
//
1257
output = conv.calendarToXML(calendar);
1258
1259
1260            f = new File JavaDoc(buildPath(sourceDirectory, DIR_CALENDAR),
1261                         ((DemoCalendar) calendars.elementAt(
1262                           getCurrentIndex().intValue())).getFilename());
1263
1264            hashMapFromFile = SourceUtils.xmlToHashMap(FileTools.readTextFile(f));
1265
1266            hashMap = SourceUtils.xmlToHashMap(output);
1267
1268            hashMapFromFile.putAll(hashMap);
1269
1270            //
1271
// Delete old file(
1272
//
1273
f.delete();
1274
1275            //
1276
// Modify the contacts Vector
1277
//
1278
((DemoCalendar) calendars.elementAt(index)).setCalendar(calendar);
1279            contList.fillList();
1280
1281            //
1282
// Write new file (same name as the old one)
1283
//
1284
tmpFile = new File JavaDoc(buildPath(sourceDirectory,DIR_CALENDAR),
1285                               ((DemoCalendar) calendars.
1286                                    elementAt(index)).getFilename());
1287
1288            out = new FileOutputStream JavaDoc (tmpFile ) ;
1289            ps = new PrintStream JavaDoc (out ) ;
1290
1291            String JavaDoc value = SourceUtils.hashMapToXml(hashMapFromFile);
1292
1293            if (value.indexOf(XML_VERSION) != -1) {
1294                ps.print(value);
1295            } else {
1296                ps.print(XML_VERSION + value);
1297            }
1298
1299        } catch (IOException JavaDoc exc) {
1300
1301            if (logger.isLoggable(Logger.DEBUG)) {
1302                logger.debug(ln.getString ("error_updating_file") +
1303                             " " +
1304                             exc.getMessage() );
1305        }
1306
1307        } catch (Exception JavaDoc exc) {
1308
1309         if (logger.isLoggable(Logger.DEBUG)) {
1310                logger.debug(ln.getString ("error_updating_file") +
1311                             " " +
1312                             exc.getMessage() );
1313            }
1314
1315        } finally {
1316            if (ps != null) {
1317                try { ps.close (); } catch (Exception JavaDoc e) { }
1318                ps = null;
1319            }
1320            if (out != null) {
1321                try { out.close (); } catch (Exception JavaDoc e) { }
1322                out = null;
1323            }
1324        }
1325    }
1326
1327    /**
1328     * Saves the specified configuration parameters
1329     * by passing them to the DeviceManager
1330     *
1331     * @param values a list of configuration values
1332     */

1333    protected void writeConfig(Hashtable JavaDoc values) {
1334
1335        try {
1336
1337            if (logger.isLoggable(Logger.INFO)) {
1338                logger.info(ln.getString ("writing_configuration"));
1339            }
1340
1341            syncmlValues.put (PARAM_SYNCMLURL ,
1342                              values.get( PARAM_SYNCMLURL ) );
1343            syncmlValues.put (PARAM_USERNAME ,
1344                              values.get( PARAM_USERNAME ) );
1345            syncmlValues.put (PARAM_PASSWORD ,
1346                              values.get( PARAM_PASSWORD ) );
1347            syncmlValues.put (PARAM_DEVICEID ,
1348                              values.get( PARAM_DEVICEID ) );
1349            syncmlValues.put (PARAM_MESSAGETYPE ,
1350                              values.get( PARAM_MESSAGETYPE ) ) ;
1351            syncmlValues.put (PARAM_LOGLEVEL ,
1352                              values.get( PARAM_LOGLEVEL ) ) ;
1353
1354            xmlCalendarValues.put(PARAM_SYNCSOURCEURI,values.
1355                                get(PARAM_SOURCEURICALENDAR ) ) ;
1356            xmlCalendarValues.put(PARAM_SYNCMODE, values.
1357                                get(PARAM_SYNCCALENDAR ) ) ;
1358            xmlContactValues.put (PARAM_SYNCSOURCEURI, values.
1359                                get(PARAM_SOURCEURICONTACT ) ) ;
1360            xmlContactValues.put (PARAM_SYNCMODE, values.
1361                                get(PARAM_SYNCCONTACT ) ) ;
1362
1363            rootNode.setValue(DM_VALUE_PATH ,
1364                              PARAM_TARGETLOCALURI ,
1365                              getBaseURL((String JavaDoc) values.
1366                                    get(PARAM_SYNCMLURL) ) ) ;
1367            rootNode.setValue(DM_VALUE_PATH ,
1368                              PARAM_SYNCMLURL ,
1369                              values.get( PARAM_SYNCMLURL ) ) ;
1370            rootNode.setValue(DM_VALUE_PATH ,
1371                              PARAM_USERNAME ,
1372                              values.get( PARAM_USERNAME ) ) ;
1373            rootNode.setValue(DM_VALUE_PATH ,
1374                              PARAM_PASSWORD ,
1375                              values.get( PARAM_PASSWORD ) ) ;
1376            rootNode.setValue(DM_VALUE_CONTACT_PATH ,
1377                              PARAM_SYNCSOURCEURI ,
1378                              values.get( PARAM_SOURCEURICONTACT ) ) ;
1379            rootNode.setValue(DM_VALUE_CONTACT_PATH ,
1380                              PARAM_SYNCMODE ,
1381                              values.get( PARAM_SYNCCONTACT ) ) ;
1382            rootNode.setValue(DM_VALUE_CALENDAR_PATH ,
1383                              PARAM_SYNCSOURCEURI ,
1384                              values.get( PARAM_SOURCEURICALENDAR ) ) ;
1385            rootNode.setValue(DM_VALUE_CALENDAR_PATH ,
1386                              PARAM_SYNCMODE ,
1387                              values.get( PARAM_SYNCCALENDAR ) ) ;
1388            rootNode.setValue(DM_VALUE_PATH ,
1389                              PARAM_DEVICEID ,
1390                              values.get( PARAM_DEVICEID ) ) ;
1391            rootNode.setValue(DM_VALUE_PATH ,
1392                              PARAM_MESSAGETYPE ,
1393                              values.get( PARAM_MESSAGETYPE ) ) ;
1394            rootNode.setValue(DM_VALUE_PATH ,
1395                              PARAM_LOGLEVEL ,
1396                              values.get( PARAM_LOGLEVEL ) ) ;
1397
1398
1399        } catch (DMException exc) {
1400
1401            if (logger.isLoggable(Logger.DEBUG)) {
1402                logger.debug(ln.getString ("device_manager_error") +
1403                             " " +
1404                             exc.getMessage () );
1405            }
1406
1407        } catch (Exception JavaDoc exc) {
1408
1409            if (logger.isLoggable(Logger.DEBUG)) {
1410                logger.debug(ln.getString ("unhandled_exception") +
1411                             " " +
1412                             exc.toString () );
1413            }
1414
1415        }
1416    }
1417
1418    /**
1419     * Returns the index of the currently selected contact
1420     *
1421     * @return the index of the currently selected contact
1422     */

1423    protected Integer JavaDoc getCurrentIndex() {
1424        return currentIndex;
1425    }
1426
1427    /**
1428     * Sets the current index, thus selecting a contact
1429     *
1430     * @param index the value the current index should be set to
1431     */

1432    protected void setCurrentIndex(Integer JavaDoc index) {
1433        currentIndex = index;
1434    }
1435
1436    //---------------------------------------------------------- Private methods
1437

1438    /**
1439     * Returns a string representing the path of the specified dir
1440     * concatenating it with the specified source directory
1441     *
1442     * @param sourceDirectory the source directory
1443     * @param dir the directory
1444     * @return the directory's path
1445     */

1446    private String JavaDoc buildPath(String JavaDoc sourceDirectory, String JavaDoc dir) {
1447        return sourceDirectory+"/"+dir;
1448    }
1449
1450    /**
1451     * Returns a vector of File elements containing the list of files in the
1452     * sourceDirectory
1453     *
1454     * @return a list of files, or an empty vector if the directory is empty
1455     */

1456    private Vector JavaDoc getExistingFiles(String JavaDoc dir) throws IOException JavaDoc {
1457        Vector JavaDoc ret = new Vector JavaDoc();
1458
1459        //File[] files = new File(buildPath(sourceDirectory,dir)).listFiles();
1460
String JavaDoc[] fileNames = new File JavaDoc(buildPath(sourceDirectory,dir)).list();
1461        if (fileNames != null) {
1462            for (int i = 0; i<fileNames.length; ++i) {
1463                ret.addElement(new File JavaDoc(buildPath(sourceDirectory,dir) ,
1464                               fileNames[i]) );
1465            }
1466        }
1467
1468        return ret;
1469    }
1470
1471    private String JavaDoc getBaseURL (String JavaDoc url) {
1472
1473        int firstSlash = url.indexOf("/" ) ;
1474        int secondSlash = url.indexOf("/", firstSlash + 1 ) ;
1475        int thirdSlash = url.indexOf("/", secondSlash + 1 ) ;
1476        int portColon = url.indexOf(":", secondSlash + 1 ) ;
1477
1478        if (thirdSlash < portColon || portColon == -1) {
1479
1480            //
1481
// No port is specified (ex: http://127.0.0.1/sync4j)
1482
//
1483
return url.substring(0, thirdSlash);
1484        } else {
1485            //
1486
// A port is specified and must be removed
1487
// (ex: http://127.0.0.1:8080/sync4j)
1488
//
1489
return url.substring(0, portColon);
1490        }
1491    }
1492
1493    /**
1494     * sort contact
1495     *
1496     * @ param contacts to sort
1497     * @ return sorthed contacts
1498     */

1499    private Vector JavaDoc sortContacts(Vector JavaDoc contacts) {
1500
1501        ContactComparator contactComparator = null ;
1502        DemoContact[] dcs = null ;
1503
1504        if (!(contacts.size () > 0)) {
1505             return contacts;
1506        }
1507
1508        dcs = new DemoContact[contacts.size()];
1509
1510        for (int i=0, l = contacts.size(); i < l; i++) {
1511            dcs[i] = (DemoContact) contacts.elementAt(i);
1512        }
1513
1514        contactComparator = new ContactComparator () ;
1515
1516        Arrays.sort(dcs, contactComparator);
1517
1518        contacts = new Vector JavaDoc();
1519
1520        for (int i=0, l = dcs.length; i < l; i++) {
1521            contacts.add(dcs[i]);
1522        }
1523
1524        return contacts;
1525
1526    }
1527
1528}
1529
Popular Tags