ObjectStore cache is working with StorableObjectEntities
[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                                                 if (!rs.wasNull()) {
257                                                         outValue = timestamp.toString();
258                                                 }
259                                                 break;
260                                         default:
261                                                 outValue = "<unsupported value>";
262                                                 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
263                                                                 " (" + aType + ")");
264                                 }
265                         } catch (SQLException e) {
266                                 throw  new StorageObjectException("Could not get Value out of Resultset -- "
267                                                 + e.toString());
268                         }
269                 }
270                 return  outValue;
271         }
272
273         /*
274          *   select-Operator um einen Datensatz zu bekommen.
275          *   @param id Primaerschluessel des Datensatzes.
276          *   @return liefert EntityObject des gefundenen Datensatzes oder null.
277          */
278         public Entity selectById(String id)     throws StorageObjectException
279   {
280                 if (id==null||id.equals(""))
281                         throw new StorageObjectException("id war null");
282
283     // ask object store for object
284     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
285       String uniqueId = id;
286       if ( theEntityClass.equals(StorableObjectEntity.class) )
287         uniqueId+="@"+theTable;
288       StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
289       theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
290       Entity hit = (Entity)o_store.use(search_sid);
291       if ( hit!=null ) return hit;
292     }
293
294                 Statement stmt=null;Connection con=getPooledCon();
295                 Entity returnEntity=null;
296                 try {
297                         ResultSet rs;
298                         /** @todo better prepared statement */
299                         String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
300                         stmt = con.createStatement();
301                         rs = executeSql(stmt, selectSql);
302                         if (rs != null) {
303                                 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
304                                 if (rs.next())
305                                         returnEntity = makeEntityFromResultSet(rs);
306                                 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
307                                 rs.close();
308                         }
309                         else {
310                                 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
311                         }
312                 }
313                 catch (SQLException sqe){
314                         throwSQLException(sqe,"selectById"); return null;
315                 }
316                 catch (NumberFormatException e) {
317                         theLog.printError("ID ist keine Zahl: " + id);
318                 }
319                 finally { freeConnection(con,stmt); }
320
321                 /** @todo OS: Entity should be saved in ostore */
322                 return returnEntity;
323         }
324
325
326         /**
327          *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
328          *   @param key  Datenbankfeld der Bedingung.
329          *   @param value  Wert die der key anehmen muss.
330          *   @return EntityList mit den gematchten Entities
331          */
332         public EntityList selectByFieldValue(String aField, String aValue)
333                 throws StorageObjectException
334         {
335                 return selectByFieldValue(aField, aValue, 0);
336         }
337
338         /**
339          *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
340          *   @param key  Datenbankfeld der Bedingung.
341          *   @param value  Wert die der key anehmen muss.
342          *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
343          *   @return EntityList mit den gematchten Entities
344          */
345         public EntityList selectByFieldValue(String aField, String aValue, int offset)
346                 throws StorageObjectException
347         {
348                 return selectByWhereClause(aField + "=" + aValue, offset);
349         }
350
351
352         /**
353          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
354          * Also offset wird der erste Datensatz genommen.
355          *
356          * @param wc where-Clause
357          * @return EntityList mit den gematchten Entities
358          * @exception StorageObjectException
359          */
360         public EntityList selectByWhereClause(String where)
361                 throws StorageObjectException
362         {
363                 return selectByWhereClause(where, 0);
364         }
365
366
367         /**
368          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
369          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
370          *
371          * @param wc where-Clause
372          * @param offset ab welchem Datensatz.
373          * @return EntityList mit den gematchten Entities
374          * @exception StorageObjectException
375          */
376         public EntityList selectByWhereClause(String whereClause, int offset)
377                 throws StorageObjectException
378         {
379                 return selectByWhereClause(whereClause, null, offset);
380         }
381
382
383         /**
384          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
385          * Also offset wird der erste Datensatz genommen.
386          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
387          *
388          * @param wc where-Clause
389          * @param ob orderBy-Clause
390          * @return EntityList mit den gematchten Entities
391          * @exception StorageObjectException
392          */
393
394         public EntityList selectByWhereClause(String where, String order)
395                 throws StorageObjectException {
396                 return selectByWhereClause(where, order, 0);
397         }
398
399
400         /**
401          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
402          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
403          *
404          * @param wc where-Clause
405          * @param ob orderBy-Clause
406          * @param offset ab welchem Datensatz
407          * @return EntityList mit den gematchten Entities
408          * @exception StorageObjectException
409          */
410
411         public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
412                 throws StorageObjectException {
413                 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
414         }
415
416
417         /**
418          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
419          * @param wc where-Clause
420          * @param ob orderBy-Clause
421          * @param offset ab welchem Datensatz
422          * @param limit wieviele Datensätze
423          * @return EntityList mit den gematchten Entities
424          * @exception StorageObjectException
425          */
426
427         public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
428                 throws StorageObjectException
429   {
430
431     // check o_store for entitylist
432     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
433       StoreIdentifier search_sid =
434         new StoreIdentifier( theEntityClass,
435                              StoreContainerType.STOC_TYPE_ENTITYLIST,
436                              StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
437       EntityList hit = (EntityList)o_store.use(search_sid);
438       if ( hit!=null ) {
439         theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
440         return hit;
441       }
442     }
443
444                 // local
445                 EntityList    theReturnList=null;
446                 Connection    con=null; Statement stmt=null;
447                 ResultSet     rs;
448                 int           offsetCount = 0, count=0;
449
450                 // build sql-statement
451
452                 /** @todo count sql string should only be assembled if we really count
453                  *  see below at the end of method //rk */
454
455                 if (wc != null && wc.length() == 0) {
456                         wc = null;
457                 }
458                 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
459                 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
460                 if (wc != null) {
461                         selectSql.append(" where ").append(wc);
462                         countSql.append(" where ").append(wc);
463                 }
464                 if (ob != null && !(ob.length() == 0)) {
465                         selectSql.append(" order by ").append(ob);
466                 }
467                 if (theAdaptor.hasLimit()) {
468                         if (limit > -1 && offset > -1) {
469                                 selectSql.append(" limit ");
470                                 if (theAdaptor.reverseLimit()) {
471                                         selectSql.append(limit).append(",").append(offset);
472                                 }
473                                 else {
474                                         selectSql.append(offset).append(",").append(limit);
475                                 }
476                         }
477                 }
478
479                 // execute sql
480                 try {
481                         con = getPooledCon();
482                         stmt = con.createStatement();
483
484                         // selecting...
485                         rs = executeSql(stmt, selectSql.toString());
486                         if (rs != null) {
487                                 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
488
489                                 theReturnList = new EntityList();
490                                 Entity theResultEntity;
491                                 while (rs.next()) {
492                                         theResultEntity = makeEntityFromResultSet(rs);
493                                         theReturnList.add(theResultEntity);
494                                         offsetCount++;
495                                 }
496                                 rs.close();
497                         }
498
499                         // making entitylist infos
500                         if (!(theAdaptor.hasLimit())) count = offsetCount;
501
502                         if (theReturnList != null) {
503                                 // now we decide if we have to know an overall count...
504                                 count=offsetCount;
505                                 if (limit > -1 && offset > -1) {
506                                         if (offsetCount==limit) {
507                                                 /** @todo counting should be deffered to entitylist
508                                                  *  getSize() should be used */
509                                                 rs = executeSql(stmt, countSql.toString());
510                                                 if (rs != null) {
511                                                         if ( rs.next() ) count = rs.getInt(1);
512                                                         rs.close();
513                                                 }
514                                                 else theLog.printError("Could not count: " + countSql);
515                                         }
516                                 }
517                                 theReturnList.setCount(count);
518                                 theReturnList.setOffset(offset);
519                                 theReturnList.setWhere(wc);
520                                 theReturnList.setOrder(ob);
521         theReturnList.setStorage(this);
522         theReturnList.setLimit(limit);
523                                 if ( offset >= limit )
524                                         theReturnList.setPrevBatch(offset - limit);
525                                 if ( offset+offsetCount < count )
526                                         theReturnList.setNextBatch(offset + limit);
527         if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
528           StoreIdentifier sid=theReturnList.getStoreIdentifier();
529           theLog.printDebugInfo("CACHE (add): " + sid.toString());
530           o_store.add(sid);
531         }
532                         }
533                 }
534                 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
535                 finally { freeConnection(con, stmt); }
536
537                 return  theReturnList;
538         }
539
540
541         /**
542          *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
543          *
544          *  @param rs Das ResultSetObjekt.
545          *  @return Entity Die Entity.
546          */
547         private Entity makeEntityFromResultSet (ResultSet rs)
548                 throws StorageObjectException
549         {
550                 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
551                 HashMap theResultHash = new HashMap();
552                 String theResult = null;
553                 int theType;
554                 Entity returnEntity = null;
555                 try {
556                         int size = metadataFields.size();
557                         for (int i = 0; i < size; i++) {
558                                 // alle durchlaufen bis nix mehr da
559                                 theType = metadataTypes[i];
560                                 if (theType == java.sql.Types.LONGVARBINARY) {
561                                         InputStream us = rs.getAsciiStream(i + 1);
562                                         if (us != null) {
563                                                 InputStreamReader is = new InputStreamReader(us);
564                                                 char[] data = new char[32768];
565                                                 StringBuffer theResultString = new StringBuffer();
566                                                 int len;
567                                                 while ((len = is.read(data)) > 0) {
568                                                         theResultString.append(data, 0, len);
569                                                 }
570                                                 is.close();
571                                                 theResult = theResultString.toString();
572                                         }
573                                         else {
574                                                 theResult = null;
575                                         }
576                                 }
577                                 else {
578                                         theResult = getValueAsString(rs, (i + 1), theType);
579                                 }
580                                 if (theResult != null) {
581                                         theResultHash.put(metadataFields.get(i), theResult);
582                                 }
583                         }
584       if (theEntityClass != null) {
585         returnEntity = (Entity)theEntityClass.newInstance();
586         returnEntity.setValues(theResultHash);
587         returnEntity.setStorage(myselfDatabase);
588         if ( returnEntity instanceof StorableObject ) {
589           theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
590           o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
591         }
592       } else {
593         throwStorageObjectException("Internal Error: theEntityClass not set!");
594       }
595                 } catch (IllegalAccessException e) {
596                         throwStorageObjectException("Kein Zugriff! -- " + e.toString());
597                 } catch (IOException e) {
598                         throwStorageObjectException("IOException! -- " + e.toString());
599                 } catch (InstantiationException e) {
600                         throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
601                 } catch (SQLException sqe) {
602                         throwSQLException(sqe, "makeEntityFromResultSet");
603                         return  null;
604                 }
605                 return  returnEntity;
606         }
607
608         /**
609          * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
610          * wird automatisch mit dem aktuellen Datum gefuellt.
611          *
612          * @param theEntity
613          * @return der Wert des Primary-keys der eingefügten Entity
614          */
615         public String insert (Entity theEntity) throws StorageObjectException {
616                 //cache
617                 invalidatePopupCache();
618
619     // invalidating all EntityLists corresponding with theEntityClass
620     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
621       StoreContainerType stoc_type =
622         StoreContainerType.valueOf( theEntityClass,
623                                     StoreContainerType.STOC_TYPE_ENTITYLIST);
624       o_store.invalidate(stoc_type);
625     }
626
627                 String returnId = null;
628                 Connection con = null; PreparedStatement pstmt = null;
629
630     try {
631                         ArrayList streamedInput = theEntity.streamedInput();
632                         StringBuffer f = new StringBuffer();
633                         StringBuffer v = new StringBuffer();
634                         String aField, aValue;
635                         boolean firstField = true;
636                         // make sql-string
637                         for (int i = 0; i < getFields().size(); i++) {
638                                 aField = (String)getFields().get(i);
639                                 if (!aField.equals(thePKeyName)) {
640                                         aValue = null;
641                                         // sonderfaelle
642                                         if (aField.equals("webdb_create")) {
643                                                 aValue = "NOW()";
644                                         }
645                                         else {
646                                                 if (streamedInput != null && streamedInput.contains(aField)) {
647                                                         aValue = "?";
648                                                 }
649                                                 else {
650                                                         if (theEntity.hasValueForField(aField)) {
651                                                                 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
652                                                                                 + "'";
653                                                         }
654                                                 }
655                                         }
656                                         // wenn Wert gegeben, dann einbauen
657                                         if (aValue != null) {
658                                                 if (firstField == false) {
659                                                         f.append(",");
660                                                         v.append(",");
661                                                 }
662                                                 else {
663                                                         firstField = false;
664                                                 }
665                                                 f.append(aField);
666                                                 v.append(aValue);
667                                         }
668                                 }
669                         }         // end for
670                         // insert into db
671                         StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
672                         String sql = sqlBuf.toString();
673                         theLog.printInfo("INSERT: " + sql);
674                         con = getPooledCon();
675                         con.setAutoCommit(false);
676                         pstmt = con.prepareStatement(sql);
677                         if (streamedInput != null) {
678                                 for (int i = 0; i < streamedInput.size(); i++) {
679                                         String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
680                                         pstmt.setBytes(i + 1, inputString.getBytes());
681                                 }
682                         }
683                         int ret = pstmt.executeUpdate();
684                         if(ret == 0){
685                                 //insert failed
686                                 return null;
687                         }
688                         pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
689                         ResultSet rs = pstmt.executeQuery();
690                         rs.next();
691                         returnId = rs.getString(1);
692                         theEntity.setId(returnId);
693                 } catch (SQLException sqe) {
694                         throwSQLException(sqe, "insert");
695                 } finally {
696                         try {
697                                 con.setAutoCommit(true);
698                         } catch (Exception e) {
699                                 ;
700                         }
701                         freeConnection(con, pstmt);
702                 }
703     /** @todo store entity in o_store */
704                 return  returnId;
705         }
706
707         /**
708          * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
709          * wird automatisch mit dem aktuellen Datum gefuellt.
710          *
711          * @param theEntity
712          */
713         public void update (Entity theEntity) throws StorageObjectException
714   {
715                 Connection con = null; PreparedStatement pstmt = null;
716                 /** @todo this is stupid: why do we prepare statement, when we
717                  *  throw it away afterwards. should be regular statement
718                  *  update/insert could better be one routine called save()
719                  *  that chooses to either insert or update depending if we
720                  *  have a primary key in the entity. i don't know if we
721                  *  still need the streamed input fields. // rk  */
722
723                 /** @todo extension: check if Entity did change, otherwise we don't need
724      *  the roundtrip to the database */
725
726                 /** invalidating corresponding entitylists in o_store*/
727     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
728       StoreContainerType stoc_type =
729         StoreContainerType.valueOf( theEntityClass,
730                                     StoreContainerType.STOC_TYPE_ENTITYLIST);
731       o_store.invalidate(stoc_type);
732     }
733
734                 ArrayList streamedInput = theEntity.streamedInput();
735                 String id = theEntity.getId();
736                 String aField;
737                 StringBuffer fv = new StringBuffer();
738                 boolean firstField = true;
739                 //cache
740                 invalidatePopupCache();
741                 // build sql statement
742                 for (int i = 0; i < getFields().size(); i++) {
743                         aField = (String)metadataFields.get(i);
744                         // only normal cases
745                         if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
746                                         aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
747                                 if (theEntity.hasValueForField(aField)) {
748                                         if (firstField == false) {
749                                                 fv.append(", ");
750                                         }
751                                         else {
752                                                 firstField = false;
753                                         }
754                                         fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
755                                 }
756                         }
757                 }
758                 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
759                 // exceptions
760                 if (metadataFields.contains("webdb_lastchange")) {
761                         sql.append(",webdb_lastchange=NOW()");
762                 }
763                 if (streamedInput != null) {
764                         for (int i = 0; i < streamedInput.size(); i++) {
765                                 sql.append(",").append(streamedInput.get(i)).append("=?");
766                         }
767                 }
768                 sql.append(" where id=").append(id);
769                 theLog.printInfo("UPDATE: " + sql);
770                 // execute sql
771                 try {
772                         con = getPooledCon();
773                         con.setAutoCommit(false);
774                         pstmt = con.prepareStatement(sql.toString());
775                         if (streamedInput != null) {
776                                 for (int i = 0; i < streamedInput.size(); i++) {
777                                         String inputString = theEntity.getValue((String)streamedInput.get(i));
778                                         pstmt.setBytes(i + 1, inputString.getBytes());
779                                 }
780                         }
781                         pstmt.executeUpdate();
782                 } catch (SQLException sqe) {
783                         throwSQLException(sqe, "update");
784                 } finally {
785                         try {
786                                 con.setAutoCommit(true);
787                         } catch (Exception e) {
788                                 ;
789                         }
790                         freeConnection(con, pstmt);
791                 }
792         }
793
794         /*
795          *   delete-Operator
796          *   @param id des zu loeschenden Datensatzes
797          *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
798          */
799         public boolean delete (String id) throws StorageObjectException {
800
801                 invalidatePopupCache();
802     // ostore send notification
803     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
804       String uniqueId = id;
805       if ( theEntityClass.equals(StorableObjectEntity.class) )
806         uniqueId+="@"+theTable;
807                         theLog.printInfo("CACHE: (del) " + id);
808                         StoreIdentifier search_sid =
809         new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
810       o_store.invalidate(search_sid);
811                 }
812
813                 /** @todo could be prepared Statement */
814                 Statement stmt = null; Connection con = null;
815                 int res = 0;
816                 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
817                 theLog.printInfo("DELETE " + sql);
818                 try {
819                         con = getPooledCon(); stmt = con.createStatement();
820                         res = stmt.executeUpdate(sql);
821                 }
822     catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
823     finally { freeConnection(con, stmt); }
824
825                 return  (res > 0) ? true : false;
826         }
827
828         /* noch nicht implementiert.
829          * @return immer false
830          */
831         public boolean delete (EntityList theEntityList) {
832                 invalidatePopupCache();
833                 return  false;
834         }
835
836         /**
837          * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
838          * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
839          * @return null
840          */
841         public SimpleList getPopupData () throws StorageObjectException {
842                 return  null;
843         }
844
845         /**
846          *  Holt Daten fuer Popups.
847          *  @param name  Name des Feldes.
848          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
849          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
850          */
851         public SimpleList getPopupData (String name, boolean hasNullValue)
852                 throws StorageObjectException {
853                 return  getPopupData(name, hasNullValue, null);
854         }
855
856         /**
857          *  Holt Daten fuer Popups.
858          *  @param name  Name des Feldes.
859          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
860          *  @param where  Schraenkt die Selektion der Datensaetze ein.
861          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
862          */
863         public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
864          return  getPopupData(name, hasNullValue, where, null);
865         }
866
867         /**
868          *  Holt Daten fuer Popups.
869          *  @param name  Name des Feldes.
870          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
871          *  @param where  Schraenkt die Selektion der Datensaetze ein.
872          *  @param order  Gibt ein Feld als Sortierkriterium an.
873          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
874          */
875         public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
876                 // caching
877                 if (hasPopupCache && popupCache != null)
878                         return  popupCache;
879                 SimpleList simpleList = null;
880                 Connection con = null;
881                 Statement stmt = null;
882                 // build sql
883                 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
884                                                                                                                                                                 .append(",").append(name).append(" from ")
885                                                                                                                                                                 .append(theTable);
886                 if (where != null && !(where.length() == 0))
887                         sql.append(" where ").append(where);
888                 sql.append(" order by ");
889                 if (order != null && !(order.length() == 0))
890                         sql.append(order);
891                 else
892                         sql.append(name);
893                 // execute sql
894                 try {
895                         con = getPooledCon();
896                 } catch (Exception e) {
897                         throw new StorageObjectException(e.toString());
898                 }
899                 try {
900                         stmt = con.createStatement();
901                         ResultSet rs = executeSql(stmt, sql.toString());
902
903                         if (rs != null) {
904                                 if (!evaluatedMetaData) get_meta_data();
905                                 simpleList = new SimpleList();
906                                 // if popup has null-selector
907                                 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
908
909                                 SimpleHash popupDict;
910                                 while (rs.next()) {
911                                         popupDict = new SimpleHash();
912                                         popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
913                                         popupDict.put("value", rs.getString(2));
914                                         simpleList.add(popupDict);
915                                 }
916                                 rs.close();
917                         }
918                 } catch (Exception e) {
919                         theLog.printError("getPopupData: "+e.toString());
920                         throw new StorageObjectException(e.toString());
921                 } finally {
922                         freeConnection(con, stmt);
923                 }
924
925                 if (hasPopupCache) popupCache = simpleList;
926                 return  simpleList;
927         }
928
929         /**
930          * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
931          * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
932          * Tabellen Verwendung finden.
933          * @return SimpleHash mit den Tabellezeilen.
934          */
935         public SimpleHash getHashData () {
936                 /** @todo dangerous! this should have a flag to be enabled, otherwise
937                  *  very big Hashes could be returned */
938                 if (hashCache == null) {
939                         try {
940                                 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
941                                                 -1));
942                         } catch (StorageObjectException e) {
943                                 theLog.printDebugInfo(e.toString());
944                         }
945                 }
946                 return  hashCache;
947         }
948
949         /* invalidates the popupCache
950          */
951         protected void invalidatePopupCache () {
952                 /** @todo  invalidates toooo much */
953                 popupCache = null;
954                 hashCache = null;
955         }
956
957         /**
958          * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
959          * @param stmt Statemnt
960          * @param sql Sql-String
961          * @return ResultSet
962          * @exception StorageObjectException
963          */
964         public ResultSet executeSql (Statement stmt, String sql)
965                 throws StorageObjectException, SQLException
966         {
967                 long startTime = System.currentTimeMillis();
968                 ResultSet rs;
969                 try {
970                         rs = stmt.executeQuery(sql);
971                         theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
972                                 + sql);
973                 }
974                 catch (SQLException e)
975                 {
976                         theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
977                                                                                                                 - startTime) + "ms. for: "+ sql);
978                         throw e;
979                 }
980
981                 return  rs;
982         }
983
984         /**
985          * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
986          * getimed und geloggt.
987          * @param stmt PreparedStatement mit der SQL-Anweisung
988          * @return Liefert ResultSet des Statements zurueck.
989          * @exception StorageObjectException, SQLException
990          */
991         public ResultSet executeSql (PreparedStatement stmt)
992                 throws StorageObjectException, SQLException {
993
994                 long startTime = (new java.util.Date()).getTime();
995                 ResultSet rs = stmt.executeQuery();
996                 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
997                 return  rs;
998         }
999
1000                 /**
1001          * returns the number of rows in the table
1002          */
1003         public int getSize(String where)
1004                 throws SQLException,StorageObjectException
1005         {
1006                 long  startTime = System.currentTimeMillis();
1007                 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
1008                 Connection con = null;
1009                 Statement stmt = null;
1010                 int result = 0;
1011
1012                 try {
1013                         con = getPooledCon();
1014                         stmt = con.createStatement();
1015                         ResultSet rs = executeSql(stmt,sql);
1016                         while(rs.next()){
1017                                 result = rs.getInt(1);
1018                         }
1019                 } catch (SQLException e) {
1020                         theLog.printError(e.toString());
1021                 } finally {
1022                         freeConnection(con,stmt);
1023                 }
1024                 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1025                 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1026                                                                                 + sql);
1027                 return result;
1028         }
1029
1030         public int executeUpdate(Statement stmt, String sql)
1031                 throws StorageObjectException, SQLException
1032         {
1033                 int rs;
1034                 long  startTime = (new java.util.Date()).getTime();
1035                 try
1036                 {
1037                         rs = stmt.executeUpdate(sql);
1038                         theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1039                                                                                                 + sql);
1040                 }
1041                 catch (SQLException e)
1042                 {
1043                         theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1044                                                                                                                 - startTime) + "ms. for: "+ sql);
1045                         throw e;
1046                 }
1047                 return rs;
1048         }
1049
1050         public int executeUpdate(String sql)
1051                 throws StorageObjectException, SQLException
1052         {
1053                 int result=-1;
1054                 long  startTime = (new java.util.Date()).getTime();
1055                 Connection con=null;PreparedStatement pstmt=null;
1056                 try {
1057                         con=getPooledCon();
1058                         pstmt = con.prepareStatement(sql);
1059                         result = pstmt.executeUpdate();
1060                 }
1061                 catch (Exception e) {
1062                         theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1063                         throw new StorageObjectException("executeUpdate failed: "+e.toString());
1064                 }
1065                 finally { freeConnection(con,pstmt); }
1066                 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1067                                                                                 + sql);
1068                 return result;
1069         }
1070
1071         /**
1072          * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1073          * @param md ResultSetMetaData
1074          * @exception StorageObjectException
1075          */
1076         private void evalMetaData (ResultSetMetaData md)
1077                 throws StorageObjectException {
1078
1079                 this.evaluatedMetaData = true;
1080                 this.metadataFields = new ArrayList();
1081                 this.metadataLabels = new ArrayList();
1082                 this.metadataNotNullFields = new ArrayList();
1083                 try {
1084                         int numFields = md.getColumnCount();
1085                         this.metadataTypes = new int[numFields];
1086                         String aField;
1087                         int aType;
1088                         for (int i = 1; i <= numFields; i++) {
1089                                 aField = md.getColumnName(i);
1090                                 metadataFields.add(aField);
1091                                 metadataLabels.add(md.getColumnLabel(i));
1092                                 aType = md.getColumnType(i);
1093                                 metadataTypes[i - 1] = aType;
1094                                 if (aField.equals(thePKeyName)) {
1095                                         thePKeyType = aType; thePKeyIndex = i;
1096                                 }
1097                                 if (md.isNullable(i) == md.columnNullable) {
1098                                         metadataNotNullFields.add(aField);
1099                                 }
1100                         }
1101                 } catch (SQLException e) {
1102                         throwSQLException(e, "evalMetaData");
1103                 }
1104         }
1105
1106         /**
1107          *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1108          *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1109          */
1110         private void get_meta_data () throws StorageObjectException {
1111                 Connection con = null;
1112                 PreparedStatement pstmt = null;
1113                 String sql = "select * from " + theTable + " where 0=1";
1114                 try {
1115                         con = getPooledCon();
1116                         pstmt = con.prepareStatement(sql);
1117                         theLog.printInfo("METADATA: " + sql);
1118                         ResultSet rs = pstmt.executeQuery();
1119                         evalMetaData(rs.getMetaData());
1120                         rs.close();
1121                 } catch (SQLException e) {
1122                         throwSQLException(e, "get_meta_data");
1123                 } finally {
1124                         freeConnection(con, pstmt);
1125                 }
1126         }
1127
1128
1129         public Connection getPooledCon() throws StorageObjectException {
1130                 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1131                         try{
1132                         Class.forName("com.codestudio.sql.PoolMan").newInstance();
1133                 } catch (Exception e){
1134                         throw new StorageObjectException("Could not find the PoolMan Driver"
1135                                                                                                                                                                 +e.toString());
1136                 }*/
1137                 Connection con = null;
1138                 try{
1139                         con = SQLManager.getInstance().requestConnection();
1140                 } catch(SQLException e){
1141                         theLog.printError("could not connect to the database "+e.toString());
1142                         System.err.println("could not connect to the database "+e.toString());
1143                         throw new StorageObjectException("Could not connect to the database"+
1144                                                                                                                                                                 e.toString());
1145                 }
1146                 return con;
1147         }
1148
1149         public void freeConnection (Connection con, Statement stmt)
1150                 throws StorageObjectException {
1151                 SQLManager.getInstance().closeStatement(stmt);
1152                 SQLManager.getInstance().returnConnection(con);
1153         }
1154
1155         /**
1156          * Wertet SQLException aus und wirft dannach eine StorageObjectException
1157          * @param sqe SQLException
1158          * @param wo Funktonsname, in der die SQLException geworfen wurde
1159          * @exception StorageObjectException
1160          */
1161         protected void throwSQLException (SQLException sqe, String wo)
1162                 throws StorageObjectException {
1163                 String state = "";
1164                 String message = "";
1165                 int vendor = 0;
1166                 if (sqe != null) {
1167                         state = sqe.getSQLState();
1168                         message = sqe.getMessage();
1169                         vendor = sqe.getErrorCode();
1170                 }
1171                 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1172                                 + wo);
1173                 throw  new StorageObjectException((sqe == null) ? "undefined sql exception" :
1174                                 sqe.toString());
1175         }
1176
1177         protected void _throwStorageObjectException (Exception e, String wo)
1178                 throws StorageObjectException {
1179                 if (e != null) {
1180                                 theLog.printError(e.toString()+ wo);
1181                                 throw  new StorageObjectException(wo + e.toString());
1182                 } else {
1183                                 theLog.printError(wo);
1184                                 throw  new StorageObjectException(wo);
1185                 }
1186
1187         }
1188
1189         /**
1190          * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1191          * eine StorageObjectException
1192          * @param message Nachricht mit dem Fehler
1193          * @exception StorageObjectException
1194          */
1195         void throwStorageObjectException (String message)
1196                 throws StorageObjectException {
1197                 _throwStorageObjectException(null, message);
1198         }
1199
1200 }
1201
1202
1203