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