o_store fixx
[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  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mir.storage;
31
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.sql.Connection;
35 import java.sql.PreparedStatement;
36 import java.sql.ResultSet;
37 import java.sql.ResultSetMetaData;
38 import java.sql.SQLException;
39 import java.sql.Statement;
40 import java.sql.Timestamp;
41 import java.text.ParseException;
42 import java.text.SimpleDateFormat;
43 import java.util.ArrayList;
44 import java.util.Calendar;
45 import java.util.GregorianCalendar;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.TimeZone;
51 import java.util.Vector;
52
53 import mir.config.MirPropertiesConfiguration;
54 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
55 import mir.entity.Entity;
56 import mir.entity.EntityList;
57 import mir.entity.StorableObjectEntity;
58 import mir.log.LoggerWrapper;
59 import mir.misc.StringUtil;
60 import mir.storage.store.ObjectStore;
61 import mir.storage.store.StorableObject;
62 import mir.storage.store.StoreContainerType;
63 import mir.storage.store.StoreIdentifier;
64 import mir.storage.store.StoreUtil;
65 import mir.util.JDBCStringRoutines;
66
67 import com.codestudio.util.SQLManager;
68
69
70 /**
71  * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
72  * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
73  * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
74  * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
75  * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
76  * Datenbank erfolgt.
77  *
78  * @version $Id: Database.java,v 1.44.2.17 2003/11/27 20:45:03 rk Exp $
79  * @author rk
80  *
81  */
82 public class Database implements StorageObject {
83   private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
84   private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
85
86
87   private static Map POPUP_EMPTYLINE = new HashMap();
88   protected static final ObjectStore o_store = ObjectStore.getInstance();
89   private static final int _millisPerHour = 60 * 60 * 1000;
90   private static final int _millisPerMinute = 60 * 1000;
91
92   static {
93     // always same object saves a little space
94     POPUP_EMPTYLINE.put("key", "");
95     POPUP_EMPTYLINE.put("value", "--");
96   }
97
98   protected LoggerWrapper logger;
99   protected MirPropertiesConfiguration configuration;
100   protected String theTable;
101   protected String theCoreTable = null;
102   protected String thePKeyName = "id";
103   protected int thePKeyType;
104   protected int thePKeyIndex;
105   protected boolean evaluatedMetaData = false;
106   protected ArrayList metadataFields;
107   protected ArrayList metadataLabels;
108   protected ArrayList metadataNotNullFields;
109   protected int[] metadataTypes;
110   protected Class theEntityClass;
111   protected List popupCache = null;
112   protected boolean hasPopupCache = false;
113   protected Map hashCache = null;
114   protected boolean hasTimestamp = true;
115   private String database_driver;
116   private String database_url;
117   private int defaultLimit;
118
119   TimeZone timezone;
120   SimpleDateFormat internalDateFormat;
121   SimpleDateFormat userInputDateFormat;
122 /*
123   private SimpleDateFormat _dateFormatterOut;
124   private SimpleDateFormat _dateFormatterIn;
125   _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
126   _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");
127 */
128
129   /**
130    * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
131    * Aus diesem file werden <code>Database.Logfile</code>,
132    * <code>Database.Username</code>,<code>Database.Password</code>,
133    * <code>Database.Host</code> und <code>Database.Adaptor</code>
134    * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
135    * erzeugt.
136    *
137    * @param   String confFilename Dateiname der Konfigurationsdatei
138    */
139   public Database() throws StorageObjectFailure {
140     try {
141       configuration = MirPropertiesConfiguration.instance();
142     }
143     catch (PropertiesConfigExc e) {
144       throw new StorageObjectFailure(e);
145     }
146     logger = new LoggerWrapper("Database");
147     timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
148     internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
149     internalDateFormat.setTimeZone(timezone);
150
151     userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
152     userInputDateFormat.setTimeZone(timezone);
153
154
155     String theAdaptorName = configuration.getString("Database.Adaptor");
156     defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
157
158     try {
159       theEntityClass = GENERIC_ENTITY_CLASS;
160     }
161     catch (Throwable e) {
162       logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
163       throw new StorageObjectFailure("Error in Database() constructor.", e);
164     }
165   }
166
167   /**
168    * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
169    * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
170    * wird eine mir.entity.GenericEntity erzeugt.
171    *
172    * @return Class-Objekt der Entity
173    */
174   public java.lang.Class getEntityClass() {
175     return theEntityClass;
176   }
177
178   /**
179    * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
180    * wieviel Datens?tze per Default selektiert werden.
181    *
182    * @return Standard-Anzahl der Datens?tze
183    */
184   public int getLimit() {
185     return defaultLimit;
186   }
187
188   /**
189    * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
190    * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
191    * @return Name des Primary-Keys
192    */
193   public String getIdName() {
194     return thePKeyName;
195   }
196
197   /**
198    * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
199    *
200    * @return Name der Tabelle
201    */
202   public String getTableName() {
203     return theTable;
204   }
205
206   /*
207   *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
208   *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
209   *   wird.
210   *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
211   *    the Table
212    */
213   public String getCoreTable() {
214     if (theCoreTable != null) {
215       return theCoreTable;
216     }
217     else {
218       return theTable;
219     }
220   }
221
222   /**
223    * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
224    * @return int-Array mit den Typen der Felder
225    * @exception StorageObjectException
226    */
227   public int[] getTypes() throws StorageObjectFailure {
228     if (metadataTypes == null) {
229       get_meta_data();
230     }
231
232     return metadataTypes;
233   }
234
235   /**
236    * Liefert eine Liste der Labels der Tabellenfelder
237    * @return ArrayListe mit Labeln
238    * @exception StorageObjectException
239    */
240   public List getLabels() throws StorageObjectFailure {
241     if (metadataLabels == null) {
242       get_meta_data();
243     }
244
245     return metadataLabels;
246   }
247
248   /**
249    * Liefert eine Liste der Felder der Tabelle
250    * @return ArrayList mit Feldern
251    * @exception StorageObjectException
252    */
253   public List getFields() throws StorageObjectFailure {
254     if (metadataFields == null) {
255       get_meta_data();
256     }
257
258     return metadataFields;
259   }
260
261   /**
262    *   Gets value out of ResultSet according to type and converts to String
263    *   @param rs  ResultSet.
264    *   @param aType  a type from java.sql.Types.*
265    *   @param index  index in ResultSet
266    *   @return returns the value as String. If no conversion is possible
267    *                             /unsupported value/ is returned
268    */
269   private String getValueAsString(ResultSet rs, int valueIndex, int aType)
270     throws StorageObjectFailure {
271     String outValue = null;
272
273     if (rs != null) {
274       try {
275         switch (aType) {
276           case java.sql.Types.BIT:
277             outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
278
279             break;
280
281           case java.sql.Types.INTEGER:
282           case java.sql.Types.SMALLINT:
283           case java.sql.Types.TINYINT:
284           case java.sql.Types.BIGINT:
285
286             int out = rs.getInt(valueIndex);
287
288             if (!rs.wasNull()) {
289               outValue = new Integer(out).toString();
290             }
291
292             break;
293
294           case java.sql.Types.NUMERIC:
295
296             /** @todo Numeric can be float or double depending upon
297              *  metadata.getScale() / especially with oracle */
298             long outl = rs.getLong(valueIndex);
299
300             if (!rs.wasNull()) {
301               outValue = new Long(outl).toString();
302             }
303
304             break;
305
306           case java.sql.Types.REAL:
307
308             float tempf = rs.getFloat(valueIndex);
309
310             if (!rs.wasNull()) {
311               tempf *= 10;
312               tempf += 0.5;
313
314               int tempf_int = (int) tempf;
315               tempf = (float) tempf_int;
316               tempf /= 10;
317               outValue = "" + tempf;
318               outValue = outValue.replace('.', ',');
319             }
320
321             break;
322
323           case java.sql.Types.DOUBLE:
324
325             double tempd = rs.getDouble(valueIndex);
326
327             if (!rs.wasNull()) {
328               tempd *= 10;
329               tempd += 0.5;
330
331               int tempd_int = (int) tempd;
332               tempd = (double) tempd_int;
333               tempd /= 10;
334               outValue = "" + tempd;
335               outValue = outValue.replace('.', ',');
336             }
337
338             break;
339
340           case java.sql.Types.CHAR:
341           case java.sql.Types.VARCHAR:
342           case java.sql.Types.LONGVARCHAR:
343             outValue = rs.getString(valueIndex);
344
345             break;
346
347           case java.sql.Types.LONGVARBINARY:
348             outValue = rs.getString(valueIndex);
349
350             break;
351
352           case java.sql.Types.TIMESTAMP:
353
354             // it's important to use Timestamp here as getting it
355             // as a string is undefined and is only there for debugging
356             // according to the API. we can make it a string through formatting.
357             // -mh
358             Timestamp timestamp = (rs.getTimestamp(valueIndex));
359
360             if (!rs.wasNull()) {
361               java.util.Date date = new java.util.Date(timestamp.getTime());
362
363               Calendar calendar = new GregorianCalendar();
364               calendar.setTime(date);
365               calendar.setTimeZone(timezone);
366               outValue = internalDateFormat.format(date);
367
368               int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
369               String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
370
371               if (offset<0)
372                 outValue = outValue + "-";
373               else
374                 outValue = outValue + "+";
375               outValue = outValue + tzOffset;
376             }
377
378             break;
379
380           default:
381             outValue = "<unsupported value>";
382             logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
383         }
384       } catch (SQLException e) {
385         throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
386           e);
387       }
388     }
389
390     return outValue;
391   }
392
393   /**
394    *   select-Operator um einen Datensatz zu bekommen.
395    *   @param id Primaerschluessel des Datensatzes.
396    *   @return liefert EntityObject des gefundenen Datensatzes oder null.
397    */
398   public Entity selectById(String id) throws StorageObjectExc {
399     if ((id == null) || id.equals("")) {
400       throw new StorageObjectExc("Database.selectById: Missing id");
401     }
402
403     // ask object store for object
404     if (StoreUtil.extendsStorableEntity(theEntityClass)) {
405       String uniqueId = id;
406
407       if (theEntityClass.equals(StorableObjectEntity.class)) {
408         uniqueId += ("@" + theTable);
409       }
410
411       StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
412       logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
413
414       Entity hit = (Entity) o_store.use(search_sid);
415
416       if (hit != null) {
417         return hit;
418       }
419     }
420
421     Statement stmt = null;
422     Connection con = getPooledCon();
423     Entity returnEntity = null;
424
425     try {
426       ResultSet rs;
427
428       /** @todo better prepared statement */
429       String selectSql =
430         "select * from " + theTable + " where " + thePKeyName + "=" + id;
431       stmt = con.createStatement();
432       rs = executeSql(stmt, selectSql);
433
434       if (rs != null) {
435         if (evaluatedMetaData == false) {
436           evalMetaData(rs.getMetaData());
437         }
438
439         if (rs.next()) {
440           returnEntity = makeEntityFromResultSet(rs);
441         }
442         else {
443           logger.debug("No data for id: " + id + " in table " + theTable);
444         }
445
446         rs.close();
447       }
448       else {
449         logger.debug("No Data for Id " + id + " in Table " + theTable);
450       }
451     }
452     catch (SQLException sqe) {
453       throwSQLException(sqe, "selectById");
454       return null;
455     }
456     catch (NumberFormatException e) {
457       logger.error("ID is no number: " + id);
458     }
459     finally {
460       freeConnection(con, stmt);
461     }
462
463     return returnEntity;
464   }
465
466   /**
467    * This method makes it possible to make selects across multiple tables
468    * 
469    * @param mainTablePrefix prefix for the mainTable
470    * @param extraTables a vector of tables for relational select
471    * @param aWhereClause whereClause
472    * @return EntityList of selected Objects
473    * @throws StorageObjectFailure
474    */
475
476   public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, 
477                                                 List extraTables, String aWhereClause )
478    throws StorageObjectFailure {
479         return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, defaultLimit);
480   }
481
482   /**
483    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
484    *   @param key  Datenbankfeld der Bedingung.
485    *   @param value  Wert die der key anehmen muss.
486    *   @return EntityList mit den gematchten Entities
487    */
488   public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
489     return selectByFieldValue(aField, aValue, 0);
490   }
491
492   /**
493    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
494    *   @param key  Datenbankfeld der Bedingung.
495    *   @param value  Wert die der key anehmen muss.
496    *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
497    *   @return EntityList mit den gematchten Entities
498    */
499   public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
500     return selectByWhereClause(aField + "=" + aValue, offset);
501   }
502
503   /**
504    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
505    * Also offset wird der erste Datensatz genommen.
506    *
507    * @param wc where-Clause
508    * @return EntityList mit den gematchten Entities
509    * @exception StorageObjectException
510    */
511   public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
512     return selectByWhereClause(where, 0);
513   }
514
515   /**
516    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
517    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
518    *
519    * @param wc where-Clause
520    * @param offset ab welchem Datensatz.
521    * @return EntityList mit den gematchten Entities
522    * @exception StorageObjectException
523    */
524   public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
525     return selectByWhereClause(whereClause, null, offset);
526   }
527
528   /**
529    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
530    * Also offset wird der erste Datensatz genommen.
531    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
532    *
533    * @param wc where-Clause
534    * @param ob orderBy-Clause
535    * @return EntityList mit den gematchten Entities
536    * @exception StorageObjectException
537    */
538   public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
539     return selectByWhereClause(where, order, 0);
540   }
541
542   public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws StorageObjectFailure {
543     return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, defaultLimit);
544   }
545
546   /**
547    * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
548    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
549    *
550    * @param wc where-Clause
551    * @param ob orderBy-Clause
552    * @param offset ab welchem Datensatz
553    * @return EntityList mit den gematchten Entities
554    * @exception StorageObjectException
555    */
556   public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
557     return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
558   }
559
560   /**
561    * select-Operator returns EntityList with matching rows in Database.
562    * @param aWhereClause where-Clause
563    * @param anOrderByClause orderBy-Clause
564    * @param offset ab welchem Datensatz
565    * @param limit wieviele Datens?tze
566    * @return EntityList mit den gematchten Entities
567    * @exception StorageObjectException
568    */
569   public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
570             int offset, int limit) throws StorageObjectFailure {
571     return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);              
572   }
573
574
575   /**
576    * select-Operator returns EntityList with matching rows in Database.
577    * @param aWhereClause where-Clause
578    * @param anOrderByClause orderBy-Clause
579    * @param offset ab welchem Datensatz
580    * @param limit wieviele Datens?tze
581    * @return EntityList mit den gematchten Entities
582    * @exception StorageObjectException
583    */
584   public EntityList selectByWhereClause(String mainTablePrefix, List extraTables,
585       String aWhereClause, String anOrderByClause,
586                         int offset, int limit) throws StorageObjectFailure {
587     
588     // TODO get rid of emtpy Strings in extraTables
589     // make extraTables null, if single empty String in it
590     if (extraTables != null && ((String)extraTables.get(0)).trim().equals(""))
591       {
592         logger.debug("+++ made extraTables to null!");
593         extraTables=null;
594       }
595     
596       String useTable = theTable;
597           String selectStar = "*";
598           if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
599             useTable+=" "+mainTablePrefix;
600             selectStar=mainTablePrefix.trim() + ".*";
601           }
602     
603     // check o_store for entitylist
604     // only if no relational select
605     if (extraTables==null) {
606       if (StoreUtil.extendsStorableEntity(theEntityClass)) {
607          StoreIdentifier searchSid = new StoreIdentifier(theEntityClass,
608                StoreContainerType.STOC_TYPE_ENTITYLIST,
609                StoreUtil.getEntityListUniqueIdentifierFor(theTable, 
610                 aWhereClause, anOrderByClause, offset, limit));
611          EntityList hit = (EntityList) o_store.use(searchSid);
612
613          if (hit != null) {
614             return hit;
615          }
616       }
617     }
618
619     // local
620     EntityList theReturnList = null;
621     Connection con = null;
622     Statement stmt = null;
623     ResultSet rs;
624     int offsetCount = 0;
625     int count = 0;
626
627     // build sql-statement
628
629     if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
630       aWhereClause = null;
631     }
632
633     StringBuffer countSql =
634       new StringBuffer("select count(*) from ").append(useTable);
635     StringBuffer selectSql =
636       new StringBuffer("select "+selectStar+" from ").append(useTable);
637  
638     // append extratables, if necessary
639     if (extraTables!=null) {
640       for (int i=0;i < extraTables.size();i++) {
641         if (!extraTables.get(i).equals("")) {        
642           countSql.append( ", " + extraTables.get(i));
643           selectSql.append( ", " + extraTables.get(i));
644         }
645       }
646     }
647     
648     if (aWhereClause != null) {
649       selectSql.append(" where ").append(aWhereClause);
650       countSql.append(" where ").append(aWhereClause);
651     }
652
653     if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
654       selectSql.append(" order by ").append(anOrderByClause);
655     }
656
657     if ((limit > -1) && (offset > -1)) {
658       selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
659     }
660
661     // execute sql
662     try {
663       con = getPooledCon();
664       stmt = con.createStatement();
665
666       // selecting...
667       rs = executeSql(stmt, selectSql.toString());
668
669       if (rs != null) {
670         if (!evaluatedMetaData) {
671           evalMetaData(rs.getMetaData());
672         }
673
674         theReturnList = new EntityList();
675         Entity theResultEntity;
676         while (rs.next()) {
677           theResultEntity = makeEntityFromResultSet(rs);
678           theReturnList.add(theResultEntity);
679           offsetCount++;
680         }
681         rs.close();
682       }
683
684       // making entitylist infos
685       count = offsetCount;
686
687       if (theReturnList != null) {
688         // now we decide if we have to know an overall count...
689         count = offsetCount;
690
691         if ((limit > -1) && (offset > -1)) {
692           if (offsetCount == limit) {
693             rs = executeSql(stmt, countSql.toString());
694
695             if (rs != null) {
696               if (rs.next()) {
697                 count = rs.getInt(1);
698               }
699
700               rs.close();
701             }
702             else {
703               logger.error("Could not count: " + countSql);
704             }
705           }
706         }
707
708         theReturnList.setCount(count);
709         theReturnList.setOffset(offset);
710         theReturnList.setWhere(aWhereClause);
711         theReturnList.setOrder(anOrderByClause);
712         theReturnList.setStorage(this);
713         theReturnList.setLimit(limit);
714
715         if (offset >= limit) {
716           theReturnList.setPrevBatch(offset - limit);
717         }
718
719         if ((offset + offsetCount) < count) {
720           theReturnList.setNextBatch(offset + limit);
721         }
722
723         if (extraTables==null && StoreUtil.extendsStorableEntity(theEntityClass)) {
724           StoreIdentifier sid = theReturnList.getStoreIdentifier();
725           logger.debug("CACHE (add): " + sid.toString());
726           o_store.add(sid);
727         }
728       }
729     }
730     catch (SQLException sqe) {
731       throwSQLException(sqe, "selectByWhereClause");
732     }
733     finally {
734       try {
735         if (con != null) {
736           freeConnection(con, stmt);
737         }
738       } catch (Throwable t) {
739       }
740     }
741
742     return theReturnList;
743   }
744
745   /**
746    *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
747    *
748    *  @param rs Das ResultSetObjekt.
749    *  @return Entity Die Entity.
750    */
751   private Entity makeEntityFromResultSet(ResultSet rs)
752     throws StorageObjectFailure {
753     /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
754     Map theResultHash = new HashMap();
755     String theResult = null;
756     int theType;
757     Entity returnEntity = null;
758
759     try {
760       int size = metadataFields.size();
761
762       for (int i = 0; i < size; i++) {
763         // alle durchlaufen bis nix mehr da
764         theType = metadataTypes[i];
765
766         if (theType == java.sql.Types.LONGVARBINARY) {
767           InputStreamReader is =
768             (InputStreamReader) rs.getCharacterStream(i + 1);
769
770           if (is != null) {
771             char[] data = new char[32768];
772             StringBuffer theResultString = new StringBuffer();
773             int len;
774
775             while ((len = is.read(data)) > 0) {
776               theResultString.append(data, 0, len);
777             }
778
779             is.close();
780             theResult = theResultString.toString();
781           } else {
782             theResult = null;
783           }
784         } else {
785           theResult = getValueAsString(rs, (i + 1), theType);
786         }
787
788         if (theResult != null) {
789           theResultHash.put(metadataFields.get(i), theResult);
790         }
791       }
792
793       if (theEntityClass != null) {
794         returnEntity = (Entity) theEntityClass.newInstance();
795         returnEntity.setStorage(this);
796         returnEntity.setValues(theResultHash);
797
798         if (returnEntity instanceof StorableObject) {
799           logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
800           o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
801         }
802       } else {
803         throwStorageObjectException("Internal Error: theEntityClass not set!");
804       }
805     }
806     catch (IllegalAccessException e) {
807       throwStorageObjectException("No access! -- " + e.getMessage());
808     }
809     catch (IOException e) {
810       throwStorageObjectException("IOException! -- " + e.getMessage());
811     }
812     catch (InstantiationException e) {
813       throwStorageObjectException("No Instatiation! -- " + e.getMessage());
814     }
815     catch (SQLException sqe) {
816       throwSQLException(sqe, "makeEntityFromResultSet");
817
818       return null;
819     }
820
821     return returnEntity;
822   }
823
824   /**
825    * Inserts an entity into the database.
826    *
827    * @param theEntity
828    * @return der Wert des Primary-keys der eingef?gten Entity
829    */
830   public String insert(Entity theEntity) throws StorageObjectFailure {
831     //cache
832     invalidatePopupCache();
833
834     // invalidating all EntityLists corresponding with theEntityClass
835     if (StoreUtil.extendsStorableEntity(theEntityClass)) {
836       StoreContainerType stoc_type =
837         StoreContainerType.valueOf(theEntityClass,
838           StoreContainerType.STOC_TYPE_ENTITYLIST);
839       o_store.invalidate(stoc_type);
840     }
841
842     String returnId = null;
843     Connection con = null;
844     PreparedStatement pstmt = null;
845
846     try {
847       List streamedInput = theEntity.streamedInput();
848       StringBuffer f = new StringBuffer();
849       StringBuffer v = new StringBuffer();
850       String aField;
851       String aValue;
852       boolean firstField = true;
853
854       // make sql-string
855       for (int i = 0; i < getFields().size(); i++) {
856         aField = (String) getFields().get(i);
857
858         if (!aField.equals(thePKeyName)) {
859           aValue = null;
860
861           // exceptions
862           if (!theEntity.hasValueForField(aField) && (
863               aField.equals("webdb_create") ||
864               aField.equals("webdb_lastchange"))) {
865             aValue = "NOW()";
866           }
867           else {
868             if ((streamedInput != null) && streamedInput.contains(aField)) {
869               aValue = "?";
870             }
871             else {
872               if (theEntity.hasValueForField(aField)) {
873                 aValue =
874                   "'" +
875                    JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";
876               }
877             }
878           }
879
880           // wenn Wert gegeben, dann einbauen
881           if (aValue != null) {
882             if (firstField == false) {
883               f.append(",");
884               v.append(",");
885             }
886             else {
887               firstField = false;
888             }
889
890             f.append(aField);
891             v.append(aValue);
892           }
893         }
894       }
895        // end for
896
897       // insert into db
898       StringBuffer sqlBuf =
899         new StringBuffer("insert into ").append(theTable).append("(").append(f)
900                                         .append(") values (").append(v).append(")");
901       String sql = sqlBuf.toString();
902
903       logger.debug("INSERT: " + sql);
904       con = getPooledCon();
905       con.setAutoCommit(false);
906       pstmt = con.prepareStatement(sql);
907
908       if (streamedInput != null) {
909         for (int i = 0; i < streamedInput.size(); i++) {
910           String inputString =
911             (String) theEntity.getValue((String) streamedInput.get(i));
912           pstmt.setBytes(i + 1, inputString.getBytes());
913         }
914       }
915
916       int ret = pstmt.executeUpdate();
917
918       if (ret == 0) {
919         //insert failed
920         return null;
921       }
922
923       pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");
924
925       ResultSet rs = pstmt.executeQuery();
926       rs.next();
927       returnId = rs.getString(1);
928       theEntity.setId(returnId);
929     }
930     catch (SQLException sqe) {
931       throwSQLException(sqe, "insert");
932     }
933     finally {
934       try {
935         con.setAutoCommit(true);
936       }
937       catch (Exception e) {
938       }
939
940       freeConnection(con, pstmt);
941     }
942
943     /** @todo store entity in o_store */
944     return returnId;
945   }
946
947   /**
948    * Updates an entity in the database
949    *
950    * @param theEntity
951    */
952   public void update(Entity theEntity) throws StorageObjectFailure {
953     Connection con = null;
954     PreparedStatement pstmt = null;
955
956     /** @todo this is stupid: why do we prepare statement, when we
957      *  throw it away afterwards. should be regular statement
958      *  update/insert could better be one routine called save()
959      *  that chooses to either insert or update depending if we
960      *  have a primary key in the entity. i don't know if we
961      *  still need the streamed input fields. // rk  */
962     /** @todo extension: check if Entity did change, otherwise we don't need
963      *  the roundtrip to the database */
964     /** invalidating corresponding entitylists in o_store*/
965     if (StoreUtil.extendsStorableEntity(theEntityClass)) {
966       StoreContainerType stoc_type =
967         StoreContainerType.valueOf(theEntityClass,
968           StoreContainerType.STOC_TYPE_ENTITYLIST);
969       o_store.invalidate(stoc_type);
970     }
971
972     List streamedInput = theEntity.streamedInput();
973     String id = theEntity.getId();
974     String aField;
975     StringBuffer fv = new StringBuffer();
976     boolean firstField = true;
977
978     //cache
979     invalidatePopupCache();
980
981     // build sql statement
982     for (int i = 0; i < getFields().size(); i++) {
983       aField = (String) metadataFields.get(i);
984
985       // only normal cases
986       if (  !(aField.equals(thePKeyName) ||
987             aField.equals("webdb_create") ||
988             aField.equals("webdb_lastchange") ||
989             ((streamedInput != null) && streamedInput.contains(aField)))) {
990         if (theEntity.hasValueForField(aField)) {
991           if (firstField == false) {
992             fv.append(", ");
993           }
994           else {
995             firstField = false;
996           }
997
998           fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
999
1000           //              fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
1001         }
1002       }
1003     }
1004
1005     StringBuffer sql =
1006       new StringBuffer("update ").append(theTable).append(" set ").append(fv);
1007
1008     // exceptions
1009     if (metadataFields.contains("webdb_lastchange")) {
1010       sql.append(",webdb_lastchange=NOW()");
1011     }
1012
1013     // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
1014     // format so anything extra will be ignored. -mh
1015     if (metadataFields.contains("webdb_create") &&
1016         theEntity.hasValueForField("webdb_create")) {
1017       // minimum of 10 (yyyy-mm-dd)...
1018       if (theEntity.getValue("webdb_create").length() >= 10) {
1019         String dateString = theEntity.getValue("webdb_create");
1020
1021         // if only 10, then add 00:00 so it doesn't throw a ParseException
1022         if (dateString.length() == 10) {
1023           dateString = dateString + " 00:00";
1024         }
1025
1026         // TimeStamp stuff
1027         try {
1028           java.util.Date d = userInputDateFormat.parse(dateString);
1029 //          Timestamp tStamp = new Timestamp(d.getTime());
1030           sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
1031         }
1032         catch (ParseException e) {
1033           throw new StorageObjectFailure(e);
1034         }
1035       }
1036     }
1037
1038     if (streamedInput != null) {
1039       for (int i = 0; i < streamedInput.size(); i++) {
1040         sql.append(",").append(streamedInput.get(i)).append("=?");
1041       }
1042     }
1043
1044     sql.append(" where id=").append(id);
1045     logger.debug("UPDATE: " + sql);
1046
1047     try {
1048       con = getPooledCon();
1049       con.setAutoCommit(false);
1050       pstmt = con.prepareStatement(sql.toString());
1051
1052       if (streamedInput != null) {
1053         for (int i = 0; i < streamedInput.size(); i++) {
1054           String inputString =
1055             theEntity.getValue((String) streamedInput.get(i));
1056           pstmt.setBytes(i + 1, inputString.getBytes());
1057         }
1058       }
1059
1060       pstmt.executeUpdate();
1061     }
1062     catch (SQLException sqe) {
1063       throwSQLException(sqe, "update");
1064     }
1065     finally {
1066       try {
1067         con.setAutoCommit(true);
1068       }
1069       catch (Exception e) {
1070         ;
1071       }
1072
1073       freeConnection(con, pstmt);
1074     }
1075   }
1076
1077   /*
1078   *   delete-Operator
1079   *   @param id des zu loeschenden Datensatzes
1080   *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
1081    */
1082   public boolean delete(String id) throws StorageObjectFailure {
1083     invalidatePopupCache();
1084
1085     // ostore send notification
1086     if (StoreUtil.extendsStorableEntity(theEntityClass)) {
1087       String uniqueId = id;
1088
1089       if (theEntityClass.equals(StorableObjectEntity.class)) {
1090         uniqueId += ("@" + theTable);
1091       }
1092
1093       logger.debug("CACHE: (del) " + id);
1094
1095       StoreIdentifier search_sid =
1096         new StoreIdentifier(theEntityClass,
1097           StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
1098       o_store.invalidate(search_sid);
1099     }
1100
1101     /** @todo could be prepared Statement */
1102     Statement stmt = null;
1103     Connection con = null;
1104     int res = 0;
1105     String sql =
1106       "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
1107
1108     //theLog.printInfo("DELETE " + sql);
1109     try {
1110       con = getPooledCon();
1111       stmt = con.createStatement();
1112       res = stmt.executeUpdate(sql);
1113     } catch (SQLException sqe) {
1114       throwSQLException(sqe, "delete");
1115     } finally {
1116       freeConnection(con, stmt);
1117     }
1118
1119     return (res > 0) ? true : false;
1120   }
1121
1122   /**
1123    * Deletes entities based on a where clause
1124    *
1125    * @param aWhereClause
1126    * @return
1127    * @throws StorageObjectFailure
1128    */
1129   public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
1130     invalidatePopupCache();
1131     if (StoreUtil.extendsStorableEntity(theEntityClass)) {
1132       StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
1133       o_store.invalidate(stoc_type);
1134     }
1135
1136     Statement stmt = null;
1137     Connection con = null;
1138     int res = 0;
1139     String sql =
1140       "delete from " + theTable + " where " + aWhereClause;
1141
1142     //theLog.printInfo("DELETE " + sql);
1143     try {
1144       con = getPooledCon();
1145       stmt = con.createStatement();
1146       res = stmt.executeUpdate(sql);
1147     }
1148     catch (SQLException sqe) {
1149       throwSQLException(sqe, "delete");
1150     }
1151     finally {
1152       freeConnection(con, stmt);
1153     }
1154
1155     return res;
1156   }
1157
1158   /* noch nicht implementiert.
1159   * @return immer false
1160    */
1161   public boolean delete(EntityList theEntityList) {
1162     invalidatePopupCache();
1163
1164     return false;
1165   }
1166
1167   /* invalidates the popupCache
1168    */
1169   protected void invalidatePopupCache() {
1170     /** @todo  invalidates toooo much */
1171     popupCache = null;
1172     hashCache = null;
1173   }
1174
1175   /**
1176    * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1177    * @param stmt Statemnt
1178    * @param sql Sql-String
1179    * @return ResultSet
1180    * @exception StorageObjectException
1181    */
1182   public ResultSet executeSql(Statement stmt, String sql)
1183                             throws StorageObjectFailure, SQLException {
1184     ResultSet rs;
1185     long startTime = System.currentTimeMillis();
1186
1187     try {
1188       rs = stmt.executeQuery(sql);
1189
1190       logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1191     }
1192     catch (SQLException e) {
1193       logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1194       throw e;
1195     }
1196
1197     return rs;
1198   }
1199 /*
1200   public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
1201     long startTime = System.currentTimeMillis();
1202     Connection connection = null;
1203     Statement statement = null;
1204
1205     try {
1206       connection = getPooledCon();
1207       statement = connection.createStatement();
1208       ResultSet result;
1209
1210       result = statement.executeQuery(sql);
1211
1212       logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1213       return result;
1214     }
1215     catch (Throwable e) {
1216       logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1217       throw new StorageObjectFailure(e);
1218     }
1219     finally {
1220       if (connection!=null) {
1221         freeConnection(connection, statement);
1222       }
1223     }
1224   }
1225 */
1226   private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
1227     try {
1228       Map result = new HashMap();
1229       ResultSetMetaData metaData = aResultSet.getMetaData();
1230       int nrColumns = metaData.getColumnCount();
1231       for (int i=0; i<nrColumns; i++) {
1232         result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
1233       }
1234
1235       return result;
1236     }
1237     catch (Throwable e) {
1238       throw new StorageObjectFailure(e);
1239     }
1240   }
1241
1242   public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
1243     Connection connection = null;
1244     Statement statement = null;
1245     try {
1246       List result = new Vector();
1247       connection = getPooledCon();
1248       statement = connection.createStatement();
1249       ResultSet resultset = executeSql(statement, sql);
1250       try {
1251         while (resultset.next() && result.size() < aLimit) {
1252           result.add(processRow(resultset));
1253         }
1254       }
1255       finally {
1256         resultset.close();
1257       }
1258
1259       return result;
1260     }
1261     catch (Throwable e) {
1262       throw new StorageObjectFailure(e);
1263     }
1264     finally {
1265       if (connection!=null) {
1266         freeConnection(connection, statement);
1267       }
1268     }
1269   };
1270
1271   public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
1272     try {
1273       List resultList = executeFreeSql(anSqlStatement, 1);
1274       try {
1275         if (resultList.size()>0)
1276           return (Map) resultList.get(0);
1277         else
1278           return null;
1279       }
1280       finally {
1281       }
1282     }
1283     catch (Throwable t) {
1284       throw new StorageObjectFailure(t);
1285     }
1286   };
1287
1288   public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
1289     Map row = executeFreeSingleRowSql(sql);
1290
1291     if (row==null)
1292       return null;
1293
1294     Iterator i = row.values().iterator();
1295     if (i.hasNext())
1296       return (String) i.next();
1297     else
1298       return null;
1299   };
1300
1301   public int getSize(String where) throws SQLException, StorageObjectFailure {
1302     return getSize("", null, where);
1303   }
1304   /**
1305    * returns the number of rows in the table
1306    */
1307   public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, StorageObjectFailure {
1308     
1309     long startTime = System.currentTimeMillis();
1310     
1311     String useTable = theTable;
1312     if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
1313           useTable+=" "+mainTablePrefix;
1314     }
1315     StringBuffer countSql =
1316       new StringBuffer("select count(*) from ").append(useTable);
1317         // append extratables, if necessary
1318       if (extraTables!=null) {
1319         for (int i=0;i < extraTables.size();i++) {
1320           if (!extraTables.get(i).equals("")) {        
1321             countSql.append( ", " + extraTables.get(i));
1322           }
1323         }
1324       }
1325
1326     if ((where != null) && (where.length() != 0)) {
1327       countSql.append( " where " + where);
1328     }
1329
1330     Connection con = null;
1331     Statement stmt = null;
1332     int result = 0;
1333
1334     try {
1335       con = getPooledCon();
1336       stmt = con.createStatement();
1337
1338       ResultSet rs = executeSql(stmt, countSql.toString());
1339
1340       while (rs.next()) {
1341         result = rs.getInt(1);
1342       }
1343     }
1344     catch (SQLException e) {
1345       logger.error("Database.getSize: " + e.getMessage());
1346     }
1347     finally {
1348       freeConnection(con, stmt);
1349     }
1350     logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + countSql);
1351
1352     return result;
1353   }
1354
1355   public int executeUpdate(Statement stmt, String sql)
1356     throws StorageObjectFailure, SQLException {
1357     int rs;
1358     long startTime = System.currentTimeMillis();
1359
1360     try {
1361       rs = stmt.executeUpdate(sql);
1362
1363       logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1364     }
1365     catch (SQLException e) {
1366       logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1367       throw e;
1368     }
1369
1370     return rs;
1371   }
1372
1373   public int executeUpdate(String sql)
1374     throws StorageObjectFailure, SQLException {
1375     int result = -1;
1376     long startTime = System.currentTimeMillis();
1377     Connection con = null;
1378     PreparedStatement pstmt = null;
1379
1380     try {
1381       con = getPooledCon();
1382       pstmt = con.prepareStatement(sql);
1383       result = pstmt.executeUpdate();
1384     }
1385     catch (Throwable e) {
1386       logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
1387       throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
1388     }
1389     finally {
1390       freeConnection(con, pstmt);
1391     }
1392
1393     logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1394     return result;
1395   }
1396
1397   /**
1398    * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1399    * @param md ResultSetMetaData
1400    * @exception StorageObjectException
1401    */
1402   private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
1403     this.evaluatedMetaData = true;
1404     this.metadataFields = new ArrayList();
1405     this.metadataLabels = new ArrayList();
1406     this.metadataNotNullFields = new ArrayList();
1407
1408     try {
1409       int numFields = md.getColumnCount();
1410       this.metadataTypes = new int[numFields];
1411
1412       String aField;
1413       int aType;
1414
1415       for (int i = 1; i <= numFields; i++) {
1416         aField = md.getColumnName(i);
1417         metadataFields.add(aField);
1418         metadataLabels.add(md.getColumnLabel(i));
1419         aType = md.getColumnType(i);
1420         metadataTypes[i - 1] = aType;
1421
1422         if (aField.equals(thePKeyName)) {
1423           thePKeyType = aType;
1424           thePKeyIndex = i;
1425         }
1426
1427         if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
1428           metadataNotNullFields.add(aField);
1429         }
1430       }
1431     }
1432     catch (SQLException e) {
1433       throwSQLException(e, "evalMetaData");
1434     }
1435   }
1436
1437   /**
1438    *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1439    *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1440    */
1441   private void get_meta_data() throws StorageObjectFailure {
1442     Connection con = null;
1443     PreparedStatement pstmt = null;
1444     String sql = "select * from " + theTable + " where 0=1";
1445
1446     try {
1447       con = getPooledCon();
1448       pstmt = con.prepareStatement(sql);
1449
1450       logger.debug("METADATA: " + sql);
1451       ResultSet rs = pstmt.executeQuery();
1452       evalMetaData(rs.getMetaData());
1453       rs.close();
1454     }
1455     catch (SQLException e) {
1456       throwSQLException(e, "get_meta_data");
1457     }
1458     finally {
1459       freeConnection(con, pstmt);
1460     }
1461   }
1462
1463   public Connection getPooledCon() throws StorageObjectFailure {
1464     Connection con = null;
1465
1466     try {
1467       con = SQLManager.getInstance().requestConnection();
1468     }
1469     catch (SQLException e) {
1470       logger.error("could not connect to the database " + e.getMessage());
1471
1472       throw new StorageObjectFailure("Could not connect to the database", e);
1473     }
1474
1475     return con;
1476   }
1477
1478   public void freeConnection(Connection con, Statement stmt)
1479     throws StorageObjectFailure {
1480     SQLManager.closeStatement(stmt);
1481     SQLManager.getInstance().returnConnection(con);
1482   }
1483
1484   /**
1485    * Wertet SQLException aus und wirft dannach eine StorageObjectException
1486    * @param sqe SQLException
1487    * @param wo Funktonsname, in der die SQLException geworfen wurde
1488    * @exception StorageObjectException
1489    */
1490   protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {
1491     String state = "";
1492     String message = "";
1493     int vendor = 0;
1494
1495     if (sqe != null) {
1496       state = sqe.getSQLState();
1497       message = sqe.getMessage();
1498       vendor = sqe.getErrorCode();
1499     }
1500
1501     String information =
1502         "SQL Error: " +
1503         "state= " + state +
1504         ", vendor= " + vendor +
1505         ", message=" + message +
1506         ", function= " + aFunction;
1507
1508     logger.error(information);
1509
1510     throw new StorageObjectFailure(information, sqe);
1511   }
1512
1513   protected void _throwStorageObjectException(Exception e, String aFunction)
1514     throws StorageObjectFailure {
1515
1516     if (e != null) {
1517       logger.error(e.getMessage() + aFunction);
1518       throw new StorageObjectFailure(aFunction, e);
1519     }
1520   }
1521
1522   /**
1523    * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1524    * eine StorageObjectException
1525    * @param message Nachricht mit dem Fehler
1526    * @exception StorageObjectException
1527    */
1528   void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
1529     logger.error(aMessage);
1530     throw new StorageObjectFailure(aMessage, null);
1531   }
1532 }