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