c0caf6d70938548a3e3e7b2f8d0457906854d0c5
[mir.git] / source / mir / storage / Database.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mir.storage;
31
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.sql.Connection;
35 import java.sql.PreparedStatement;
36 import java.sql.ResultSet;
37 import java.sql.ResultSetMetaData;
38 import java.sql.SQLException;
39 import java.sql.Statement;
40 import java.sql.Timestamp;
41 import java.text.ParseException;
42 import java.text.SimpleDateFormat;
43 import java.util.ArrayList;
44 import java.util.Calendar;
45 import java.util.GregorianCalendar;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.TimeZone;
51 import java.util.Vector;
52
53 import mir.config.MirPropertiesConfiguration;
54 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
55 import mir.entity.Entity;
56 import mir.entity.EntityList;
57 import mir.entity.StorableObjectEntity;
58 import mir.log.LoggerWrapper;
59 import mir.misc.StringUtil;
60 import mir.storage.store.ObjectStore;
61 import mir.storage.store.StorableObject;
62 import mir.storage.store.StoreContainerType;
63 import mir.storage.store.StoreIdentifier;
64 import mir.storage.store.StoreUtil;
65 import mir.util.JDBCStringRoutines;
66
67 import com.codestudio.util.SQLManager;
68
69
70 /**
71  * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
72  * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
73  * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
74  * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
75  * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
76  * Datenbank erfolgt.
77  *
78  * @version $Id: Database.java,v 1.44.2.11 2003/11/24 23:37:18 rk Exp $
79  * @author rk
80  *
81  */
82 public class Database implements StorageObject {
83   private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
84   private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
85
86
87   private static Map POPUP_EMPTYLINE = new HashMap();
88   protected static final ObjectStore o_store = ObjectStore.getInstance();
89   private static final int _millisPerHour = 60 * 60 * 1000;
90   private static final int _millisPerMinute = 60 * 1000;
91
92   static {
93     // always same object saves a little space
94     POPUP_EMPTYLINE.put("key", "");
95     POPUP_EMPTYLINE.put("value", "--");
96   }
97
98   protected LoggerWrapper logger;
99   protected MirPropertiesConfiguration configuration;
100   protected String theTable;
101   protected String theCoreTable = null;
102   protected String thePKeyName = "id";
103   protected int thePKeyType;
104   protected int thePKeyIndex;
105   protected boolean evaluatedMetaData = false;
106   protected ArrayList metadataFields;
107   protected ArrayList metadataLabels;
108   protected ArrayList metadataNotNullFields;
109   protected int[] metadataTypes;
110   protected Class theEntityClass;
111   protected List popupCache = null;
112   protected boolean hasPopupCache = false;
113   protected Map hashCache = null;
114   protected boolean hasTimestamp = true;
115   private String database_driver;
116   private String database_url;
117   private int defaultLimit;
118
119   TimeZone timezone;
120   SimpleDateFormat internalDateFormat;
121   SimpleDateFormat userInputDateFormat;
122 /*
123   private SimpleDateFormat _dateFormatterOut;
124   private SimpleDateFormat _dateFormatterIn;
125   _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
126   _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");
127 */
128
129   /**
130    * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
131    * Aus diesem file werden <code>Database.Logfile</code>,
132    * <code>Database.Username</code>,<code>Database.Password</code>,
133    * <code>Database.Host</code> und <code>Database.Adaptor</code>
134    * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
135    * erzeugt.
136    *
137    * @param   String confFilename Dateiname der Konfigurationsdatei
138    */
139   public Database() throws StorageObjectFailure {
140     try {
141       configuration = MirPropertiesConfiguration.instance();
142     }
143     catch (PropertiesConfigExc e) {
144       throw new StorageObjectFailure(e);
145     }
146     logger = new LoggerWrapper("Database");
147     timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
148     internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
149     internalDateFormat.setTimeZone(timezone);
150
151     userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
152     userInputDateFormat.setTimeZone(timezone);
153
154
155     String theAdaptorName = configuration.getString("Database.Adaptor");
156     defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
157
158     try {
159       theEntityClass = GENERIC_ENTITY_CLASS;
160     }
161     catch (Throwable e) {
162       logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
163       throw new StorageObjectFailure("Error in Database() constructor.", e);
164     }
165   }
166
167   /**
168    * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
169    * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
170    * wird eine mir.entity.GenericEntity erzeugt.
171    *
172    * @return Class-Objekt der Entity
173    */
174   public java.lang.Class getEntityClass() {
175     return theEntityClass;
176   }
177
178   /**
179    * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
180    * wieviel Datens?tze per Default selektiert werden.
181    *
182    * @return Standard-Anzahl der Datens?tze
183    */
184   public int getLimit() {
185     return defaultLimit;
186   }
187
188   /**
189    * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
190    * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
191    * @return Name des Primary-Keys
192    */
193   public String getIdName() {
194     return thePKeyName;
195   }
196
197   /**
198    * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
199    *
200    * @return Name der Tabelle
201    */
202   public String getTableName() {
203     return theTable;
204   }
205
206   /*
207   *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
208   *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
209   *   wird.
210   *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
211   *    the Table
212    */
213   public String getCoreTable() {
214     if (theCoreTable != null) {
215       return theCoreTable;
216     }
217     else {
218       return theTable;
219     }
220   }
221
222   /**
223    * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
224    * @return int-Array mit den Typen der Felder
225    * @exception StorageObjectException
226    */
227   public int[] getTypes() throws StorageObjectFailure {
228     if (metadataTypes == null) {
229       get_meta_data();
230     }
231
232     return metadataTypes;
233   }
234
235   /**
236    * Liefert eine Liste der Labels der Tabellenfelder
237    * @return ArrayListe mit Labeln
238    * @exception StorageObjectException
239    */
240   public List getLabels() throws StorageObjectFailure {
241     if (metadataLabels == null) {
242       get_meta_data();
243     }
244
245     return metadataLabels;
246   }
247
248   /**
249    * Liefert eine Liste der Felder der Tabelle
250    * @return ArrayList mit Feldern
251    * @exception StorageObjectException
252    */
253   public List getFields() throws StorageObjectFailure {
254     if (metadataFields == null) {
255       get_meta_data();
256     }
257
258     return metadataFields;
259   }
260
261   /**
262    *   Gets value out of ResultSet according to type and converts to String
263    *   @param rs  ResultSet.
264    *   @param aType  a type from java.sql.Types.*
265    *   @param index  index in ResultSet
266    *   @return returns the value as String. If no conversion is possible
267    *                             /unsupported value/ is returned
268    */
269   private String getValueAsString(ResultSet rs, int valueIndex, int aType)
270     throws StorageObjectFailure {
271     String outValue = null;
272
273     if (rs != null) {
274       try {
275         switch (aType) {
276           case java.sql.Types.BIT:
277             outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
278
279             break;
280
281           case java.sql.Types.INTEGER:
282           case java.sql.Types.SMALLINT:
283           case java.sql.Types.TINYINT:
284           case java.sql.Types.BIGINT:
285
286             int out = rs.getInt(valueIndex);
287
288             if (!rs.wasNull()) {
289               outValue = new Integer(out).toString();
290             }
291
292             break;
293
294           case java.sql.Types.NUMERIC:
295
296             /** @todo Numeric can be float or double depending upon
297              *  metadata.getScale() / especially with oracle */
298             long outl = rs.getLong(valueIndex);
299
300             if (!rs.wasNull()) {
301               outValue = new Long(outl).toString();
302             }
303
304             break;
305
306           case java.sql.Types.REAL:
307
308             float tempf = rs.getFloat(valueIndex);
309
310             if (!rs.wasNull()) {
311               tempf *= 10;
312               tempf += 0.5;
313
314               int tempf_int = (int) tempf;
315               tempf = (float) tempf_int;
316               tempf /= 10;
317               outValue = "" + tempf;
318               outValue = outValue.replace('.', ',');
319             }
320
321             break;
322
323           case java.sql.Types.DOUBLE:
324
325             double tempd = rs.getDouble(valueIndex);
326
327             if (!rs.wasNull()) {
328               tempd *= 10;
329               tempd += 0.5;
330
331               int tempd_int = (int) tempd;
332               tempd = (double) tempd_int;
333               tempd /= 10;
334               outValue = "" + tempd;
335               outValue = outValue.replace('.', ',');
336             }
337
338             break;
339
340           case java.sql.Types.CHAR:
341           case java.sql.Types.VARCHAR:
342           case java.sql.Types.LONGVARCHAR:
343             outValue = rs.getString(valueIndex);
344
345             break;
346
347           case java.sql.Types.LONGVARBINARY:
348             outValue = rs.getString(valueIndex);
349
350             break;
351
352           case java.sql.Types.TIMESTAMP:
353
354             // it's important to use Timestamp here as getting it
355             // as a string is undefined and is only there for debugging
356             // according to the API. we can make it a string through formatting.
357             // -mh
358             Timestamp timestamp = (rs.getTimestamp(valueIndex));
359
360             if (!rs.wasNull()) {
361               java.util.Date date = new java.util.Date(timestamp.getTime());
362
363               Calendar calendar = new GregorianCalendar();
364               calendar.setTime(date);
365               calendar.setTimeZone(timezone);
366               outValue = internalDateFormat.format(date);
367
368               int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
369               String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
370
371               if (offset<0)
372                 outValue = outValue + "-";
373               else
374                 outValue = outValue + "+";
375               outValue = outValue + tzOffset;
376             }
377
378             break;
379
380           default:
381             outValue = "<unsupported value>";
382             logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
383         }
384       } catch (SQLException e) {
385         throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
386           e);
387       }
388     }
389
390     return outValue;
391   }
392
393   /**
394    *   select-Operator um einen Datensatz zu bekommen.
395    *   @param id Primaerschluessel des Datensatzes.
396    *   @return liefert EntityObject des gefundenen Datensatzes oder null.
397    */
398   public Entity selectById(String id) throws StorageObjectExc {
399     if ((id == null) || id.equals("")) {
400       throw new StorageObjectExc("Database.selectById: Missing id");
401     }
402
403     // ask object store for object
404     if (StoreUtil.implementsStorableObject(theEntityClass)) {
405       String uniqueId = id;
406
407       if (theEntityClass.equals(StorableObjectEntity.class)) {
408         uniqueId += ("@" + theTable);
409       }
410
411       StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
412       logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
413
414       Entity hit = (Entity) o_store.use(search_sid);
415
416       if (hit != null) {
417         return hit;
418       }
419     }
420
421     Statement stmt = null;
422     Connection con = getPooledCon();
423     Entity returnEntity = null;
424
425     try {
426       ResultSet rs;
427
428       /** @todo better prepared statement */
429       String selectSql =
430         "select * from " + theTable + " where " + thePKeyName + "=" + id;
431       stmt = con.createStatement();
432       rs = executeSql(stmt, selectSql);
433
434       if (rs != null) {
435         if (evaluatedMetaData == false) {
436           evalMetaData(rs.getMetaData());
437         }
438
439         if (rs.next()) {
440           returnEntity = makeEntityFromResultSet(rs);
441         }
442         else {
443           logger.debug("No data for id: " + id + " in table " + theTable);
444         }
445
446         rs.close();
447       }
448       else {
449         logger.debug("No Data for Id " + id + " in Table " + theTable);
450       }
451     }
452     catch (SQLException sqe) {
453       throwSQLException(sqe, "selectById");
454       return null;
455     }
456     catch (NumberFormatException e) {
457       logger.error("ID is no number: " + id);
458     }
459     finally {
460       freeConnection(con, stmt);
461     }
462
463     return returnEntity;
464   }
465
466   /**
467    * This method makes it possible to make selects across multiple tables
468    * 
469    * @param mainTablePrefix prefix for the mainTable
470    * @param extraTables a vector of tables for relational select
471    * @param aWhereClause whereClause
472    * @return EntityList of selected Objects
473    * @throws StorageObjectFailure
474    */
475
476   public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, 
477                                                 List extraTables, String aWhereClause )
478    throws StorageObjectFailure {
479         return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, -1);
480   }
481
482   /**
483    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
484    *   @param key  Datenbankfeld der Bedingung.
485    *   @param value  Wert die der key anehmen muss.
486    *   @return EntityList mit den gematchten Entities
487    */
488   public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
489     return selectByFieldValue(aField, aValue, 0);
490   }
491
492   /**
493    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
494    *   @param key  Datenbankfeld der Bedingung.
495    *   @param value  Wert die der key anehmen muss.
496    *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
497    *   @return EntityList mit den gematchten Entities
498    */
499   public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
500     return selectByWhereClause(aField + "=" + aValue, offset);
501   }
502
503   /**
504    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
505    * Also offset wird der erste Datensatz genommen.
506    *
507    * @param wc where-Clause
508    * @return EntityList mit den gematchten Entities
509    * @exception StorageObjectException
510    */
511   public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
512     return selectByWhereClause(where, 0);
513   }
514
515   /**
516    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
517    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
518    *
519    * @param wc where-Clause
520    * @param offset ab welchem Datensatz.
521    * @return EntityList mit den gematchten Entities
522    * @exception StorageObjectException
523    */
524   public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
525     return selectByWhereClause(whereClause, null, offset);
526   }
527
528   /**
529    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
530    * Also offset wird der erste Datensatz genommen.
531    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
532    *
533    * @param wc where-Clause
534    * @param ob orderBy-Clause
535    * @return EntityList mit den gematchten Entities
536    * @exception StorageObjectException
537    */
538   public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
539     return selectByWhereClause(where, order, 0);
540   }
541
542   /**
543    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
544    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
545    *
546    * @param wc where-Clause
547    * @param ob orderBy-Clause
548    * @param offset ab welchem Datensatz
549    * @return EntityList mit den gematchten Entities
550    * @exception StorageObjectException
551    */
552   public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
553     return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
554   }
555
556   /**
557    * select-Operator returns EntityList with matching rows in Database.
558    * @param aWhereClause where-Clause
559    * @param anOrderByClause orderBy-Clause
560    * @param offset ab welchem Datensatz
561    * @param limit wieviele Datens?tze
562    * @return EntityList mit den gematchten Entities
563    * @exception StorageObjectException
564    */
565   public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
566             int offset, int limit) throws StorageObjectFailure {
567     return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);              
568   }
569
570   /**
571    * select-Operator returns EntityList with matching rows in Database.
572    * @param aWhereClause where-Clause
573    * @param anOrderByClause orderBy-Clause
574    * @param offset ab welchem Datensatz
575    * @param limit wieviele Datens?tze
576    * @return EntityList mit den gematchten Entities
577    * @exception StorageObjectException
578    */
579   public EntityList selectByWhereClause(String mainTablePrefix, List extraTables,
580       String aWhereClause, String anOrderByClause,
581                         int offset, int limit) throws StorageObjectFailure {
582     
583     
584     String useTable = theTable;
585     String selectStar = "*";
586     if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
587       useTable+=" "+mainTablePrefix;
588       selectStar=mainTablePrefix.trim() + ".*";
589     }
590     
591     // check o_store for entitylist
592     // only if no relational select
593     if (extraTables==null) {
594       if (StoreUtil.implementsStorableObject(theEntityClass)) {
595         StoreIdentifier search_sid =
596             new StoreIdentifier(
597               theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
598               StoreUtil.getEntityListUniqueIdentifierFor(useTable, aWhereClause, anOrderByClause, offset, limit));
599         EntityList hit = (EntityList) o_store.use(search_sid);
600   
601         if (hit != null) {
602           logger.debug("CACHE (hit): " + search_sid.toString());
603   
604           return hit;
605         }
606       }
607     }
608
609     // local
610     EntityList theReturnList = null;
611     Connection con = null;
612     Statement stmt = null;
613     ResultSet rs;
614     int offsetCount = 0;
615     int count = 0;
616
617     // build sql-statement
618
619     if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
620       aWhereClause = null;
621     }
622
623     StringBuffer countSql =
624       new StringBuffer("select count(*) from ").append(useTable);
625     StringBuffer selectSql =
626       new StringBuffer("select "+selectStar+" from ").append(useTable);
627  
628     // append extratables, if necessary
629     if (extraTables!=null) {
630       for (int i=0;i < extraTables.size();i++) {
631         countSql.append( ", " + extraTables.get(i));
632         selectSql.append( ", " + extraTables.get(i));
633       }
634     }
635     
636     if (aWhereClause != null) {
637       selectSql.append(" where ").append(aWhereClause);
638       countSql.append(" where ").append(aWhereClause);
639     }
640
641     if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
642       selectSql.append(" order by ").append(anOrderByClause);
643     }
644
645     if ((limit > -1) && (offset > -1)) {
646       selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
647     }
648
649     // execute sql
650     try {
651       con = getPooledCon();
652       stmt = con.createStatement();
653
654       // selecting...
655       rs = executeSql(stmt, selectSql.toString());
656
657       if (rs != null) {
658         if (!evaluatedMetaData) {
659           evalMetaData(rs.getMetaData());
660         }
661
662         theReturnList = new EntityList();
663         Entity theResultEntity;
664         while (rs.next()) {
665           theResultEntity = makeEntityFromResultSet(rs);
666           theReturnList.add(theResultEntity);
667           offsetCount++;
668         }
669         rs.close();
670       }
671
672       // making entitylist infos
673       count = offsetCount;
674
675       if (theReturnList != null) {
676         // now we decide if we have to know an overall count...
677         count = offsetCount;
678
679         if ((limit > -1) && (offset > -1)) {
680           if (offsetCount == limit) {
681             rs = executeSql(stmt, countSql.toString());
682
683             if (rs != null) {
684               if (rs.next()) {
685                 count = rs.getInt(1);
686               }
687
688               rs.close();
689             }
690             else {
691               logger.error("Could not count: " + countSql);
692             }
693           }
694         }
695
696         theReturnList.setCount(count);
697         theReturnList.setOffset(offset);
698         theReturnList.setWhere(aWhereClause);
699         theReturnList.setOrder(anOrderByClause);
700         theReturnList.setStorage(this);
701         theReturnList.setLimit(limit);
702
703         if (offset >= limit) {
704           theReturnList.setPrevBatch(offset - limit);
705         }
706
707         if ((offset + offsetCount) < count) {
708           theReturnList.setNextBatch(offset + limit);
709         }
710
711         if (extraTables==null && StoreUtil.implementsStorableObject(theEntityClass)) {
712           StoreIdentifier sid = theReturnList.getStoreIdentifier();
713           logger.debug("CACHE (add): " + sid.toString());
714           o_store.add(sid);
715         }
716       }
717     }
718     catch (SQLException sqe) {
719       throwSQLException(sqe, "selectByWhereClause");
720     }
721     finally {
722       try {
723         if (con != null) {
724           freeConnection(con, stmt);
725         }
726       } catch (Throwable t) {
727       }
728     }
729
730     return theReturnList;
731   }
732
733   /**
734    *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
735    *
736    *  @param rs Das ResultSetObjekt.
737    *  @return Entity Die Entity.
738    */
739   private Entity makeEntityFromResultSet(ResultSet rs)
740     throws StorageObjectFailure {
741     /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
742     Map theResultHash = new HashMap();
743     String theResult = null;
744     int theType;
745     Entity returnEntity = null;
746
747     try {
748       int size = metadataFields.size();
749
750       for (int i = 0; i < size; i++) {
751         // alle durchlaufen bis nix mehr da
752         theType = metadataTypes[i];
753
754         if (theType == java.sql.Types.LONGVARBINARY) {
755           InputStreamReader is =
756             (InputStreamReader) rs.getCharacterStream(i + 1);
757
758           if (is != null) {
759             char[] data = new char[32768];
760             StringBuffer theResultString = new StringBuffer();
761             int len;
762
763             while ((len = is.read(data)) > 0) {
764               theResultString.append(data, 0, len);
765             }
766
767             is.close();
768             theResult = theResultString.toString();
769           } else {
770             theResult = null;
771           }
772         } else {
773           theResult = getValueAsString(rs, (i + 1), theType);
774         }
775
776         if (theResult != null) {
777           theResultHash.put(metadataFields.get(i), theResult);
778         }
779       }
780
781       if (theEntityClass != null) {
782         returnEntity = (Entity) theEntityClass.newInstance();
783         returnEntity.setStorage(this);
784         returnEntity.setValues(theResultHash);
785
786         if (returnEntity instanceof StorableObject) {
787           logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
788           o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
789         }
790       } else {
791         throwStorageObjectException("Internal Error: theEntityClass not set!");
792       }
793     }
794     catch (IllegalAccessException e) {
795       throwStorageObjectException("No access! -- " + e.getMessage());
796     }
797     catch (IOException e) {
798       throwStorageObjectException("IOException! -- " + e.getMessage());
799     }
800     catch (InstantiationException e) {
801       throwStorageObjectException("No Instatiation! -- " + e.getMessage());
802     }
803     catch (SQLException sqe) {
804       throwSQLException(sqe, "makeEntityFromResultSet");
805
806       return null;
807     }
808
809     return returnEntity;
810   }
811
812   /**
813    * Inserts an entity into the database.
814    *
815    * @param theEntity
816    * @return der Wert des Primary-keys der eingef?gten Entity
817    */
818   public String insert(Entity theEntity) throws StorageObjectFailure {
819     //cache
820     invalidatePopupCache();
821
822     // invalidating all EntityLists corresponding with theEntityClass
823     if (StoreUtil.implementsStorableObject(theEntityClass)) {
824       StoreContainerType stoc_type =
825         StoreContainerType.valueOf(theEntityClass,
826           StoreContainerType.STOC_TYPE_ENTITYLIST);
827       o_store.invalidate(stoc_type);
828     }
829
830     String returnId = null;
831     Connection con = null;
832     PreparedStatement pstmt = null;
833
834     try {
835       List streamedInput = theEntity.streamedInput();
836       StringBuffer f = new StringBuffer();
837       StringBuffer v = new StringBuffer();
838       String aField;
839       String aValue;
840       boolean firstField = true;
841
842       // make sql-string
843       for (int i = 0; i < getFields().size(); i++) {
844         aField = (String) getFields().get(i);
845
846         if (!aField.equals(thePKeyName)) {
847           aValue = null;
848
849           // exceptions
850           if (!theEntity.hasValueForField(aField) && (
851               aField.equals("webdb_create") ||
852               aField.equals("webdb_lastchange"))) {
853             aValue = "NOW()";
854           }
855           else {
856             if ((streamedInput != null) && streamedInput.contains(aField)) {
857               aValue = "?";
858             }
859             else {
860               if (theEntity.hasValueForField(aField)) {
861                 aValue =
862                   "'" +
863                    JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";
864               }
865             }
866           }
867
868           // wenn Wert gegeben, dann einbauen
869           if (aValue != null) {
870             if (firstField == false) {
871               f.append(",");
872               v.append(",");
873             }
874             else {
875               firstField = false;
876             }
877
878             f.append(aField);
879             v.append(aValue);
880           }
881         }
882       }
883        // end for
884
885       // insert into db
886       StringBuffer sqlBuf =
887         new StringBuffer("insert into ").append(theTable).append("(").append(f)
888                                         .append(") values (").append(v).append(")");
889       String sql = sqlBuf.toString();
890
891       logger.debug("INSERT: " + sql);
892       con = getPooledCon();
893       con.setAutoCommit(false);
894       pstmt = con.prepareStatement(sql);
895
896       if (streamedInput != null) {
897         for (int i = 0; i < streamedInput.size(); i++) {
898           String inputString =
899             (String) theEntity.getValue((String) streamedInput.get(i));
900           pstmt.setBytes(i + 1, inputString.getBytes());
901         }
902       }
903
904       int ret = pstmt.executeUpdate();
905
906       if (ret == 0) {
907         //insert failed
908         return null;
909       }
910
911       pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");
912
913       ResultSet rs = pstmt.executeQuery();
914       rs.next();
915       returnId = rs.getString(1);
916       theEntity.setId(returnId);
917     }
918     catch (SQLException sqe) {
919       throwSQLException(sqe, "insert");
920     }
921     finally {
922       try {
923         con.setAutoCommit(true);
924       }
925       catch (Exception e) {
926       }
927
928       freeConnection(con, pstmt);
929     }
930
931     /** @todo store entity in o_store */
932     return returnId;
933   }
934
935   /**
936    * Updates an entity in the database
937    *
938    * @param theEntity
939    */
940   public void update(Entity theEntity) throws StorageObjectFailure {
941     Connection con = null;
942     PreparedStatement pstmt = null;
943
944     /** @todo this is stupid: why do we prepare statement, when we
945      *  throw it away afterwards. should be regular statement
946      *  update/insert could better be one routine called save()
947      *  that chooses to either insert or update depending if we
948      *  have a primary key in the entity. i don't know if we
949      *  still need the streamed input fields. // rk  */
950     /** @todo extension: check if Entity did change, otherwise we don't need
951      *  the roundtrip to the database */
952     /** invalidating corresponding entitylists in o_store*/
953     if (StoreUtil.implementsStorableObject(theEntityClass)) {
954       StoreContainerType stoc_type =
955         StoreContainerType.valueOf(theEntityClass,
956           StoreContainerType.STOC_TYPE_ENTITYLIST);
957       o_store.invalidate(stoc_type);
958     }
959
960     List streamedInput = theEntity.streamedInput();
961     String id = theEntity.getId();
962     String aField;
963     StringBuffer fv = new StringBuffer();
964     boolean firstField = true;
965
966     //cache
967     invalidatePopupCache();
968
969     // build sql statement
970     for (int i = 0; i < getFields().size(); i++) {
971       aField = (String) metadataFields.get(i);
972
973       // only normal cases
974       if (  !(aField.equals(thePKeyName) ||
975             aField.equals("webdb_create") ||
976             aField.equals("webdb_lastchange") ||
977             ((streamedInput != null) && streamedInput.contains(aField)))) {
978         if (theEntity.hasValueForField(aField)) {
979           if (firstField == false) {
980             fv.append(", ");
981           }
982           else {
983             firstField = false;
984           }
985
986           fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
987
988           //              fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
989         }
990       }
991     }
992
993     StringBuffer sql =
994       new StringBuffer("update ").append(theTable).append(" set ").append(fv);
995
996     // exceptions
997     if (metadataFields.contains("webdb_lastchange")) {
998       sql.append(",webdb_lastchange=NOW()");
999     }
1000
1001     // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
1002     // format so anything extra will be ignored. -mh
1003     if (metadataFields.contains("webdb_create") &&
1004         theEntity.hasValueForField("webdb_create")) {
1005       // minimum of 10 (yyyy-mm-dd)...
1006       if (theEntity.getValue("webdb_create").length() >= 10) {
1007         String dateString = theEntity.getValue("webdb_create");
1008
1009         // if only 10, then add 00:00 so it doesn't throw a ParseException
1010         if (dateString.length() == 10) {
1011           dateString = dateString + " 00:00";
1012         }
1013
1014         // TimeStamp stuff
1015         try {
1016           java.util.Date d = userInputDateFormat.parse(dateString);
1017 //          Timestamp tStamp = new Timestamp(d.getTime());
1018           sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
1019         }
1020         catch (ParseException e) {
1021           throw new StorageObjectFailure(e);
1022         }
1023       }
1024     }
1025
1026     if (streamedInput != null) {
1027       for (int i = 0; i < streamedInput.size(); i++) {
1028         sql.append(",").append(streamedInput.get(i)).append("=?");
1029       }
1030     }
1031
1032     sql.append(" where id=").append(id);
1033     logger.debug("UPDATE: " + sql);
1034
1035     try {
1036       con = getPooledCon();
1037       con.setAutoCommit(false);
1038       pstmt = con.prepareStatement(sql.toString());
1039
1040       if (streamedInput != null) {
1041         for (int i = 0; i < streamedInput.size(); i++) {
1042           String inputString =
1043             theEntity.getValue((String) streamedInput.get(i));
1044           pstmt.setBytes(i + 1, inputString.getBytes());
1045         }
1046       }
1047
1048       pstmt.executeUpdate();
1049     }
1050     catch (SQLException sqe) {
1051       throwSQLException(sqe, "update");
1052     }
1053     finally {
1054       try {
1055         con.setAutoCommit(true);
1056       }
1057       catch (Exception e) {
1058         ;
1059       }
1060
1061       freeConnection(con, pstmt);
1062     }
1063   }
1064
1065   /*
1066   *   delete-Operator
1067   *   @param id des zu loeschenden Datensatzes
1068   *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
1069    */
1070   public boolean delete(String id) throws StorageObjectFailure {
1071     invalidatePopupCache();
1072
1073     // ostore send notification
1074     if (StoreUtil.implementsStorableObject(theEntityClass)) {
1075       String uniqueId = id;
1076
1077       if (theEntityClass.equals(StorableObjectEntity.class)) {
1078         uniqueId += ("@" + theTable);
1079       }
1080
1081       logger.debug("CACHE: (del) " + id);
1082
1083       StoreIdentifier search_sid =
1084         new StoreIdentifier(theEntityClass,
1085           StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
1086       o_store.invalidate(search_sid);
1087     }
1088
1089     /** @todo could be prepared Statement */
1090     Statement stmt = null;
1091     Connection con = null;
1092     int res = 0;
1093     String sql =
1094       "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
1095
1096     //theLog.printInfo("DELETE " + sql);
1097     try {
1098       con = getPooledCon();
1099       stmt = con.createStatement();
1100       res = stmt.executeUpdate(sql);
1101     } catch (SQLException sqe) {
1102       throwSQLException(sqe, "delete");
1103     } finally {
1104       freeConnection(con, stmt);
1105     }
1106
1107     return (res > 0) ? true : false;
1108   }
1109
1110   /**
1111    * Deletes entities based on a where clause
1112    *
1113    * @param aWhereClause
1114    * @return
1115    * @throws StorageObjectFailure
1116    */
1117   public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
1118     invalidatePopupCache();
1119     if (StoreUtil.implementsStorableObject(theEntityClass)) {
1120       StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
1121       o_store.invalidate(stoc_type);
1122     }
1123
1124     Statement stmt = null;
1125     Connection con = null;
1126     int res = 0;
1127     String sql =
1128       "delete from " + theTable + " where " + aWhereClause;
1129
1130     //theLog.printInfo("DELETE " + sql);
1131     try {
1132       con = getPooledCon();
1133       stmt = con.createStatement();
1134       res = stmt.executeUpdate(sql);
1135     }
1136     catch (SQLException sqe) {
1137       throwSQLException(sqe, "delete");
1138     }
1139     finally {
1140       freeConnection(con, stmt);
1141     }
1142
1143     return res;
1144   }
1145
1146   /* noch nicht implementiert.
1147   * @return immer false
1148    */
1149   public boolean delete(EntityList theEntityList) {
1150     invalidatePopupCache();
1151
1152     return false;
1153   }
1154
1155   /* invalidates the popupCache
1156    */
1157   protected void invalidatePopupCache() {
1158     /** @todo  invalidates toooo much */
1159     popupCache = null;
1160     hashCache = null;
1161   }
1162
1163   /**
1164    * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1165    * @param stmt Statemnt
1166    * @param sql Sql-String
1167    * @return ResultSet
1168    * @exception StorageObjectException
1169    */
1170   public ResultSet executeSql(Statement stmt, String sql)
1171                             throws StorageObjectFailure, SQLException {
1172     ResultSet rs;
1173     long startTime = System.currentTimeMillis();
1174
1175     try {
1176       rs = stmt.executeQuery(sql);
1177
1178       logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1179     }
1180     catch (SQLException e) {
1181       logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1182       throw e;
1183     }
1184
1185     return rs;
1186   }
1187 /*
1188   public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
1189     long startTime = System.currentTimeMillis();
1190     Connection connection = null;
1191     Statement statement = null;
1192
1193     try {
1194       connection = getPooledCon();
1195       statement = connection.createStatement();
1196       ResultSet result;
1197
1198       result = statement.executeQuery(sql);
1199
1200       logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1201       return result;
1202     }
1203     catch (Throwable e) {
1204       logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1205       throw new StorageObjectFailure(e);
1206     }
1207     finally {
1208       if (connection!=null) {
1209         freeConnection(connection, statement);
1210       }
1211     }
1212   }
1213 */
1214   private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
1215     try {
1216       Map result = new HashMap();
1217       ResultSetMetaData metaData = aResultSet.getMetaData();
1218       int nrColumns = metaData.getColumnCount();
1219       for (int i=0; i<nrColumns; i++) {
1220         result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
1221       }
1222
1223       return result;
1224     }
1225     catch (Throwable e) {
1226       throw new StorageObjectFailure(e);
1227     }
1228   }
1229
1230   public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
1231     Connection connection = null;
1232     Statement statement = null;
1233     try {
1234       List result = new Vector();
1235       connection = getPooledCon();
1236       statement = connection.createStatement();
1237       ResultSet resultset = executeSql(statement, sql);
1238       try {
1239         while (resultset.next() && result.size() < aLimit) {
1240           result.add(processRow(resultset));
1241         }
1242       }
1243       finally {
1244         resultset.close();
1245       }
1246
1247       return result;
1248     }
1249     catch (Throwable e) {
1250       throw new StorageObjectFailure(e);
1251     }
1252     finally {
1253       if (connection!=null) {
1254         freeConnection(connection, statement);
1255       }
1256     }
1257   };
1258
1259   public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
1260     try {
1261       List resultList = executeFreeSql(anSqlStatement, 1);
1262       try {
1263         if (resultList.size()>0)
1264           return (Map) resultList.get(0);
1265         else
1266           return null;
1267       }
1268       finally {
1269       }
1270     }
1271     catch (Throwable t) {
1272       throw new StorageObjectFailure(t);
1273     }
1274   };
1275
1276   public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
1277     Map row = executeFreeSingleRowSql(sql);
1278
1279     if (row==null)
1280       return null;
1281
1282     Iterator i = row.values().iterator();
1283     if (i.hasNext())
1284       return (String) i.next();
1285     else
1286       return null;
1287   };
1288
1289   /**
1290    * returns the number of rows in the table
1291    */
1292   public int getSize(String where) throws SQLException, StorageObjectFailure {
1293     long startTime = System.currentTimeMillis();
1294     String sql = "SELECT Count(*) FROM " + theTable;
1295
1296     if ((where != null) && (where.length() != 0)) {
1297       sql = sql + " where " + where;
1298     }
1299
1300     Connection con = null;
1301     Statement stmt = null;
1302     int result = 0;
1303
1304     try {
1305       con = getPooledCon();
1306       stmt = con.createStatement();
1307
1308       ResultSet rs = executeSql(stmt, sql);
1309
1310       while (rs.next()) {
1311         result = rs.getInt(1);
1312       }
1313     }
1314     catch (SQLException e) {
1315       logger.error("Database.getSize: " + e.getMessage());
1316     }
1317     finally {
1318       freeConnection(con, stmt);
1319     }
1320
1321     //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1322     logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1323
1324     return result;
1325   }
1326
1327   public int executeUpdate(Statement stmt, String sql)
1328     throws StorageObjectFailure, SQLException {
1329     int rs;
1330     long startTime = System.currentTimeMillis();
1331
1332     try {
1333       rs = stmt.executeUpdate(sql);
1334
1335       logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1336     }
1337     catch (SQLException e) {
1338       logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1339       throw e;
1340     }
1341
1342     return rs;
1343   }
1344
1345   public int executeUpdate(String sql)
1346     throws StorageObjectFailure, SQLException {
1347     int result = -1;
1348     long startTime = System.currentTimeMillis();
1349     Connection con = null;
1350     PreparedStatement pstmt = null;
1351
1352     try {
1353       con = getPooledCon();
1354       pstmt = con.prepareStatement(sql);
1355       result = pstmt.executeUpdate();
1356     }
1357     catch (Throwable e) {
1358       logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
1359       throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
1360     }
1361     finally {
1362       freeConnection(con, pstmt);
1363     }
1364
1365     logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1366     return result;
1367   }
1368
1369   /**
1370    * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1371    * @param md ResultSetMetaData
1372    * @exception StorageObjectException
1373    */
1374   private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
1375     this.evaluatedMetaData = true;
1376     this.metadataFields = new ArrayList();
1377     this.metadataLabels = new ArrayList();
1378     this.metadataNotNullFields = new ArrayList();
1379
1380     try {
1381       int numFields = md.getColumnCount();
1382       this.metadataTypes = new int[numFields];
1383
1384       String aField;
1385       int aType;
1386
1387       for (int i = 1; i <= numFields; i++) {
1388         aField = md.getColumnName(i);
1389         metadataFields.add(aField);
1390         metadataLabels.add(md.getColumnLabel(i));
1391         aType = md.getColumnType(i);
1392         metadataTypes[i - 1] = aType;
1393
1394         if (aField.equals(thePKeyName)) {
1395           thePKeyType = aType;
1396           thePKeyIndex = i;
1397         }
1398
1399         if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
1400           metadataNotNullFields.add(aField);
1401         }
1402       }
1403     }
1404     catch (SQLException e) {
1405       throwSQLException(e, "evalMetaData");
1406     }
1407   }
1408
1409   /**
1410    *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1411    *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1412    */
1413   private void get_meta_data() throws StorageObjectFailure {
1414     Connection con = null;
1415     PreparedStatement pstmt = null;
1416     String sql = "select * from " + theTable + " where 0=1";
1417
1418     try {
1419       con = getPooledCon();
1420       pstmt = con.prepareStatement(sql);
1421
1422       logger.debug("METADATA: " + sql);
1423       ResultSet rs = pstmt.executeQuery();
1424       evalMetaData(rs.getMetaData());
1425       rs.close();
1426     }
1427     catch (SQLException e) {
1428       throwSQLException(e, "get_meta_data");
1429     }
1430     finally {
1431       freeConnection(con, pstmt);
1432     }
1433   }
1434
1435   public Connection getPooledCon() throws StorageObjectFailure {
1436     Connection con = null;
1437
1438     try {
1439       con = SQLManager.getInstance().requestConnection();
1440     }
1441     catch (SQLException e) {
1442       logger.error("could not connect to the database " + e.getMessage());
1443
1444       throw new StorageObjectFailure("Could not connect to the database", e);
1445     }
1446
1447     return con;
1448   }
1449
1450   public void freeConnection(Connection con, Statement stmt)
1451     throws StorageObjectFailure {
1452     SQLManager.closeStatement(stmt);
1453     SQLManager.getInstance().returnConnection(con);
1454   }
1455
1456   /**
1457    * Wertet SQLException aus und wirft dannach eine StorageObjectException
1458    * @param sqe SQLException
1459    * @param wo Funktonsname, in der die SQLException geworfen wurde
1460    * @exception StorageObjectException
1461    */
1462   protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {
1463     String state = "";
1464     String message = "";
1465     int vendor = 0;
1466
1467     if (sqe != null) {
1468       state = sqe.getSQLState();
1469       message = sqe.getMessage();
1470       vendor = sqe.getErrorCode();
1471     }
1472
1473     String information =
1474         "SQL Error: " +
1475         "state= " + state +
1476         ", vendor= " + vendor +
1477         ", message=" + message +
1478         ", function= " + aFunction;
1479
1480     logger.error(information);
1481
1482     throw new StorageObjectFailure(information, sqe);
1483   }
1484
1485   protected void _throwStorageObjectException(Exception e, String aFunction)
1486     throws StorageObjectFailure {
1487
1488     if (e != null) {
1489       logger.error(e.getMessage() + aFunction);
1490       throw new StorageObjectFailure(aFunction, e);
1491     }
1492   }
1493
1494   /**
1495    * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1496    * eine StorageObjectException
1497    * @param message Nachricht mit dem Fehler
1498    * @exception StorageObjectException
1499    */
1500   void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
1501     logger.error(aMessage);
1502     throw new StorageObjectFailure(aMessage, null);
1503   }
1504 }