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