KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > syncclient > sps > jdbc > DataStoreImpl


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.sps.jdbc;
20
21 import java.sql.Connection JavaDoc;
22 import java.sql.DriverManager JavaDoc;
23 import java.sql.PreparedStatement JavaDoc;
24 import java.sql.ResultSet JavaDoc;
25 import java.sql.ResultSetMetaData JavaDoc;
26 import java.sql.SQLException JavaDoc;
27 import java.sql.Statement JavaDoc;
28
29 import java.util.Date JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.Vector JavaDoc;
32
33 import sync4j.syncclient.common.logging.Logger;
34
35 import sync4j.syncclient.spdm.DMException;
36 import sync4j.syncclient.spdm.ManagementNode;
37 import sync4j.syncclient.spdm.SimpleDeviceManager;
38
39 import sync4j.syncclient.sps.common.DataStore;
40 import sync4j.syncclient.sps.common.Record;
41 import sync4j.syncclient.sps.common.RecordMetadata;
42 import sync4j.syncclient.sps.common.RecordFilter;
43
44 /**
45  * This class create DataStore
46  * and provide method to operate about record
47  *
48  * @author Fabio Maggi @ Funambol
49  * $Id: DataStoreImpl.java,v 1.5 2005/01/19 11:18:37 fabius Exp $
50  */

51 public class DataStoreImpl extends DataStore {
52
53     //------------------------------------------------------------- Private data
54

55     Logger logger = new Logger();
56
57     //------------------------------------------------------------- Constructors
58

59     public DataStoreImpl(String JavaDoc dataStoreName, RecordMetadata recordMetadata) {
60         super(dataStoreName, recordMetadata);
61     }
62
63     //------------------------------------------------------------- Public methods
64

65     /**
66      * create record
67      *
68      * @param key
69      * @return record
70      **/

71     public Record newRecord(String JavaDoc key) {
72
73         Record record = null;
74         record = new Record(this, key);
75         return record;
76
77     }
78
79     /**
80      * read record
81      * @param record
82      **/

83     public Record readRecord(Record record) {
84
85         String JavaDoc query = null;
86         Object JavaDoc params[] = null;
87
88         Vector JavaDoc dataRows = null;
89         Object JavaDoc[] dataRow = null;
90
91
92         query = DataStoreSql.selectQuery(this, record);
93
94         params = new Object JavaDoc[1];
95
96         params[0] = (Object JavaDoc) record.getKey();
97
98         dataRows = execPreparedSelect(query, params);
99
100         for (int i=0; i<dataRows.size(); i++) {
101
102             dataRow = (Object JavaDoc[]) dataRows.elementAt(i);
103
104             for (int j=1; j <= dataRow.length; j++) {
105                 record.setField(j, (String JavaDoc) dataRow[j-1]);
106             }
107         }
108
109         return record;
110
111     }
112
113     /**
114      * store record
115      * @param record
116      **/

117     public Record storeRecord(Record record) {
118
119         String JavaDoc query = null;
120         Object JavaDoc params[] = null;
121
122         Vector JavaDoc dataRows = null;
123         Object JavaDoc[] dataRow = null;
124
125         boolean findRecord = false;
126
127         int recordSize = 0;
128
129         query = DataStoreSql.selectQuery(this, record);
130
131         params = new Object JavaDoc[1];
132
133         params[0] = (Object JavaDoc) record.getKey();
134
135         dataRows = execPreparedSelect(query, params);
136
137         if (dataRows.size() > 0) {
138             findRecord = true;
139         }
140
141         recordSize = this.getRecordMetadata().getFieldMetadata().length;
142
143         params = new Object JavaDoc[recordSize];
144
145         if (findRecord) {
146
147             query = DataStoreSql.updateQuery(this, record);
148
149             int i=0;
150
151             for(i = 1; i < recordSize; i++) {
152
153                 //provvisorio, in attesa di correzione baco sul server
154
if (record.getString(i+1) == null || record.getString(i+1).equals("null")) {
155                     params[i-1] = null;
156                 } else {
157                     params[i-1] = (Object JavaDoc) record.getString(i+1);
158                 }
159             }
160
161             //key is last param in update query
162
params[i-1] = (Object JavaDoc) record.getString(1);
163
164
165         } else {
166
167             record.setKey(String.valueOf(getNextKey()));
168
169             query= DataStoreSql.insertQuery(this, record);
170
171             for(int i = 1; i <= recordSize; i++) {
172
173                 //provvisorio, in attesa di correzione baco sul server
174
if (record.getString(i) == null || record.getString(i).equals("null")) {
175                     params[i-1] = null;
176                 } else {
177                     params[i-1] = (Object JavaDoc) record.getString(i);
178                 }
179             }
180
181         }
182
183         execPreparedUpdate(query, params);
184
185         return record;
186
187     }
188
189     /**
190      * delete record
191      * @param record
192      **/

193     public void deleteRecord(Record record) {
194
195         String JavaDoc query = null;
196         Object JavaDoc params[] = null;
197
198         Vector JavaDoc dataRows = null;
199         Object JavaDoc[] dataRow = null;
200
201         boolean findRecord = false;
202
203         query = DataStoreSql.selectQuery(this, record);
204
205         params = new Object JavaDoc[1];
206
207         params[0] = (Object JavaDoc) record.getKey();
208
209         dataRows = execPreparedSelect(query, params);
210
211         if (dataRows.size() > 0) {
212             findRecord = true;
213         }
214
215         if (findRecord) {
216             query = DataStoreSql.deleteQuery(this, record);
217             execPreparedUpdate(query, params);
218         } else {
219             //record non esistente
220
return;
221         }
222
223         return;
224
225     }
226
227     /**
228      * return alla records of dataStore
229      *
230      * @return find records
231      **/

232     public Vector JavaDoc findAllRecords() {
233
234         Vector JavaDoc records = new Vector JavaDoc();
235
236         Record record = null;
237
238         Connection JavaDoc con = null;
239         Statement JavaDoc stmt = null;
240         ResultSet JavaDoc rs = null;
241         ResultSetMetaData JavaDoc rsmd = null;
242
243         String JavaDoc query = null;
244
245         try {
246
247             con = getConnection();
248
249             stmt = con.createStatement();
250
251             query = DataStoreSql.allRecordsQuery(this);
252
253             rs = stmt.executeQuery(query);
254
255             rsmd = rs.getMetaData();
256
257             while (rs.next()) {
258
259                 record = new Record(this, rs.getString(1));
260
261                 for (int i=2; i <= rsmd.getColumnCount(); i++) {
262                     record.setField (i, rs.getString(i));
263                 }
264
265               records.addElement(record);
266
267             }
268
269         } catch(Exception JavaDoc e) {
270              if (logger.isLoggable(Logger.INFO)) {
271                  logger.info("Error reading records: " + e.getMessage());
272              }
273         } finally {
274
275             if(con != null) {
276                 try {con.close();} catch (Exception JavaDoc e){}
277                 con = null;
278             }
279
280             if(stmt != null) {
281                 try {stmt.close();} catch (Exception JavaDoc e){}
282                 stmt = null;
283             }
284
285             if(rs != null) {
286                 try{rs.close();} catch (Exception JavaDoc e){}
287                 rs = null;
288             }
289
290         }
291
292         return records;
293
294     }
295
296     /**
297      * return a Vector of Records
298      * found by state, last timestamp
299      *
300      * @param state state of record
301      * @param since last timestamp
302      * @return find records
303      **/

304     public Vector JavaDoc findRecords(char state, Date JavaDoc since) {
305
306         Vector JavaDoc records = new Vector JavaDoc();
307
308         Record record = null;
309
310         Connection JavaDoc con = null;
311         PreparedStatement JavaDoc ps = null;
312         Statement JavaDoc stmt = null;
313         ResultSet JavaDoc rs = null;
314         ResultSetMetaData JavaDoc rsmd = null;
315
316         String JavaDoc query = null;
317
318         String JavaDoc nameFieldState = null;
319         String JavaDoc nameFieldTimestamp = null;
320
321         String JavaDoc function = null;
322
323         for (int i=0; i < this.getRecordMetadata().getFieldMetadata().length; i++) {
324
325             function = (String JavaDoc) this.getRecordMetadata().getFieldMetadata()[i].getAttributes().get("function");
326
327             if (state!=' ' && function.equals("mtype")) {
328                 nameFieldState = this.getRecordMetadata().getFieldMetadata()[i].getName();
329             }
330
331             if (since!=null && function.equals("timestamp")) {
332                 nameFieldTimestamp = this.getRecordMetadata().getFieldMetadata()[i].getName();
333             }
334
335         }
336
337         try {
338
339             con = getConnection();
340
341             stmt = con.createStatement();
342
343             query = DataStoreSql.RecordsByStateByDateQuery(this, nameFieldState, nameFieldTimestamp);
344
345             ps = con.prepareStatement(query);
346
347             if (nameFieldState != null && nameFieldTimestamp != null) {
348                 ps.setString(1, String.valueOf(state));
349                 ps.setDate(2, new java.sql.Date JavaDoc(since.getTime()));
350             } else if (nameFieldState != null && nameFieldTimestamp == null) {
351                 ps.setString(1, String.valueOf(state));
352             } else if (nameFieldState == null && nameFieldTimestamp != null) {
353                 ps.setDate(1, new java.sql.Date JavaDoc(since.getTime()));
354             }
355
356             rs = ps.executeQuery();
357
358             rsmd = rs.getMetaData();
359
360             while (rs.next()) {
361
362                 record = new Record(this, rs.getString(1));
363
364                 for (int i=2; i <= rsmd.getColumnCount(); i++) {
365                     record.setField (i, rs.getString(i));
366                 }
367
368               records.addElement(record);
369
370             }
371
372         } catch(Exception JavaDoc e) {
373              if (logger.isLoggable(Logger.INFO) ||
374                   logger.isLoggable(Logger.DEBUG)) {
375                   logger.info("Error reading records: " + e.getMessage());
376              }
377         } finally {
378
379             if(con != null) {
380                 try {con.close();} catch (Exception JavaDoc e){}
381                 con = null;
382             }
383
384             if(stmt != null) {
385                 try {stmt.close();} catch (Exception JavaDoc e){}
386                 stmt = null;
387             }
388
389             if(rs != null) {
390                 try{rs.close();} catch (Exception JavaDoc e){}
391                 rs = null;
392             }
393
394         }
395
396         return records;
397
398     }
399
400
401     /**
402      * return records of dataStore find by RecordFilter
403      *
404      * @param recordFilter filter
405      * @return find records
406      **/

407     public Vector JavaDoc findRecords(RecordFilter recordFilter) {
408
409         Vector JavaDoc allRecords = null;
410         Vector JavaDoc findRecords = new Vector JavaDoc();
411
412         Record record = null;
413
414         allRecords = this.findAllRecords();
415
416         for(int i=0; i < allRecords.size(); i++) {
417
418             record = this.readRecord((Record) allRecords.elementAt(i));
419
420             if(recordFilter.accept(record)) {
421                 findRecords.addElement(allRecords.elementAt(i));
422             }
423         }
424
425         return findRecords;
426
427     }
428
429     /**
430      * @return datastore next key
431      **/

432     public long getNextKey() {
433
434         Connection JavaDoc con = null;
435         Statement JavaDoc stmt = null;
436         ResultSet JavaDoc rs = null;
437         ResultSetMetaData JavaDoc rsmd = null;
438
439         String JavaDoc query = null;
440
441         String JavaDoc function = null;
442         String JavaDoc nameFieldKey = null;
443
444         int nRecords = 0;
445         long key = 0;
446
447
448         for (int i=0; i < this.getRecordMetadata().getFieldMetadata().length; i++) {
449
450             function = (String JavaDoc) this.getRecordMetadata().getFieldMetadata()[i].getAttributes().get("function");
451
452             if (function.equals("key")) {
453                 nameFieldKey = this.getRecordMetadata().getFieldMetadata()[i].getName();
454             }
455
456         }
457
458         try {
459
460             con = getConnection();
461
462             stmt = con.createStatement();
463
464             query = "select count(*) from " + this.getDataStoreName();
465
466             rs = stmt.executeQuery(query);
467
468             while (rs.next()) {
469
470                 try {
471                     nRecords = Integer.parseInt(rs.getString(1));
472                 } catch (NumberFormatException JavaDoc e) {
473                     if (logger.isLoggable(Logger.INFO)) {
474                       logger.info("Error reading records: " + e.getMessage());
475                     }
476                 }
477             }
478
479             if (nRecords!=0) {
480
481                 query = DataStoreSql.getNextKeyQuery(this, nameFieldKey);
482
483                 rs = stmt.executeQuery(query);
484
485                 while (rs.next()) {
486                     try {
487                         key = Long.parseLong(rs.getString(1));
488                     } catch (NumberFormatException JavaDoc e) {
489                         if (logger.isLoggable(Logger.INFO)) {
490                             logger.info("Error reading records: " + e.getMessage());
491                         }
492                     }
493                 }
494
495             } else {
496                 //key about no record in table
497
key = 1000;
498
499             }
500
501
502         } catch(Exception JavaDoc e) {
503              if (logger.isLoggable(Logger.INFO)) {
504                 logger.info("Error reading records: " + e.getMessage());
505              }
506         } finally {
507
508             if(con != null) {
509                 try {con.close();} catch (Exception JavaDoc e){}
510                 con = null;
511             }
512
513             if(stmt != null) {
514                 try {stmt.close();} catch (Exception JavaDoc e){}
515                 stmt = null;
516             }
517
518             if(rs != null) {
519                 try{rs.close();} catch (Exception JavaDoc e){}
520                 rs = null;
521             }
522
523         }
524
525         return key;
526     }
527
528     //----------------------------------------------------------- Private methods
529

530     /**
531      * Execute update query by PreparedStatement
532      *
533      * @param query query formatted in PreparedStatement form
534      * @param params params about query
535      **/

536     private void execPreparedUpdate(String JavaDoc query, Object JavaDoc[] params) {
537
538         Connection JavaDoc con = null;
539         ResultSet JavaDoc rs = null;
540
541         PreparedStatement JavaDoc preparedStatement;
542
543         try {
544
545             con = getConnection();
546
547             preparedStatement = con.prepareStatement(query);
548
549             int numParam = params.length;
550
551             for (int i=0; i<numParam; i++) {
552                 preparedStatement.setObject(i+1, params[i]);
553             }
554
555             preparedStatement.executeUpdate();
556
557         } catch(Exception JavaDoc e) {
558              if (logger.isLoggable(Logger.INFO)) {
559                  logger.info("Error reading records: " + e.getMessage());
560              }
561         } finally {
562
563             if(con != null) {
564                 try{con.close();} catch (Exception JavaDoc e){}
565                 con = null;
566             }
567
568         }
569
570     }
571
572     /**
573      * Execute select query by PreparedStatement
574      *
575      * @param query query formatted in PreparedStatement form
576      * @param params params about query
577      * @return Vector about read records
578      **/

579     private Vector JavaDoc execPreparedSelect(String JavaDoc query, Object JavaDoc[] params) {
580
581         Connection JavaDoc con = null;
582         ResultSet JavaDoc rs = null;
583
584         Vector JavaDoc dataRows;
585         Object JavaDoc[] dataRow = null;
586         Object JavaDoc obj =null;
587
588         dataRows = new Vector JavaDoc();
589
590
591         try {
592
593             con = getConnection();
594
595             PreparedStatement JavaDoc preparedStatement = con.prepareStatement(query);
596
597             int numParam = params.length;
598
599             for (int i=0; i<numParam; i++) {
600                 preparedStatement.setObject(i+1, params[i]);
601             }
602
603             rs = preparedStatement.executeQuery();
604
605             int numCol = rs.getMetaData().getColumnCount();
606
607             while (rs.next()) {
608
609                 dataRow = new Object JavaDoc[numCol];
610
611                 for (int i=0; i<numCol; i++) {
612                   obj = rs.getObject(i+1);
613                   dataRow[i] = obj;
614                 }
615
616                 dataRows.addElement(dataRow);
617
618             }
619         } catch(Exception JavaDoc e) {
620              if (logger.isLoggable(Logger.INFO)) {
621                 logger.info("Error reading records: " + e.getMessage());
622              }
623         } finally {
624
625             if(con != null) {
626                 try{con.close();} catch (Exception JavaDoc e){}
627                 con = null;
628             }
629
630         }
631
632         return dataRows;
633
634     }
635
636     /**
637      * @return database connection
638      **/

639     private Connection JavaDoc getConnection ()
640     throws ClassNotFoundException JavaDoc, SQLException JavaDoc, DMException {
641
642         String JavaDoc jdbcDriver = null;
643         String JavaDoc urlConnection = null;
644         String JavaDoc userConnection = null;
645         String JavaDoc passwordConnection = null;
646
647         Connection JavaDoc con = null;
648
649         String JavaDoc contextSources = "sps/jdbc";
650
651         Hashtable JavaDoc jdbcParams = null;
652
653         String JavaDoc appURI = null;
654
655         ManagementNode rootNode = null;
656         ManagementNode sourcesNode = null;
657         ManagementNode[] sources = null;
658
659         //@todo trovare un altro modo per settare la appURI
660
//appURI = System.getProperty(SimpleDeviceManager.PROP_DM_APP_BASE);
661

662
663         try {
664
665             rootNode = SimpleDeviceManager.getDeviceManager().getManagementTree(appURI);
666
667             sourcesNode = rootNode.getChildNode(contextSources);
668
669             sources = sourcesNode.getChildren();
670
671             jdbcParams = sources[0].getValues();
672
673         } catch (DMException e) {
674             if (logger.isLoggable(Logger.INFO)) {
675                 logger.info("Error reading jdbc config values: " + e.getMessage());
676             }
677         }
678
679         jdbcDriver = (String JavaDoc) jdbcParams.get("jdbcDriver");
680         urlConnection = (String JavaDoc) jdbcParams.get("url");
681         userConnection = (String JavaDoc) jdbcParams.get("user");
682         passwordConnection = (String JavaDoc) jdbcParams.get("password");
683
684         Class.forName(jdbcDriver);
685
686         con = DriverManager.getConnection(urlConnection, userConnection, passwordConnection);
687
688         return con;
689
690     }
691
692     /**
693      * Method define start DB operathions
694      */

695     public void startDBOperations() {
696
697     }
698
699     /**
700      * Method define end DB operathions
701      */

702     public void commitDBOperations() {
703
704     }
705
706 }
Popular Tags