KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dbforms > event > datalist > dao > DataSource


1 /*
2  * $Header: /cvsroot/jdbforms/dbforms/src/org/dbforms/event/datalist/dao/DataSource.java,v 1.32 2004/10/21 20:39:23 hkollmann Exp $
3  * $Revision: 1.32 $
4  * $Date: 2004/10/21 20:39:23 $
5  *
6  * DbForms - a Rapid Application Development Framework
7  * Copyright (C) 2001 Joachim Peer <joepeer@excite.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  */

23 package org.dbforms.event.datalist.dao;
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27 import org.dbforms.config.DbEventInterceptorData;
28 import org.dbforms.config.DbFormsConfigRegistry;
29 import org.dbforms.config.Field;
30 import org.dbforms.config.FieldTypes;
31 import org.dbforms.config.FieldValue;
32 import org.dbforms.config.FieldValues;
33 import org.dbforms.config.ResultSetVector;
34 import org.dbforms.config.Table;
35
36 import org.dbforms.util.FileHolder;
37 import org.dbforms.util.Util;
38
39 import java.io.File JavaDoc;
40 import java.io.IOException JavaDoc;
41
42 import java.sql.Connection JavaDoc;
43 import java.sql.SQLException JavaDoc;
44
45 import java.util.Iterator JavaDoc;
46
47
48
49 /**
50  * Abstract base class for DataSource.
51  *
52  * @author hkk
53  */

54 public abstract class DataSource {
55    /** log4j category class */
56    private static Log logCat = LogFactory.getLog(DataSource.class);
57    private Table table;
58
59    /**
60     * Creates a new DataSource object.
61     */

62    public DataSource() {
63    }
64
65    /**
66     * Sets the select data for this dataSource
67     *
68     * @param filterConstraint FieldValue array used to restrict a set in a
69     * resultset
70     * @param orderConstraint FieldValue array used to build a cumulation of
71     * rules for ordering (sorting)
72     * @param sqlFilter sql condition to add to where clause
73     * @param sqlFilterParams list of FieldValues to fill the sqlFilter with
74     */

75    public abstract void setSelect(FieldValue[] filterConstraint,
76       FieldValue[] orderConstraint, String JavaDoc sqlFilter,
77       FieldValue[] sqlFilterParams);
78
79
80    /**
81     * get count rows from position
82     *
83     * @param position keyValueStr to the row<br>
84     * key format: FieldID ":" Length ":" Value<br>
85     * example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"<br>
86     * If the key consists of more than one fields, the key values are
87     * seperated through "-"<br>
88     * example: value of field 1=12, value of field 3=1992, then we'll
89     * get "1:2:12-3:4:1992"
90     * @param count count of rows to fetch
91     *
92     * @return the fetched ResultSetVector
93     *
94     * @throws SQLException
95     */

96    public ResultSetVector getCurrent(DbEventInterceptorData interceptorData,
97       String JavaDoc position, int count) throws SQLException JavaDoc {
98       try {
99          open();
100
101          int start = findStartRow(position);
102
103          if (count == 0) {
104             count = size() - start;
105          }
106
107          return getResultSetVector(interceptorData, start, count);
108       } catch (Exception JavaDoc e) {
109          logCat.error("getCurrent", e);
110          close();
111
112          return new ResultSetVector();
113       }
114    }
115
116
117    /**
118     * get count rows from first row
119     *
120     * @param count count of rows to fetch
121     *
122     * @return the fetched ResultSetVector
123     *
124     * @throws SQLException
125     */

126    public ResultSetVector getFirst(DbEventInterceptorData interceptorData,
127       int count) throws SQLException JavaDoc {
128       try {
129          open();
130
131          if (count == 0) {
132             count = size();
133          }
134
135          return getResultSetVector(interceptorData, 0, count);
136       } catch (Exception JavaDoc e) {
137          logCat.error("getFirst", e);
138          close();
139
140          return new ResultSetVector();
141       }
142    }
143
144
145    /**
146     * get count rows from last row
147     *
148     * @param count count of rows to fetch
149     *
150     * @return the fetched ResultSetVector
151     *
152     * @throws SQLException
153     */

154    public ResultSetVector getLast(DbEventInterceptorData interceptorData,
155       int count) throws SQLException JavaDoc {
156       try {
157          open();
158
159          return getResultSetVector(interceptorData, size() - 1, -count);
160       } catch (Exception JavaDoc e) {
161          logCat.error("getLast", e);
162          close();
163
164          return new ResultSetVector();
165       }
166    }
167
168
169    /**
170     * get count next rows from position
171     *
172     * @param position keyValueStr to the row<br>
173     * key format: FieldID ":" Length ":" Value<br>
174     * example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"<br>
175     * If the key consists of more than one fields, the key values are
176     * seperated through "-"<br>
177     * example: value of field 1=12, value of field 3=1992, then we'll
178     * get "1:2:12-3:4:1992"
179     * @param count count of rows to fetch
180     *
181     * @return the fetched ResultSetVector
182     *
183     * @throws SQLException
184     */

185    public ResultSetVector getNext(DbEventInterceptorData interceptorData,
186       String JavaDoc position, int count) throws SQLException JavaDoc {
187       try {
188          open();
189
190          int start = findStartRow(position) + 1;
191
192          if (count == 0) {
193             count = size() - start;
194          }
195
196          return getResultSetVector(interceptorData, start, count);
197       } catch (Exception JavaDoc e) {
198          logCat.error("getNext", e);
199          close();
200
201          return new ResultSetVector();
202       }
203    }
204
205
206    /**
207     * get count rows backwards from position
208     *
209     * @param position keyValueStr to the row<br>
210     * key format: FieldID ":" Length ":" Value<br>
211     * example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"<br>
212     * If the key consists of more than one fields, the key values are
213     * seperated through "-"<br>
214     * example: value of field 1=12, value of field 3=1992, then we'll
215     * get "1:2:12-3:4:1992"
216     * @param count count of rows to fetch
217     *
218     * @return the fetched ResultSetVector
219     *
220     * @throws SQLException
221     */

222    public ResultSetVector getPrev(DbEventInterceptorData interceptorData,
223       String JavaDoc position, int count) throws SQLException JavaDoc {
224       try {
225          open();
226
227          int start = findStartRow(position) - 1;
228
229          if (count == 0) {
230             count = start;
231          }
232
233          return getResultSetVector(interceptorData, start, -count);
234       } catch (Exception JavaDoc e) {
235          logCat.error("getPrev", e);
236          close();
237
238          return new ResultSetVector();
239       }
240    }
241
242
243    /**
244     * Sets the select data for this dataSource for free form selects. default
245     * methods just raises an exception
246     *
247     * @param tableList the list of tables involved into the query
248     * @param whereClause free-form whereClause to be appended to query
249     *
250     * @throws SQLException
251     */

252    public void setSelect(String JavaDoc tableList, String JavaDoc whereClause)
253       throws SQLException JavaDoc {
254       throw new SQLException JavaDoc("Free form select not implemented");
255    }
256
257
258    /**
259     * gets the Table for the DataSource
260     *
261     * @return Table
262     */

263    public Table getTable() {
264       return table;
265    }
266
267
268    /**
269     * performs an delete in the DataSource
270     *
271     * @param con DOCUMENT ME!
272     * @param keyValuesStr keyValueStr to the row to update<br>
273     * key format: FieldID ":" Length ":" Value<br>
274     * example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"<br>
275     * If the key consists of more than one fields, the key values are
276     * seperated through "-"<br>
277     * example: value of field 1=12, value of field 3=1992, then we'll
278     * get "1:2:12-3:4:1992"
279     *
280     * @throws SQLException if any error occurs
281     */

282    public void doDelete(DbEventInterceptorData interceptorData,
283       String JavaDoc keyValuesStr) throws SQLException JavaDoc {
284    }
285
286
287    /**
288     * performs an insert into the DataSource
289     *
290     * @param con DOCUMENT ME!
291     * @param fieldValues FieldValues to insert
292     *
293     * @throws SQLException
294     */

295    public void doInsert(DbEventInterceptorData interceptorData,
296       FieldValues fieldValues) throws SQLException JavaDoc {
297    }
298
299
300    /**
301     * performs an update into the DataSource
302     *
303     * @param con DOCUMENT ME!
304     * @param fieldValues FieldValues to update
305     * @param keyValuesStr keyValueStr to the row to update<br>
306     * key format: FieldID ":" Length ":" Value<br>
307     * example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"<br>
308     * If the key consists of more than one fields, the key values are
309     * seperated through "-"<br>
310     * example: value of field 1=12, value of field 3=1992, then we'll
311     * get "1:2:12-3:4:1992"
312     *
313     * @throws SQLException if any error occurs
314     */

315    public void doUpdate(DbEventInterceptorData interceptorData,
316       FieldValues fieldValues, String JavaDoc keyValuesStr) throws SQLException JavaDoc {
317    }
318
319
320    /**
321     * set the connection parameter for the DataSouce. virtual method, if you
322     * need the connection data you must override this method
323     *
324     * @param con the JDBC Connection object
325     * @param dbConnectionName name of the used db connection. Can be used to
326     * get an own db connection, e.g. to hold it during the session
327     * (see DataSourceJDBC for example!)
328     */

329    protected void setConnection(Connection JavaDoc con, String JavaDoc dbConnectionName) {
330    }
331
332
333    /**
334     * should retrieve the row at an special index as an Object[]
335     *
336     * @param i index of row to fetch
337     *
338     * @return Object[] of the fetched row
339     *
340     * @throws SQLException
341     */

342    protected abstract Object JavaDoc[] getRow(int i) throws SQLException JavaDoc;
343
344
345    /**
346     * should close all open datasets
347     */

348    protected abstract void close();
349
350
351    /**
352     * maps the startRow to the internal index
353     *
354     * @param startRow keyValueStr to the row<br>
355     * key format: FieldID ":" Length ":" Value<br>
356     * example: if key id = 121 and field id=2 then keyValueStr contains "2:3:121"<br>
357     * If the key consists of more than one fields, the key values are
358     * seperated through "-"<br>
359     * example: value of field 1=12, value of field 3=1992, then we'll
360     * get "1:2:12-3:4:1992"
361     *
362     * @return the index of the row, 0 as first row if not found
363     *
364     * @throws SQLException
365     */

366    protected abstract int findStartRow(String JavaDoc startRow)
367       throws SQLException JavaDoc;
368
369
370    /**
371     * return true if there are more records to fetch then the given record
372     * number
373     *
374     * @param i index of last fetched row.
375     *
376     * @return true if there are more records to fetch then the given record
377     * number
378     *
379     * @throws SQLException
380     */

381    protected abstract boolean hasMore(int i) throws SQLException JavaDoc;
382
383
384    /**
385     * Will be called to open all datasets
386     *
387     * @throws SQLException
388     */

389    protected abstract void open() throws SQLException JavaDoc;
390
391
392    /**
393     * Must return the size of the whole resultset with all data fetch
394     *
395     * @return size of whole resultset
396     *
397     * @throws SQLException
398     */

399    protected abstract int size() throws SQLException JavaDoc;
400
401
402    /**
403     * @param table The table to set.
404     */

405    protected void setTable(Table table) {
406       this.table = table;
407    }
408
409
410    /**
411     * deletes the blob files on disk
412     *
413     * @param fieldValues FieldValues to delete, called by
414     *
415     * @throws SQLException
416     */

417    protected void deleteBlobFilesFromDisk(FieldValues fieldValues)
418       throws SQLException JavaDoc {
419       Iterator JavaDoc iter = fieldValues.keys();
420
421       while (iter.hasNext()) {
422          String JavaDoc fieldName = (String JavaDoc) iter.next();
423          Field curField = table.getFieldByName(fieldName);
424
425          if (curField != null) {
426             int fieldType = curField.getType();
427
428             String JavaDoc directory = null;
429
430             try {
431                directory = Util.replaceRealPath(curField.getDirectory(),
432                      DbFormsConfigRegistry.instance().lookup().getRealPath());
433             } catch (Exception JavaDoc e) {
434                logCat.error("deleteBlobFilesFromDisk", e);
435                throw new SQLException JavaDoc(e.getMessage());
436             }
437
438             if (fieldType == FieldTypes.DISKBLOB) {
439                String JavaDoc fileName = fieldValues.get(fieldName).getFieldValue()
440                                             .trim();
441
442                // get a filename
443
if (!Util.isNull(fileName)) {
444                   // remember: every field may have its own storing dir!
445
File JavaDoc file = new File JavaDoc(directory, fileName);
446
447                   if (file.exists()) {
448                      file.delete();
449                      logCat.info("deleted file " + fileName + " from dir "
450                         + directory);
451                   } else {
452                      logCat.info("delete of file " + fileName + " from dir "
453                         + directory + " failed because file not found");
454                   }
455                }
456             }
457          }
458       }
459    }
460
461
462    /**
463     * save the blob files to disk
464     *
465     * @param fieldValues FieldValues to update
466     *
467     * @throws SQLException
468     * @throws IllegalArgumentException
469     */

470    protected void saveBlobFilesToDisk(FieldValues fieldValues)
471       throws SQLException JavaDoc {
472       Iterator JavaDoc iter = fieldValues.keys();
473
474       while (iter.hasNext()) {
475          String JavaDoc fieldName = (String JavaDoc) iter.next();
476          Field curField = table.getFieldByName(fieldName);
477
478          if (curField != null) {
479             int fieldType = curField.getType();
480
481             if (fieldType == FieldTypes.DISKBLOB) {
482                String JavaDoc directory = curField.getDirectory();
483
484                // check if directory-attribute was provided
485
if (directory == null) {
486                   throw new IllegalArgumentException JavaDoc(
487                      "directory-attribute needed for fields of type DISKBLOB");
488                }
489
490                try {
491                   directory = Util.replaceRealPath(directory,
492                         DbFormsConfigRegistry.instance().lookup().getRealPath());
493                } catch (Exception JavaDoc e) {
494                   logCat.error("saveBlobFilesToDisk", e);
495                }
496
497                // instanciate file object for that dir
498
File JavaDoc dir = new File JavaDoc(directory);
499
500                // Check saveDirectory is truly a directory
501
if (!dir.isDirectory()) {
502                   throw new IllegalArgumentException JavaDoc("Not a directory: "
503                      + directory);
504                }
505
506                // Check saveDirectory is writable
507
if (!dir.canWrite()) {
508                   throw new IllegalArgumentException JavaDoc("Not writable: "
509                      + directory);
510                }
511
512                // dir is ok so lets store the filepart
513
FileHolder fileHolder = fieldValues.get(fieldName).getFileHolder();
514
515                if (fileHolder != null) {
516                   try {
517                      fileHolder.writeBufferToFile(dir);
518
519                      //filePart.getInputStream().close();
520
logCat.info("fin + closedy");
521                   } catch (IOException JavaDoc ioe) {
522                      //#checkme: this would be a good place for rollback in database!!
523
logCat.error("saveBlobFilesToDisk", ioe);
524                      throw new SQLException JavaDoc("could not store file '"
525                         + fileHolder.getFileName() + "' to dir '" + directory
526                         + "'");
527                   }
528                } else {
529                   logCat.info("uh! empty fileHolder");
530                }
531             }
532          }
533       }
534    }
535
536
537    /**
538     * DOCUMENT ME!
539     *
540     * @param startRow
541     * @param count
542     *
543     * @return the resultsetvector
544     *
545     * @throws SQLException
546     */

547    protected ResultSetVector getResultSetVector(
548       DbEventInterceptorData interceptorData, int startRow, int count)
549       throws SQLException JavaDoc {
550       ResultSetVector result = null;
551       result = new ResultSetVector(table);
552
553       int begin = 0;
554       int ende = 0;
555
556       Object JavaDoc[] row;
557
558       if (count > 0) {
559          begin = startRow;
560
561          for (ende = begin; ende < (startRow + count); ende++) {
562             row = getRow(ende);
563
564             if (row == null) {
565                break;
566             }
567
568             result.addRow(interceptorData, row);
569          }
570       } else if (count < 0) {
571          begin = startRow + count + 1;
572
573          if (begin < 0) {
574             begin = 0;
575          }
576
577          for (ende = begin; ende <= startRow; ende++) {
578             row = getRow(ende);
579
580             if (row == null) {
581                break;
582             }
583
584             result.addRow(interceptorData, row);
585          }
586       }
587
588       result.setFirstPage(!(begin > 0));
589       result.setLastPage(!hasMore(ende));
590
591       return result;
592    }
593 }
594
Popular Tags