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