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