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