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