b8d5f59c49fe67bb4b6276b42f5433b165aa04e0
[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     if (wc != null && wc.length() == 0) {
410       wc = null;
411     }
412     StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
413     StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
414     if (wc != null) {
415       selectSql.append(" where ").append(wc);
416       countSql.append(" where ").append(wc);
417     }
418     if (ob != null && !(ob.length() == 0)) {
419       selectSql.append(" order by ").append(ob);
420     }
421     if (theAdaptor.hasLimit()) {
422       if (limit > -1 && offset > -1) {
423         selectSql.append(" limit ");
424         if (theAdaptor.reverseLimit()) {
425           selectSql.append(limit).append(",").append(offset);
426         }
427         else {
428           selectSql.append(offset).append(",").append(limit);
429         }
430       }
431     }
432
433       // execute sql
434     try {
435       con = getPooledCon();
436       stmt = con.createStatement();
437       // counting rows
438       if (theAdaptor.hasLimit()) {
439         rs = executeSql(stmt, countSql.toString());
440         if (rs != null) {
441           if (rs.next())
442             count = rs.getInt(1);
443           rs.close();
444           //nothing in the table: return null
445           if(count<=0){
446             freeConnection(con, stmt);
447             return null;
448           }
449         } else {
450           theLog.printError("Could not count: " + countSql);
451         }
452       }
453
454       // hier select
455       rs = executeSql(stmt, selectSql.toString());
456       if (rs != null) {
457         theReturnList = new EntityList();
458         if (evaluatedMetaData == false) {
459           evalMetaData(rs.getMetaData());
460         }
461         Entity theResultEntity;
462         while (rs.next()) {
463           theResultEntity = makeEntityFromResultSet(rs);
464           theReturnList.add(theResultEntity);
465           offsetCount++;
466         }
467         rs.close();
468       }
469       // making entitylist
470       if (!(theAdaptor.hasLimit()))
471         count = offsetCount;
472       if (theReturnList != null) {
473         theReturnList.setCount(count);
474         theReturnList.setOffset(offset);
475         theReturnList.setWhere(wc);
476         theReturnList.setOrder(ob);
477         if (offset >= limit) {
478           theReturnList.setPrevBatch(offset - limit);
479         }
480         if (offset + offsetCount < count) {
481           theReturnList.setNextBatch(offset + limit);
482         }
483       }
484     } catch (SQLException sqe) {
485       throwSQLException(sqe, "selectByWhereClause");
486     } finally {
487       freeConnection(con, stmt);
488     }
489     return  theReturnList;
490   }
491
492   /**
493    *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
494    *
495    *  @param rs Das ResultSetObjekt.
496    *  @return Entity Die Entity.
497    */
498
499   public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
500     HashMap theResultHash = new HashMap();
501     String theResult = null;
502     int theType;
503     Entity returnEntity = null;
504     try {
505       int size = metadataFields.size();
506       for (int i = 0; i < size; i++) {
507         // alle durchlaufen bis nix mehr da
508         theType = metadataTypes[i];
509         if (theType == java.sql.Types.LONGVARBINARY) {
510           InputStream us = rs.getAsciiStream(i + 1);
511           if (us != null) {
512             InputStreamReader is = new InputStreamReader(us);
513             char[] data = new char[32768];
514             StringBuffer theResultString = new StringBuffer();
515             int len;
516             while ((len = is.read(data)) > 0) {
517               theResultString.append(data, 0, len);
518             }
519             is.close();
520             theResult = theResultString.toString();
521           }
522           else {
523             theResult = null;
524           }
525         }
526         else {
527           theResult = getValueAsString(rs, (i + 1), theType);
528         }
529         if (theResult != null) {
530           theResultHash.put(metadataFields.get(i), theResult);
531         }
532       }
533       if (cache != null && theResultHash.containsKey(thePKeyName) &&
534           (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
535         returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
536       } else {
537         if (theEntityClass != null) {
538           returnEntity = (Entity)theEntityClass.newInstance();
539           returnEntity.setValues(theResultHash);
540           returnEntity.setStorage(myselfDatabase);
541           if (cache != null) {
542             //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
543             cache.put(returnEntity.getId(), returnEntity);
544           }
545         } else {
546           throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
547         }
548       }
549     } catch (IllegalAccessException e) {
550       throwStorageObjectException("Kein Zugriff! -- " + e.toString());
551     } catch (IOException e) {
552       throwStorageObjectException("IOException! -- " + e.toString());
553     } catch (InstantiationException e) {
554       throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
555     } catch (SQLException sqe) {
556       throwSQLException(sqe, "makeEntityFromResultSet");
557       return  null;
558     }
559     return  returnEntity;
560   }
561
562   /**
563    * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
564    * wird automatisch mit dem aktuellen Datum gefuellt.
565    *
566    * @param theEntity
567    * @return der Wert des Primary-keys der eingefügten Entity
568    */
569   public String insert (Entity theEntity) throws StorageObjectException {
570     String returnId = null;
571     Connection con = null;
572     PreparedStatement pstmt = null;
573     //cache
574     invalidatePopupCache();
575     try {
576       ArrayList streamedInput = theEntity.streamedInput();
577       StringBuffer f = new StringBuffer();
578       StringBuffer v = new StringBuffer();
579       String aField, aValue;
580       boolean firstField = true;
581       // make sql-string
582       for (int i = 0; i < getFields().size(); i++) {
583         aField = (String)getFields().get(i);
584         if (!aField.equals(thePKeyName)) {
585           aValue = null;
586           // sonderfaelle
587           if (aField.equals("webdb_create")) {
588             aValue = "NOW()";
589           }
590           else {
591             if (streamedInput != null && streamedInput.contains(aField)) {
592               aValue = "?";
593             }
594             else {
595               if (theEntity.hasValueForField(aField)) {
596                 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
597                     + "'";
598               }
599             }
600           }
601           // wenn Wert gegeben, dann einbauen
602           if (aValue != null) {
603             if (firstField == false) {
604               f.append(",");
605               v.append(",");
606             }
607             else {
608               firstField = false;
609             }
610             f.append(aField);
611             v.append(aValue);
612           }
613         }
614       }         // end for
615       // insert into db
616       StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
617       String sql = sqlBuf.toString();
618       theLog.printInfo("INSERT: " + sql);
619       con = getPooledCon();
620       con.setAutoCommit(false);
621       pstmt = con.prepareStatement(sql);
622       if (streamedInput != null) {
623         for (int i = 0; i < streamedInput.size(); i++) {
624           String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
625           pstmt.setBytes(i + 1, inputString.getBytes());
626         }
627       }
628       int ret = pstmt.executeUpdate();
629       if(ret == 0){
630         //insert failed
631         return null;
632       }
633       pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
634       ResultSet rs = pstmt.executeQuery();
635       rs.next();
636       returnId = rs.getString(1);
637       theEntity.setId(returnId);
638     } catch (SQLException sqe) {
639       throwSQLException(sqe, "insert");
640     } finally {
641       try {
642         con.setAutoCommit(true);
643       } catch (Exception e) {
644         ;
645       }
646       freeConnection(con, pstmt);
647     }
648     return  returnId;
649   }
650
651   /**
652    * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
653    * wird automatisch mit dem aktuellen Datum gefuellt.
654    *
655    * @param theEntity
656    */
657   public void update (Entity theEntity) throws StorageObjectException {
658     Connection con = null;
659     PreparedStatement pstmt = null;
660     ArrayList streamedInput = theEntity.streamedInput();
661     String id = theEntity.getId();
662     String aField;
663     StringBuffer fv = new StringBuffer();
664     boolean firstField = true;
665     //cache
666     invalidatePopupCache();
667     // build sql statement
668     for (int i = 0; i < getFields().size(); i++) {
669       aField = (String)metadataFields.get(i);
670       // only normal cases
671       if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
672           aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
673         if (theEntity.hasValueForField(aField)) {
674           if (firstField == false) {
675             fv.append(", ");
676           }
677           else {
678             firstField = false;
679           }
680           fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
681         }
682       }
683     }
684     StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
685     // exceptions
686     if (metadataFields.contains("webdb_lastchange")) {
687       sql.append(",webdb_lastchange=NOW()");
688     }
689     if (streamedInput != null) {
690       for (int i = 0; i < streamedInput.size(); i++) {
691         sql.append(",").append(streamedInput.get(i)).append("=?");
692       }
693     }
694     sql.append(" where id=").append(id);
695     theLog.printInfo("UPDATE: " + sql);
696     // execute sql
697     try {
698       con = getPooledCon();
699       con.setAutoCommit(false);
700       pstmt = con.prepareStatement(sql.toString());
701       if (streamedInput != null) {
702         for (int i = 0; i < streamedInput.size(); i++) {
703           String inputString = theEntity.getValue((String)streamedInput.get(i));
704           pstmt.setBytes(i + 1, inputString.getBytes());
705         }
706       }
707       pstmt.executeUpdate();
708     } catch (SQLException sqe) {
709       throwSQLException(sqe, "update");
710     } finally {
711       try {
712         con.setAutoCommit(true);
713       } catch (Exception e) {
714         ;
715       }
716       freeConnection(con, pstmt);
717     }
718   }
719
720   /*
721    *   delete-Operator
722    *   @param id des zu loeschenden Datensatzes
723    *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
724    */
725   public boolean delete (String id) throws StorageObjectException {
726     Statement stmt = null;
727     Connection con = null;
728     String sql;
729     int res = 0;
730     // loeschen des caches
731     invalidatePopupCache();
732     sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
733         "'";
734     theLog.printInfo("DELETE " + sql);
735     try {
736       con = getPooledCon();
737       stmt = con.createStatement();
738       res = stmt.executeUpdate(sql);
739     } catch (SQLException sqe) {
740       throwSQLException(sqe, "delete");
741     } finally {
742       freeConnection(con, stmt);
743     }
744     if (cache != null) {
745       theLog.printInfo("CACHE: deleted " + id);
746       cache.remove(id);
747     }
748     return  (res > 0) ? true : false;
749   }
750
751   /* noch nicht implementiert.
752    * @return immer false
753    */
754   public boolean delete (EntityList theEntityList) {
755     invalidatePopupCache();
756     return  false;
757   }
758
759   /**
760    * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
761    * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
762    * @return null
763    */
764   public SimpleList getPopupData () throws StorageObjectException {
765     return  null;
766   }
767
768   /**
769    *  Holt Daten fuer Popups.
770    *  @param name  Name des Feldes.
771    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
772    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
773    */
774   public SimpleList getPopupData (String name, boolean hasNullValue)
775     throws StorageObjectException {
776     return  getPopupData(name, hasNullValue, null);
777   }
778
779   /**
780    *  Holt Daten fuer Popups.
781    *  @param name  Name des Feldes.
782    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
783    *  @param where  Schraenkt die Selektion der Datensaetze ein.
784    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
785    */
786   public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
787    return  getPopupData(name, hasNullValue, where, null);
788   }
789
790   /**
791    *  Holt Daten fuer Popups.
792    *  @param name  Name des Feldes.
793    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
794    *  @param where  Schraenkt die Selektion der Datensaetze ein.
795    *  @param order  Gibt ein Feld als Sortierkriterium an.
796    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
797    */
798   public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
799     // caching
800     if (hasPopupCache && popupCache != null)
801       return  popupCache;
802     SimpleList simpleList = null;
803     Connection con = null;
804     Statement stmt = null;
805     // build sql
806     StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
807                                         .append(",").append(name).append(" from ")
808                                         .append(theTable);
809     if (where != null && !(where.length() == 0))
810       sql.append(" where ").append(where);
811     sql.append(" order by ");
812     if (order != null && !(order.length() == 0))
813       sql.append(order);
814     else
815       sql.append(name);
816     // execute sql
817     try {
818       con = getPooledCon();
819     } catch (Exception e) {
820       throw new StorageObjectException(e.toString()); 
821     }
822     try {
823       stmt = con.createStatement();
824       ResultSet rs = executeSql(stmt, sql.toString());
825       if (rs != null) {
826         if (evaluatedMetaData == false)
827           get_meta_data();
828         simpleList = new SimpleList();
829         SimpleHash popupDict;
830         if (hasNullValue) {
831           popupDict = new SimpleHash();
832           popupDict.put("key", "");
833           popupDict.put("value", "--");
834           simpleList.add(popupDict);
835         }
836         while (rs.next()) {
837           popupDict = new SimpleHash();
838           popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
839           popupDict.put("value", rs.getString(2));
840           simpleList.add(popupDict);
841         }
842         rs.close();
843       }
844     } catch (Exception e) {
845       theLog.printError("getPopupData: "+e.toString());
846       throw new StorageObjectException(e.toString()); 
847     } finally {
848       freeConnection(con, stmt);
849     }
850     if (hasPopupCache) {
851       popupCache = simpleList;
852     }
853     return  simpleList;
854   }
855
856   /**
857    * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
858    * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
859    * Tabellen Verwendung finden.
860    * @return SimpleHash mit den Tabellezeilen.
861    */
862   public SimpleHash getHashData () {
863     if (hashCache == null) {
864       try {
865         hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
866             -1));
867       } catch (StorageObjectException e) {
868         theLog.printDebugInfo(e.toString());
869       }
870     }
871     return  hashCache;
872   }
873
874   /* invalidates the popupCache
875    */
876   protected void invalidatePopupCache () {
877
878     /** @todo  invalidates toooo much */
879     popupCache = null;
880     hashCache = null;
881   }
882
883   /**
884    * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
885    * @param stmt Statemnt
886    * @param sql Sql-String
887    * @return ResultSet
888    * @exception StorageObjectException
889    */
890   public ResultSet executeSql (Statement stmt, String sql)
891     throws StorageObjectException, SQLException
892   {
893     ResultSet rs;
894     long startTime = (new java.util.Date()).getTime();
895     try {
896       rs = stmt.executeQuery(sql);
897       theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
898         + sql);
899     }
900     catch (SQLException e)
901     {
902       theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
903                             - startTime) + "ms. for: "+ sql);
904       throw e;
905     }
906
907     return  rs;
908   }
909
910   /**
911    * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
912    * getimed und geloggt.
913    * @param stmt PreparedStatement mit der SQL-Anweisung
914    * @return Liefert ResultSet des Statements zurueck.
915    * @exception StorageObjectException, SQLException
916    */
917   public ResultSet executeSql (PreparedStatement stmt)
918     throws StorageObjectException, SQLException {
919
920     long startTime = (new java.util.Date()).getTime();
921     ResultSet rs = stmt.executeQuery();
922     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
923     return  rs;
924   }
925
926     /**
927    * returns the number of rows in the table
928    */
929   public int getSize(String where)
930     throws SQLException,StorageObjectException
931   {
932     long  startTime = (new java.util.Date()).getTime();
933     String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
934     //theLog.printDebugInfo("trying: "+ sql);
935     Connection con = null;
936     Statement stmt = null;
937     int result = 0;
938
939     try {
940       con = getPooledCon();
941       stmt = con.createStatement();
942       ResultSet rs = executeSql(stmt,sql);
943       while(rs.next()){
944         result = rs.getInt(1);
945       }
946     } catch (SQLException e) {
947       theLog.printError(e.toString());
948     } finally {
949       freeConnection(con,stmt);
950     }
951     theLog.printInfo(theTable + " has "+ result +" rows where " + where);
952     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
953                     + sql);
954     return result;
955   }
956
957   public int executeUpdate(Statement stmt, String sql)
958     throws StorageObjectException, SQLException
959   {
960     int rs;
961     long  startTime = (new java.util.Date()).getTime();
962     try
963     {
964       rs = stmt.executeUpdate(sql);
965       theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
966                         + sql);
967     }
968     catch (SQLException e)
969     {
970       theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() 
971                             - startTime) + "ms. for: "+ sql);
972       throw e;
973     }
974     return rs;
975   }
976
977   public int executeUpdate(String sql)
978     throws StorageObjectException, SQLException
979   {
980     int result=-1;
981     long  startTime = (new java.util.Date()).getTime();
982     Connection con=null;PreparedStatement pstmt=null;
983     try {
984       con=getPooledCon();
985       pstmt = con.prepareStatement(sql);
986       result = pstmt.executeUpdate();
987     }
988     catch (Exception e) {
989       theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
990       throw new StorageObjectException("executeUpdate failed: "+e.toString());
991     }
992     finally { freeConnection(con,pstmt); }
993     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
994                     + sql);
995     return result;
996   }
997
998   /**
999    * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1000    * @param md ResultSetMetaData
1001    * @exception StorageObjectException
1002    */
1003   private void evalMetaData (ResultSetMetaData md)
1004     throws StorageObjectException {
1005
1006     this.evaluatedMetaData = true;
1007     this.metadataFields = new ArrayList();
1008     this.metadataLabels = new ArrayList();
1009     this.metadataNotNullFields = new ArrayList();
1010     try {
1011       int numFields = md.getColumnCount();
1012       this.metadataTypes = new int[numFields];
1013       String aField;
1014       int aType;
1015       for (int i = 1; i <= numFields; i++) {
1016         aField = md.getColumnName(i);
1017         metadataFields.add(aField);
1018         metadataLabels.add(md.getColumnLabel(i));
1019         aType = md.getColumnType(i);
1020         metadataTypes[i - 1] = aType;
1021         if (aField.equals(thePKeyName)) {
1022           thePKeyType = aType;
1023         }
1024         if (md.isNullable(i) == md.columnNullable) {
1025           metadataNotNullFields.add(aField);
1026         }
1027       }
1028     } catch (SQLException e) {
1029       throwSQLException(e, "evalMetaData");
1030     }
1031   }
1032
1033   /**
1034    *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1035    *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1036    */
1037   private void get_meta_data () throws StorageObjectException {
1038     Connection con = null;
1039     PreparedStatement pstmt = null;
1040     String sql = "select * from " + theTable + " where 0=1";
1041     try {
1042       con = getPooledCon();
1043       pstmt = con.prepareStatement(sql);
1044       theLog.printInfo("METADATA: " + sql);
1045       ResultSet rs = pstmt.executeQuery();
1046       evalMetaData(rs.getMetaData());
1047       rs.close();
1048     } catch (SQLException e) {
1049       throwSQLException(e, "get_meta_data");
1050     } finally {
1051       freeConnection(con, pstmt);
1052     }
1053   }
1054
1055   
1056   public Connection getPooledCon() throws StorageObjectException {
1057     /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1058       try{
1059       Class.forName("com.codestudio.sql.PoolMan").newInstance();
1060     } catch (Exception e){
1061       throw new StorageObjectException("Could not find the PoolMan Driver"
1062                                         +e.toString());
1063     }*/
1064     Connection con = null;
1065     try{
1066       con = SQLManager.getInstance().requestConnection();
1067     } catch(SQLException e){
1068       theLog.printError("could not connect to the database "+e.toString());
1069       System.err.println("could not connect to the database "+e.toString());
1070       throw new StorageObjectException("Could not connect to the database"+
1071                                         e.toString());
1072     }
1073     return con;
1074   }
1075  
1076   public void freeConnection (Connection con, Statement stmt)
1077     throws StorageObjectException {
1078     SQLManager.getInstance().closeStatement(stmt);
1079     SQLManager.getInstance().returnConnection(con);
1080   }
1081
1082   /**
1083    * Wertet SQLException aus und wirft dannach eine StorageObjectException
1084    * @param sqe SQLException
1085    * @param wo Funktonsname, in der die SQLException geworfen wurde
1086    * @exception StorageObjectException
1087    */
1088   protected void throwSQLException (SQLException sqe, String wo)
1089     throws StorageObjectException {
1090     String state = "";
1091     String message = "";
1092     int vendor = 0;
1093     if (sqe != null) {
1094       state = sqe.getSQLState();
1095       message = sqe.getMessage();
1096       vendor = sqe.getErrorCode();
1097     }
1098     theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1099         + wo);
1100     throw  new StorageObjectException((sqe == null) ? "undefined sql exception" :
1101         sqe.toString());
1102   }
1103
1104   protected void _throwStorageObjectException (Exception e, String wo)
1105     throws StorageObjectException {
1106     if (e != null) {
1107         theLog.printError(e.toString()+ wo);
1108         throw  new StorageObjectException(wo + e.toString());
1109     } else {
1110         theLog.printError(wo);
1111         throw  new StorageObjectException(wo);
1112     }
1113
1114   }
1115
1116   /**
1117    * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach 
1118    * eine StorageObjectException
1119    * @param message Nachricht mit dem Fehler
1120    * @exception StorageObjectException
1121    */
1122   void throwStorageObjectException (String message)
1123     throws StorageObjectException {
1124     _throwStorageObjectException(null, message);
1125   }
1126
1127 }
1128
1129
1130