more error handling.
[mir.git] / source / mir / storage / Database.java
1 /*
2  * put your module comment here
3  */
4 package mir.storage;
5
6 import  java.sql.*;
7 import  java.lang.*;
8 import  java.io.*;
9 import  java.util.*;
10 import  freemarker.template.SimpleList;
11 import  freemarker.template.SimpleHash;
12 import  com.javaexchange.dbConnectionBroker.*;
13 import  mir.storage.StorageObject;
14 import  mir.entity.*;
15 import  mir.misc.*;
16
17
18 /**
19  * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
20  * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
21  * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
22  * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
23  * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
24  * Datenbank erfolgt.
25  *
26  * @author RK
27  * @version 16.7.1999
28  */
29 public class Database implements StorageObject {
30
31   protected DbConnectionBroker        myBroker;
32   protected String                    theTable;
33   protected String                    theCoreTable=null;
34   protected String                    thePKeyName="id";
35   protected int                       thePKeyType;
36   protected boolean                   evaluatedMetaData=false;
37   protected ArrayList                 metadataFields,metadataLabels,metadataNotNullFields;
38   protected int[]                     metadataTypes;
39   protected Class                     theEntityClass;
40   protected StorageObject             myselfDatabase;
41   protected HashMap                   cache;
42   protected SimpleList                popupCache=null;
43   protected boolean                   hasPopupCache = false;
44   protected SimpleHash                hashCache=null;
45   protected boolean                   hasTimestamp=true;
46   private       String                database_driver;
47   private       String                database_url;
48   private int                         defaultLimit;
49   protected DatabaseAdaptor             theAdaptor;
50   protected Logfile                   theLog;
51   protected Connection                con;
52
53   /**
54    * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
55    * Aus diesem file werden <code>Database.Logfile</code>,
56    * <code>Database.Username</code>,<code>Database.Password</code>,
57    * <code>Database.Host</code> und <code>Database.Adaptor</code>
58    * ausgelesen und ein Broker für die Verbindugen zur Datenbank
59    * erzeugt.
60    *
61    * @param   String confFilename Dateiname der Konfigurationsdatei
62    */
63   public Database() throws StorageObjectException {
64     theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
65     String database_username=MirConfig.getProp("Database.Username");
66     String database_password=MirConfig.getProp("Database.Password");
67     String database_host=MirConfig.getProp("Database.Host");
68     String theAdaptorName=MirConfig.getProp("Database.Adaptor");
69     try {
70       theEntityClass = Class.forName("mir.entity.GenericEntity");
71       theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
72       defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
73       database_driver=theAdaptor.getDriver();
74       database_url=theAdaptor.getURL(database_username,database_password,database_host);
75       theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url  );
76       MirConfig.addBroker(database_driver,database_url);
77       myBroker=MirConfig.getBroker();
78     }
79     catch (Exception e){
80       theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
81       throw new StorageObjectException(e.toString());
82     }
83   }
84
85   /**
86    * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
87    * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
88    * wird eine mir.entity.GenericEntity erzeugt.
89    *
90    * @return Class-Objekt der Entity
91    */
92   public java.lang.Class getEntityClass () {
93     return  theEntityClass;
94   }
95
96   /**
97    * Liefert die Standardbeschränkung von select-Statements zurück, also
98    * wieviel Datensätze per Default selektiert werden.
99    *
100    * @return Standard-Anzahl der Datensätze
101    */
102   public int getLimit () {
103     return  defaultLimit;
104   }
105
106   /**
107    * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
108    * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
109    * @return Name des Primary-Keys
110    */
111   public String getIdName () {
112     return  thePKeyName;
113   }
114
115   /**
116    * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
117    *
118    * @return Name der Tabelle
119    */
120   public String getTableName () {
121     return  theTable;
122   }
123
124   /*
125    *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
126    *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
127    *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
128    *    the Table
129    */
130
131   public String getCoreTable(){
132     if (theCoreTable!=null) return theCoreTable;
133     else return theTable;
134   }
135
136   /**
137    * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
138    * @return int-Array mit den Typen der Felder
139    * @exception StorageObjectException
140    */
141   public int[] getTypes () throws StorageObjectException {
142     if (metadataTypes == null)
143       get_meta_data();
144     return  metadataTypes;
145   }
146
147   /**
148    * Liefert eine Liste der Labels der Tabellenfelder
149    * @return ArrayListe mit Labeln
150    * @exception StorageObjectException
151    */
152   public ArrayList getLabels () throws StorageObjectException {
153     if (metadataLabels == null)
154       get_meta_data();
155     return  metadataLabels;
156   }
157
158   /**
159    * Liefert eine Liste der Felder der Tabelle
160    * @return ArrayList mit Feldern
161    * @exception StorageObjectException
162    */
163   public ArrayList getFields () throws StorageObjectException {
164     if (metadataFields == null)
165       get_meta_data();
166     return  metadataFields;
167   }
168
169
170   /*
171    *   Gets value out of ResultSet according to type and converts to String
172    *   @param inValue  Wert aus ResultSet.
173    *   @param aType  Datenbanktyp.
174    *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
175    *           dann /unsupported value/
176    */
177   private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
178     String outValue = null;
179     if (rs != null) {
180       try {
181         switch (aType) {
182           case java.sql.Types.BIT:
183             outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
184             break;
185           case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
186             int out = rs.getInt(valueIndex);
187             if (!rs.wasNull())
188               outValue = new Integer(out).toString();
189             break;
190           case java.sql.Types.NUMERIC:
191             long outl = rs.getLong(valueIndex);
192             if (!rs.wasNull())
193               outValue = new Long(outl).toString();
194             break;
195           case java.sql.Types.REAL:
196             float tempf = rs.getFloat(valueIndex);
197             if (!rs.wasNull()) {
198               tempf *= 10;
199               tempf += 0.5;
200               int tempf_int = (int)tempf;
201               tempf = (float)tempf_int;
202               tempf /= 10;
203               outValue = "" + tempf;
204               outValue = outValue.replace('.', ',');
205             }
206             break;
207           case java.sql.Types.DOUBLE:
208             double tempd = rs.getDouble(valueIndex);
209             if (!rs.wasNull()) {
210               tempd *= 10;
211               tempd += 0.5;
212               int tempd_int = (int)tempd;
213               tempd = (double)tempd_int;
214               tempd /= 10;
215               outValue = "" + tempd;
216               outValue = outValue.replace('.', ',');
217             }
218             break;
219           case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
220             outValue = rs.getString(valueIndex);
221             if (outValue != null)
222               outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
223             break;
224           case java.sql.Types.LONGVARBINARY:
225             outValue = rs.getString(valueIndex);
226             if (outValue != null)
227               outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
228             break;
229           case java.sql.Types.TIMESTAMP:
230             Timestamp timestamp = (rs.getTimestamp(valueIndex));
231             if (!rs.wasNull()) {
232               outValue = timestamp.toString();
233             }
234             break;
235           default:
236             outValue = "<unsupported value>";
237             theLog.printWarning("Unsupported Datatype: at " + valueIndex +
238                 " (" + aType + ")");
239         }
240       } catch (SQLException e) {
241         throw  new StorageObjectException("Could not get Value out of Resultset -- "
242             + e.toString());
243       }
244     }
245     return  outValue;
246   }
247
248   /*
249    *   select-Operator um einen Datensatz zu bekommen.
250    *   @param id Primaerschluessel des Datensatzes.
251    *   @return liefert EntityObject des gefundenen Datensatzes oder null.
252    */
253   public Entity selectById(String id)
254     throws StorageObjectException {
255
256     if (id==null||id.equals(""))
257       throw new StorageObjectException("id war null");
258     if (cache != null && cache.containsKey(id))
259       return (Entity)cache.get(id);  // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
260
261     Statement stmt=null;Connection con=getPooledCon();
262     Entity returnEntity=null;
263     try {
264       ResultSet rs;
265       String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
266       stmt = con.createStatement();
267       rs = executeSql(stmt, selectSql);
268       if (rs != null) {
269         if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
270         if (rs.next())
271           returnEntity = makeEntityFromResultSet(rs);
272         else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
273         rs.close();
274       } else {
275         theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
276       }
277     } catch (SQLException sqe){
278       throwSQLException(sqe,"selectById"); return null;
279     } catch (NumberFormatException e) {
280       theLog.printError("ID ist keine Zahl: " + id);
281     } finally {
282       freeConnection(con,stmt);
283     }
284
285     return returnEntity;
286   }
287
288   /**
289    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
290    *   @param key  Datenbankfeld der Bedingung.
291    *   @param value  Wert die der key anehmen muss.
292    *   @return EntityList mit den gematchten Entities
293    */
294
295   public EntityList selectByFieldValue(String aField, String aValue)
296     throws StorageObjectException {
297
298     return selectByFieldValue(aField, aValue, 0);
299   }
300
301   /**
302    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
303    *   @param key  Datenbankfeld der Bedingung.
304    *   @param value  Wert die der key anehmen muss.
305    *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
306    *   @return EntityList mit den gematchten Entities
307    */
308
309   public EntityList selectByFieldValue(String aField, String aValue, int offset)
310     throws StorageObjectException {
311
312     return selectByWhereClause(aField + "=" + aValue, offset);
313   }
314
315
316   /**
317    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
318    * Also offset wird der erste Datensatz genommen.
319    *
320    * @param wc where-Clause
321    * @return EntityList mit den gematchten Entities
322    * @exception StorageObjectException
323    */
324   public EntityList selectByWhereClause(String where)
325     throws StorageObjectException {
326
327     return selectByWhereClause(where, 0);
328   }
329
330
331   /**
332    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
333    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
334    *
335    * @param wc where-Clause
336    * @param offset ab welchem Datensatz.
337    * @return EntityList mit den gematchten Entities
338    * @exception StorageObjectException
339    */
340   public EntityList selectByWhereClause(String whereClause, int offset)
341     throws StorageObjectException {
342
343     return selectByWhereClause(whereClause, null, offset);
344   }
345
346   /**
347    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
348    * Also offset wird der erste Datensatz genommen.
349    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
350    *
351    * @param wc where-Clause
352    * @param ob orderBy-Clause
353    * @return EntityList mit den gematchten Entities
354    * @exception StorageObjectException
355    */
356
357   public EntityList selectByWhereClause(String where, String order)
358     throws StorageObjectException {
359
360     return selectByWhereClause(where, order, 0);
361   }
362   /**
363    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
364    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
365    *
366    * @param wc where-Clause
367    * @param ob orderBy-Clause
368    * @param offset ab welchem Datensatz
369    * @return EntityList mit den gematchten Entities
370    * @exception StorageObjectException
371    */
372
373   public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
374     throws StorageObjectException {
375
376     return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
377   }
378
379
380   /**
381    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
382    * @param wc where-Clause
383    * @param ob orderBy-Clause
384    * @param offset ab welchem Datensatz
385    * @param limit wieviele Datensätze
386    * @return EntityList mit den gematchten Entities
387    * @exception StorageObjectException
388    */
389
390   public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
391     throws StorageObjectException   {
392
393     // local
394     EntityList    theReturnList=null;
395     Connection    con=null;
396     Statement     stmt=null;
397     ResultSet     rs;
398     int       offsetCount = 0;
399     int           count=0;
400
401
402     // build sql-statement
403     if (wc != null && wc.length() == 0) {
404       wc = null;
405     }
406     StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
407     StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
408     if (wc != null) {
409       selectSql.append(" where ").append(wc);
410       countSql.append(" where ").append(wc);
411     }
412     if (ob != null && !(ob.length() == 0)) {
413       selectSql.append(" order by ").append(ob);
414     }
415     if (theAdaptor.hasLimit()) {
416       if (limit > -1 && offset > -1) {
417         selectSql.append(" limit ");
418         if (theAdaptor.reverseLimit()) {
419           selectSql.append(limit).append(",").append(offset);
420         }
421         else {
422           selectSql.append(offset).append(",").append(limit);
423         }
424       }
425     }
426
427       // execute sql
428     try {
429       con = getPooledCon();
430       stmt = con.createStatement();
431       // counting rows
432       if (theAdaptor.hasLimit()) {
433         rs = executeSql(stmt, countSql.toString());
434         if (rs != null) {
435           if (rs.next())
436             count = rs.getInt(1);
437           rs.close();
438         }
439         else
440           theLog.printError("Mh. Konnte nicht zaehlen: " + countSql);
441       }
442       // hier select
443       rs = executeSql(stmt, selectSql.toString());
444       if (rs != null) {
445         theReturnList = new EntityList();
446         if (evaluatedMetaData == false) {
447           evalMetaData(rs.getMetaData());
448         }
449         Entity theResultEntity;
450         while (rs.next()) {
451           theResultEntity = makeEntityFromResultSet(rs);
452           theReturnList.add(theResultEntity);
453           offsetCount++;
454         }
455         rs.close();
456       }
457       // making entitylist
458       if (!(theAdaptor.hasLimit()))
459         count = offsetCount;
460       if (theReturnList != null) {
461         theReturnList.setCount(count);
462         theReturnList.setOffset(offset);
463         theReturnList.setWhere(wc);
464         theReturnList.setOrder(ob);
465         if (offset >= limit) {
466           theReturnList.setPrevBatch(offset - limit);
467         }
468         if (offset + offsetCount < count) {
469           theReturnList.setNextBatch(offset + limit);
470         }
471       }
472     } catch (SQLException sqe) {
473       throwSQLException(sqe, "selectByWhereClause");
474     } finally {
475       freeConnection(con, stmt);
476     }
477     return  theReturnList;
478   }
479
480   /**
481    *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
482    *
483    *  @param rs Das ResultSetObjekt.
484    *  @return Entity Die Entity.
485    */
486
487   public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
488     HashMap theResultHash = new HashMap();
489     String theResult = null;
490     int theType;
491     Entity returnEntity = null;
492     try {
493       int size = metadataFields.size();
494       for (int i = 0; i < size; i++) {
495         // alle durchlaufen bis nix mehr da
496         theType = metadataTypes[i];
497         if (theType == java.sql.Types.LONGVARBINARY) {
498           InputStream us = rs.getAsciiStream(i + 1);
499           if (us != null) {
500             InputStreamReader is = new InputStreamReader(us);
501             char[] data = new char[32768];
502             StringBuffer theResultString = new StringBuffer();
503             int len;
504             while ((len = is.read(data)) > 0) {
505               theResultString.append(data, 0, len);
506             }
507             is.close();
508             theResult = theResultString.toString();
509           }
510           else {
511             theResult = null;
512           }
513         }
514         else {
515           theResult = getValueAsString(rs, (i + 1), theType);
516         }
517         if (theResult != null) {
518           theResultHash.put(metadataFields.get(i), theResult);
519         }
520       }
521       if (cache != null && theResultHash.containsKey(thePKeyName) && cache.containsKey((String)theResultHash.get(thePKeyName))) {
522         //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
523         returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
524       }
525       else {
526         if (theEntityClass != null) {
527           returnEntity = (Entity)theEntityClass.newInstance();
528           returnEntity.setValues(theResultHash);
529           returnEntity.setStorage(myselfDatabase);
530           if (cache != null) {
531             //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
532             cache.put(returnEntity.getId(), returnEntity);
533           }
534         }
535         else {
536           throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
537         }
538       }
539     }           // try
540     catch (IllegalAccessException e) {
541       throwStorageObjectException("Kein Zugriff! -- " + e.toString());
542     } catch (IOException e) {
543       throwStorageObjectException("IOException! -- " + e.toString());
544     } catch (InstantiationException e) {
545       throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
546     } catch (SQLException sqe) {
547       throwSQLException(sqe, "makeEntityFromResultSet");
548       return  null;
549     }
550     return  returnEntity;
551   }
552
553   /**
554    * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
555    * wird automatisch mit dem aktuellen Datum gefuellt.
556    *
557    * @param theEntity
558    * @return der Wert des Primary-keys der eingefügten Entity
559    */
560   public String insert (Entity theEntity) throws StorageObjectException {
561     String returnId = null;
562     Connection con = null;
563     PreparedStatement pstmt = null;
564     //cache
565     invalidatePopupCache();
566     try {
567       HashMap theEntityValues = theEntity.getValues();
568       ArrayList streamedInput = theEntity.streamedInput();
569       StringBuffer f = new StringBuffer();
570       StringBuffer v = new StringBuffer();
571       String aField, aValue;
572       boolean firstField = true;
573       // make sql-string
574       for (int i = 0; i < getFields().size(); i++) {
575         aField = (String)getFields().get(i);
576         if (!aField.equals(thePKeyName)) {
577           aValue = null;
578           // sonderfaelle
579           if (aField.equals("webdb_create")) {
580             aValue = "NOW()";
581           }
582           else {
583             if (streamedInput != null && streamedInput.contains(aField)) {
584               aValue = "?";
585             }
586             else {
587               if (theEntityValues.containsKey(aField)) {
588                 aValue = "'" + StringUtil.quote((String)theEntityValues.get(aField))
589                     + "'";
590               }
591             }
592           }
593           // wenn Wert gegeben, dann einbauen
594           if (aValue != null) {
595             if (firstField == false) {
596               f.append(",");
597               v.append(",");
598             }
599             else {
600               firstField = false;
601             }
602             f.append(aField);
603             v.append(aValue);
604           }
605         }
606       }         // end for
607       // insert into db
608       StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
609       String sql = sqlBuf.toString();
610       theLog.printInfo("INSERT: " + sql);
611       con = getPooledCon();
612       con.setAutoCommit(false);
613       pstmt = con.prepareStatement(sql);
614       if (streamedInput != null) {
615         for (int i = 0; i < streamedInput.size(); i++) {
616           String inputString = (String)theEntityValues.get(streamedInput.get(i));
617           pstmt.setBytes(i + 1, inputString.getBytes());
618         }
619       }
620       int ret = pstmt.executeUpdate();
621       if(ret == 0){
622         //insert failed
623         return null;
624       }
625       pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
626       ResultSet rs = pstmt.executeQuery();
627       rs.next();
628       returnId = rs.getString(1);
629       theEntity.setId(returnId);
630     } catch (SQLException sqe) {
631       throwSQLException(sqe, "insert");
632     } finally {
633       try {
634         con.setAutoCommit(true);
635       } catch (Exception e) {
636         ;
637       }
638       freeConnection(con, pstmt);
639     }
640     return  returnId;
641   }
642
643   /**
644    * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
645    * wird automatisch mit dem aktuellen Datum gefuellt.
646    *
647    * @param theEntity
648    */
649   public void update (Entity theEntity) throws StorageObjectException {
650     Connection con = null;
651     PreparedStatement pstmt = null;
652     ArrayList streamedInput = theEntity.streamedInput();
653     HashMap theEntityValues = theEntity.getValues();
654     String id = theEntity.getId();
655     String aField;
656     StringBuffer fv = new StringBuffer();
657     boolean firstField = true;
658     //cache
659     invalidatePopupCache();
660     // build sql statement
661     for (int i = 0; i < getFields().size(); i++) {
662       aField = (String)metadataFields.get(i);
663       // only normal cases
664       if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
665           aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
666         if (theEntityValues.containsKey(aField)) {
667           if (firstField == false) {
668             fv.append(", ");
669           }
670           else {
671             firstField = false;
672           }
673           fv.append(aField).append("='").append(StringUtil.quote((String)theEntityValues.get(aField))).append("'");
674         }
675       }
676     }
677     StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
678     // exceptions
679     if (metadataFields.contains("webdb_lastchange")) {
680       sql.append(",webdb_lastchange=NOW()");
681     }
682     if (streamedInput != null) {
683       for (int i = 0; i < streamedInput.size(); i++) {
684         sql.append(",").append(streamedInput.get(i)).append("=?");
685       }
686     }
687     sql.append(" where id=").append(id);
688     theLog.printInfo("UPDATE: " + sql);
689     // execute sql
690     try {
691       con = getPooledCon();
692       con.setAutoCommit(false);
693       pstmt = con.prepareStatement(sql.toString());
694       if (streamedInput != null) {
695         for (int i = 0; i < streamedInput.size(); i++) {
696           String inputString = (String)theEntityValues.get(streamedInput.get(i));
697           pstmt.setBytes(i + 1, inputString.getBytes());
698         }
699       }
700       pstmt.executeUpdate();
701     } catch (SQLException sqe) {
702       throwSQLException(sqe, "update");
703     } finally {
704       try {
705         con.setAutoCommit(true);
706       } catch (Exception e) {
707         ;
708       }
709       freeConnection(con, pstmt);
710     }
711   }
712
713   /*
714    *   delete-Operator
715    *   @param id des zu loeschenden Datensatzes
716    *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
717    */
718   public boolean delete (String id) throws StorageObjectException {
719     Statement stmt = null;
720     Connection con = null;
721     String sql;
722     int res = 0;
723     // loeschen des caches
724     invalidatePopupCache();
725     sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
726         "'";
727     theLog.printInfo("DELETE " + sql);
728     try {
729       con = getPooledCon();
730       stmt = con.createStatement();
731       res = stmt.executeUpdate(sql);
732     } catch (SQLException sqe) {
733       throwSQLException(sqe, "delete");
734     } finally {
735       freeConnection(con, stmt);
736     }
737     if (cache != null) {
738       theLog.printInfo("CACHE: deleted " + id);
739       cache.remove(id);
740     }
741     return  (res > 0) ? true : false;
742   }
743
744   /* noch nicht implementiert.
745    * @return immer false
746    */
747   public boolean delete (EntityList theEntityList) {
748     invalidatePopupCache();
749     return  false;
750   }
751
752   /**
753    * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
754    * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
755    * @return null
756    */
757   public SimpleList getPopupData () throws StorageObjectException {
758     return  null;
759   }
760
761   /**
762    *  Holt Daten fuer Popups.
763    *  @param name  Name des Feldes.
764    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
765    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
766    */
767   public SimpleList getPopupData (String name, boolean hasNullValue) 
768     throws StorageObjectException {
769     return  getPopupData(name, hasNullValue, null);
770   }
771
772   /**
773    *  Holt Daten fuer Popups.
774    *  @param name  Name des Feldes.
775    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
776    *  @param where  Schraenkt die Selektion der Datensaetze ein.
777    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
778    */
779   public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
780    return  getPopupData(name, hasNullValue, where, null);
781   }
782
783   /**
784    *  Holt Daten fuer Popups.
785    *  @param name  Name des Feldes.
786    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
787    *  @param where  Schraenkt die Selektion der Datensaetze ein.
788    *  @param order  Gibt ein Feld als Sortierkriterium an.
789    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
790    */
791   public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
792     // caching
793     if (hasPopupCache && popupCache != null)
794       return  popupCache;
795     SimpleList simpleList = null;
796     Connection con = null;
797     Statement stmt = null;
798     // build sql
799     StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
800     if (where != null && !(where.length() == 0))
801       sql.append(" where ").append(where);
802     sql.append(" order by ");
803     if (order != null && !(order.length() == 0))
804       sql.append(order);
805     else
806       sql.append(name);
807     // execute sql
808     try {
809       con = getPooledCon();
810       stmt = con.createStatement();
811       ResultSet rs = executeSql(stmt, sql.toString());
812       if (rs != null) {
813         if (evaluatedMetaData == false)
814           get_meta_data();
815         simpleList = new SimpleList();
816         SimpleHash popupDict;
817         if (hasNullValue) {
818           popupDict = new SimpleHash();
819           popupDict.put("key", "");
820           popupDict.put("value", "--");
821           simpleList.add(popupDict);
822         }
823         while (rs.next()) {
824           popupDict = new SimpleHash();
825           popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
826           popupDict.put("value", rs.getString(2));
827           simpleList.add(popupDict);
828         }
829         rs.close();
830       }
831     } catch (Exception e) {
832       theLog.printDebugInfo(e.toString());
833       throw new StorageObjectException(e.toString());
834     } finally {
835       freeConnection(con, stmt);
836     }
837     if (hasPopupCache) {
838       popupCache = simpleList;
839     }
840     return  simpleList;
841   }
842
843   /**
844    * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
845    * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
846    * Tabellen Verwendung finden.
847    * @return SimpleHash mit den Tabellezeilen.
848    */
849   public SimpleHash getHashData () {
850     if (hashCache == null) {
851       try {
852         hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
853             -1));
854       } catch (StorageObjectException e) {
855         theLog.printDebugInfo(e.toString());
856       }
857     }
858     return  hashCache;
859   }
860
861   /* invalidates the popupCache
862    */
863   protected void invalidatePopupCache () {
864
865     /** @todo  invalidates toooo much */
866     popupCache = null;
867     hashCache = null;
868   }
869
870   /**
871    * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
872    * @param stmt Statemnt
873    * @param sql Sql-String
874    * @return ResultSet
875    * @exception StorageObjectException
876    */
877   public ResultSet executeSql (Statement stmt, String sql)
878     throws StorageObjectException, SQLException
879   {
880     ResultSet rs;
881     long startTime = (new java.util.Date()).getTime();
882     try {
883       rs = stmt.executeQuery(sql);
884       theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
885         + sql);
886     }
887     catch (SQLException e)
888     {
889       theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
890         + sql);
891       throw e;
892     }
893
894     return  rs;
895   }
896
897   /**
898    * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
899    * getimed und geloggt.
900    * @param stmt PreparedStatement mit der SQL-Anweisung
901    * @return Liefert ResultSet des Statements zurueck.
902    * @exception StorageObjectException, SQLException
903    */
904   public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
905       SQLException {
906
907     long startTime = (new java.util.Date()).getTime();
908     ResultSet rs = stmt.executeQuery();
909     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
910     return  rs;
911   }
912
913     /**
914    * returns the number of rows in the table
915    */
916   public int getSize(String where)
917     throws SQLException,StorageObjectException
918   {
919     long  startTime = (new java.util.Date()).getTime();
920     String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
921     //theLog.printDebugInfo("trying: "+ sql);
922     Connection con = null;
923     Statement stmt = null;
924     int result = 0;
925
926     try {
927       con = getPooledCon();
928       stmt = con.createStatement();
929       ResultSet rs = executeSql(stmt,sql);
930       while(rs.next()){
931         result = rs.getInt(1);
932       }
933     } catch (SQLException e) {
934       theLog.printError(e.toString());
935     } finally {
936       freeConnection(con,stmt);
937     }
938     theLog.printInfo(theTable + " has "+ result +" rows where " + where);
939     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
940     return result;
941   }
942
943   public int executeUpdate(Statement stmt, String sql)
944     throws StorageObjectException, SQLException
945   {
946     int rs;
947     long  startTime = (new java.util.Date()).getTime();
948     try
949     {
950       rs = stmt.executeUpdate(sql);
951       theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
952     }
953     catch (SQLException e)
954     {
955       theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
956         + sql);
957       throw e;
958     }
959     return rs;
960   }
961
962   public int executeUpdate(String sql)
963     throws StorageObjectException, SQLException
964   {
965     int result=-1;
966     long  startTime = (new java.util.Date()).getTime();
967     Connection con=null;PreparedStatement pstmt=null;
968     try {
969       con=getPooledCon();
970       pstmt = con.prepareStatement(sql);
971       result = pstmt.executeUpdate();
972     }
973     catch (Exception e) {
974       theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
975       throw new StorageObjectException("executeUpdate failed: "+e.toString());
976     }
977     finally { freeConnection(con,pstmt); }
978     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
979     return result;
980   }
981
982   /**
983    * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
984    * @param md ResultSetMetaData
985    * @exception StorageObjectException
986    */
987   private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
988     this.evaluatedMetaData = true;
989     this.metadataFields = new ArrayList();
990     this.metadataLabels = new ArrayList();
991     this.metadataNotNullFields = new ArrayList();
992     try {
993       int numFields = md.getColumnCount();
994       this.metadataTypes = new int[numFields];
995       String aField;
996       int aType;
997       for (int i = 1; i <= numFields; i++) {
998         aField = md.getColumnName(i);
999         metadataFields.add(aField);
1000         metadataLabels.add(md.getColumnLabel(i));
1001         aType = md.getColumnType(i);
1002         metadataTypes[i - 1] = aType;
1003         if (aField.equals(thePKeyName)) {
1004           thePKeyType = aType;
1005         }
1006         if (md.isNullable(i) == md.columnNullable) {
1007           metadataNotNullFields.add(aField);
1008         }
1009       }
1010     } catch (SQLException e) {
1011       throwSQLException(e, "evalMetaData");
1012     }
1013   }
1014
1015   /**
1016    *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1017    *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1018    */
1019   private void get_meta_data () throws StorageObjectException {
1020     Connection con = null;
1021     PreparedStatement pstmt = null;
1022     String sql = "select * from " + theTable + " where 0=1";
1023     try {
1024       con = getPooledCon();
1025       pstmt = con.prepareStatement(sql);
1026       theLog.printInfo("METADATA: " + sql);
1027       ResultSet rs = pstmt.executeQuery();
1028       evalMetaData(rs.getMetaData());
1029       rs.close();
1030     } catch (SQLException e) {
1031       throwSQLException(e, "get_meta_data");
1032     } finally {
1033       freeConnection(con, pstmt);
1034     }
1035   }
1036
1037   /**
1038    * Datenbankverbindung wird geschlossen
1039    */
1040   public void disconnectPool () throws StorageObjectException {
1041     try {
1042       myBroker.destroy(100);
1043     } catch (SQLException sqe) {
1044       throwSQLException(sqe, "disconnectPool");
1045     }
1046   }
1047
1048   /**
1049    * Returns Connection-Object out of the PoolBroker.
1050    *
1051    * @return Connection Object.
1052    */
1053   public Connection getPooledCon () throws StorageObjectException {
1054     if (myBroker != null) {
1055       Connection con = myBroker.getConnection();
1056       if (con != null)
1057         return  con;
1058     }
1059     throw  new StorageObjectException("No connection to database!");
1060   }
1061
1062   /**
1063    * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1064    * zurückgeben
1065    * @param con Connection zur Datenbank
1066    * @param stmt Statement-Objekt
1067    */
1068   public void freeConnection (Connection con, Statement stmt)
1069     throws StorageObjectException {
1070     try {
1071       if (stmt != null)
1072         stmt.close();
1073     } catch (SQLException e1) {
1074       theLog.printDebugInfo(e1.toString());
1075       throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1076     }
1077     if (con != null)
1078       myBroker.freeConnection(con);
1079     else {
1080       theLog.printDebugInfo("Con was null!");
1081       throw new StorageObjectException("Con was null!");
1082     }
1083   }
1084
1085   /**
1086    * Wertet SQLException aus und wirft dannach eine StorageObjectException
1087    * @param sqe SQLException
1088    * @param wo Funktonsname, in der die SQLException geworfen wurde
1089    * @exception StorageObjectException
1090    */
1091   protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1092     String state = "";
1093     String message = "";
1094     int vendor = 0;
1095     if (sqe != null) {
1096       state = sqe.getSQLState();
1097       message = sqe.getMessage();
1098       vendor = sqe.getErrorCode();
1099     }
1100     theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1101         + wo);
1102     throw  new StorageObjectException((sqe == null) ? "undefined sql exception" :
1103         sqe.toString());
1104   }
1105
1106   protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1107     if (e != null) {
1108         theLog.printError(e.toString()+ wo);
1109         throw  new StorageObjectException(wo + e.toString());
1110     } else {
1111         theLog.printError(wo);
1112         throw  new StorageObjectException(wo);
1113     }
1114         
1115   }
1116
1117   /**
1118    * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1119    * @param message Nachricht mit dem Fehler
1120    * @exception StorageObjectException
1121    */
1122   void throwStorageObjectException (String message) throws StorageObjectException {
1123     _throwStorageObjectException(null, message);
1124   }
1125 }
1126
1127
1128