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