2 * put your module comment here
10 import freemarker.template.SimpleList;
11 import freemarker.template.SimpleHash;
12 import com.javaexchange.dbConnectionBroker.*;
13 import mir.storage.StorageObject;
19 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
20 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
21 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
22 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
23 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
29 public class Database implements StorageObject {
31 protected DbConnectionBroker myBroker;
32 protected String theTable;
33 protected String theCoreTable=null;
34 protected String thePKeyName="id";
35 protected int thePKeyType;
36 protected boolean evaluatedMetaData=false;
37 protected ArrayList metadataFields,metadataLabels,metadataNotNullFields;
38 protected int[] metadataTypes;
39 protected Class theEntityClass;
40 protected StorageObject myselfDatabase;
41 protected HashMap cache;
42 protected SimpleList popupCache=null;
43 protected boolean hasPopupCache = false;
44 protected SimpleHash hashCache=null;
45 protected boolean hasTimestamp=true;
46 private String database_driver;
47 private String database_url;
48 private int defaultLimit;
49 protected DatabaseAdaptor theAdaptor;
50 protected Logfile theLog;
51 protected Connection con;
54 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
55 * Aus diesem file werden <code>Database.Logfile</code>,
56 * <code>Database.Username</code>,<code>Database.Password</code>,
57 * <code>Database.Host</code> und <code>Database.Adaptor</code>
58 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
61 * @param String confFilename Dateiname der Konfigurationsdatei
63 public Database() throws StorageObjectException {
64 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
65 String database_username=MirConfig.getProp("Database.Username");
66 String database_password=MirConfig.getProp("Database.Password");
67 String database_host=MirConfig.getProp("Database.Host");
68 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
70 theEntityClass = Class.forName("mir.entity.GenericEntity");
71 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
72 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
73 database_driver=theAdaptor.getDriver();
74 database_url=theAdaptor.getURL(database_username,database_password,database_host);
75 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
76 MirConfig.addBroker(database_driver,database_url);
77 myBroker=MirConfig.getBroker();
80 theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
81 throw new StorageObjectException(e.toString());
86 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
87 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
88 * wird eine mir.entity.GenericEntity erzeugt.
90 * @return Class-Objekt der Entity
92 public java.lang.Class getEntityClass () {
93 return theEntityClass;
97 * Liefert die Standardbeschränkung von select-Statements zurück, also
98 * wieviel Datensätze per Default selektiert werden.
100 * @return Standard-Anzahl der Datensätze
102 public int getLimit () {
107 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
108 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
109 * @return Name des Primary-Keys
111 public String getIdName () {
116 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
118 * @return Name der Tabelle
120 public String getTableName () {
125 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
126 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
127 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
131 public String getCoreTable(){
132 if (theCoreTable!=null) return theCoreTable;
133 else return theTable;
137 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
138 * @return int-Array mit den Typen der Felder
139 * @exception StorageObjectException
141 public int[] getTypes () throws StorageObjectException {
142 if (metadataTypes == null)
144 return metadataTypes;
148 * Liefert eine Liste der Labels der Tabellenfelder
149 * @return ArrayListe mit Labeln
150 * @exception StorageObjectException
152 public ArrayList getLabels () throws StorageObjectException {
153 if (metadataLabels == null)
155 return metadataLabels;
159 * Liefert eine Liste der Felder der Tabelle
160 * @return ArrayList mit Feldern
161 * @exception StorageObjectException
163 public ArrayList getFields () throws StorageObjectException {
164 if (metadataFields == null)
166 return metadataFields;
171 * Gets value out of ResultSet according to type and converts to String
172 * @param inValue Wert aus ResultSet.
173 * @param aType Datenbanktyp.
174 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
175 * dann /unsupported value/
177 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
178 String outValue = null;
182 case java.sql.Types.BIT:
183 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
185 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
186 int out = rs.getInt(valueIndex);
188 outValue = new Integer(out).toString();
190 case java.sql.Types.NUMERIC:
191 long outl = rs.getLong(valueIndex);
193 outValue = new Long(outl).toString();
195 case java.sql.Types.REAL:
196 float tempf = rs.getFloat(valueIndex);
200 int tempf_int = (int)tempf;
201 tempf = (float)tempf_int;
203 outValue = "" + tempf;
204 outValue = outValue.replace('.', ',');
207 case java.sql.Types.DOUBLE:
208 double tempd = rs.getDouble(valueIndex);
212 int tempd_int = (int)tempd;
213 tempd = (double)tempd_int;
215 outValue = "" + tempd;
216 outValue = outValue.replace('.', ',');
219 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
220 outValue = rs.getString(valueIndex);
221 if (outValue != null)
222 outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
224 case java.sql.Types.LONGVARBINARY:
225 outValue = rs.getString(valueIndex);
226 if (outValue != null)
227 outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
229 case java.sql.Types.TIMESTAMP:
230 Timestamp timestamp = (rs.getTimestamp(valueIndex));
232 outValue = timestamp.toString();
236 outValue = "<unsupported value>";
237 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
240 } catch (SQLException e) {
241 throw new StorageObjectException("Could not get Value out of Resultset -- "
249 * select-Operator um einen Datensatz zu bekommen.
250 * @param id Primaerschluessel des Datensatzes.
251 * @return liefert EntityObject des gefundenen Datensatzes oder null.
253 public Entity selectById(String id)
254 throws StorageObjectException {
256 if (id==null||id.equals(""))
257 throw new StorageObjectException("id war null");
258 if (cache != null && cache.containsKey(id))
259 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
261 Statement stmt=null;Connection con=getPooledCon();
262 Entity returnEntity=null;
265 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
266 stmt = con.createStatement();
267 rs = executeSql(stmt, selectSql);
269 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
271 returnEntity = makeEntityFromResultSet(rs);
272 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
275 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
277 } catch (SQLException sqe){
278 throwSQLException(sqe,"selectById"); return null;
279 } catch (NumberFormatException e) {
280 theLog.printError("ID ist keine Zahl: " + id);
282 freeConnection(con,stmt);
289 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
290 * @param key Datenbankfeld der Bedingung.
291 * @param value Wert die der key anehmen muss.
292 * @return EntityList mit den gematchten Entities
295 public EntityList selectByFieldValue(String aField, String aValue)
296 throws StorageObjectException {
298 return selectByFieldValue(aField, aValue, 0);
302 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
303 * @param key Datenbankfeld der Bedingung.
304 * @param value Wert die der key anehmen muss.
305 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
306 * @return EntityList mit den gematchten Entities
309 public EntityList selectByFieldValue(String aField, String aValue, int offset)
310 throws StorageObjectException {
312 return selectByWhereClause(aField + "=" + aValue, offset);
317 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
318 * Also offset wird der erste Datensatz genommen.
320 * @param wc where-Clause
321 * @return EntityList mit den gematchten Entities
322 * @exception StorageObjectException
324 public EntityList selectByWhereClause(String where)
325 throws StorageObjectException {
327 return selectByWhereClause(where, 0);
332 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
333 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
335 * @param wc where-Clause
336 * @param offset ab welchem Datensatz.
337 * @return EntityList mit den gematchten Entities
338 * @exception StorageObjectException
340 public EntityList selectByWhereClause(String whereClause, int offset)
341 throws StorageObjectException {
343 return selectByWhereClause(whereClause, null, offset);
347 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
348 * Also offset wird der erste Datensatz genommen.
349 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
351 * @param wc where-Clause
352 * @param ob orderBy-Clause
353 * @return EntityList mit den gematchten Entities
354 * @exception StorageObjectException
357 public EntityList selectByWhereClause(String where, String order)
358 throws StorageObjectException {
360 return selectByWhereClause(where, order, 0);
363 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
364 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
366 * @param wc where-Clause
367 * @param ob orderBy-Clause
368 * @param offset ab welchem Datensatz
369 * @return EntityList mit den gematchten Entities
370 * @exception StorageObjectException
373 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
374 throws StorageObjectException {
376 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
381 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
382 * @param wc where-Clause
383 * @param ob orderBy-Clause
384 * @param offset ab welchem Datensatz
385 * @param limit wieviele Datensätze
386 * @return EntityList mit den gematchten Entities
387 * @exception StorageObjectException
390 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
391 throws StorageObjectException {
394 EntityList theReturnList=null;
402 // build sql-statement
403 if (wc != null && wc.length() == 0) {
406 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
407 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
409 selectSql.append(" where ").append(wc);
410 countSql.append(" where ").append(wc);
412 if (ob != null && !(ob.length() == 0)) {
413 selectSql.append(" order by ").append(ob);
415 if (theAdaptor.hasLimit()) {
416 if (limit > -1 && offset > -1) {
417 selectSql.append(" limit ");
418 if (theAdaptor.reverseLimit()) {
419 selectSql.append(limit).append(",").append(offset);
422 selectSql.append(offset).append(",").append(limit);
429 con = getPooledCon();
430 stmt = con.createStatement();
432 if (theAdaptor.hasLimit()) {
433 rs = executeSql(stmt, countSql.toString());
436 count = rs.getInt(1);
440 theLog.printError("Mh. Konnte nicht zaehlen: " + countSql);
443 rs = executeSql(stmt, selectSql.toString());
445 theReturnList = new EntityList();
446 if (evaluatedMetaData == false) {
447 evalMetaData(rs.getMetaData());
449 Entity theResultEntity;
451 theResultEntity = makeEntityFromResultSet(rs);
452 theReturnList.add(theResultEntity);
458 if (!(theAdaptor.hasLimit()))
460 if (theReturnList != null) {
461 theReturnList.setCount(count);
462 theReturnList.setOffset(offset);
463 theReturnList.setWhere(wc);
464 theReturnList.setOrder(ob);
465 if (offset >= limit) {
466 theReturnList.setPrevBatch(offset - limit);
468 if (offset + offsetCount < count) {
469 theReturnList.setNextBatch(offset + limit);
472 } catch (SQLException sqe) {
473 throwSQLException(sqe, "selectByWhereClause");
475 freeConnection(con, stmt);
477 return theReturnList;
481 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
483 * @param rs Das ResultSetObjekt.
484 * @return Entity Die Entity.
487 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
488 HashMap theResultHash = new HashMap();
489 String theResult = null;
491 Entity returnEntity = null;
493 int size = metadataFields.size();
494 for (int i = 0; i < size; i++) {
495 // alle durchlaufen bis nix mehr da
496 theType = metadataTypes[i];
497 if (theType == java.sql.Types.LONGVARBINARY) {
498 InputStream us = rs.getAsciiStream(i + 1);
500 InputStreamReader is = new InputStreamReader(us);
501 char[] data = new char[32768];
502 StringBuffer theResultString = new StringBuffer();
504 while ((len = is.read(data)) > 0) {
505 theResultString.append(data, 0, len);
508 theResult = theResultString.toString();
515 theResult = getValueAsString(rs, (i + 1), theType);
517 if (theResult != null) {
518 theResultHash.put(metadataFields.get(i), theResult);
521 if (cache != null && theResultHash.containsKey(thePKeyName) && cache.containsKey((String)theResultHash.get(thePKeyName))) {
522 //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
523 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
526 if (theEntityClass != null) {
527 returnEntity = (Entity)theEntityClass.newInstance();
528 returnEntity.setValues(theResultHash);
529 returnEntity.setStorage(myselfDatabase);
531 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
532 cache.put(returnEntity.getId(), returnEntity);
536 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
540 catch (IllegalAccessException e) {
541 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
542 } catch (IOException e) {
543 throwStorageObjectException("IOException! -- " + e.toString());
544 } catch (InstantiationException e) {
545 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
546 } catch (SQLException sqe) {
547 throwSQLException(sqe, "makeEntityFromResultSet");
554 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
555 * wird automatisch mit dem aktuellen Datum gefuellt.
558 * @return der Wert des Primary-keys der eingefügten Entity
560 public String insert (Entity theEntity) throws StorageObjectException {
561 String returnId = null;
562 Connection con = null;
563 PreparedStatement pstmt = null;
565 invalidatePopupCache();
567 HashMap theEntityValues = theEntity.getValues();
568 ArrayList streamedInput = theEntity.streamedInput();
569 StringBuffer f = new StringBuffer();
570 StringBuffer v = new StringBuffer();
571 String aField, aValue;
572 boolean firstField = true;
574 for (int i = 0; i < getFields().size(); i++) {
575 aField = (String)getFields().get(i);
576 if (!aField.equals(thePKeyName)) {
579 if (aField.equals("webdb_create")) {
583 if (streamedInput != null && streamedInput.contains(aField)) {
587 if (theEntityValues.containsKey(aField)) {
588 aValue = "'" + StringUtil.quote((String)theEntityValues.get(aField))
593 // wenn Wert gegeben, dann einbauen
594 if (aValue != null) {
595 if (firstField == false) {
608 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
609 String sql = sqlBuf.toString();
610 theLog.printInfo("INSERT: " + sql);
611 con = getPooledCon();
612 con.setAutoCommit(false);
613 pstmt = con.prepareStatement(sql);
614 if (streamedInput != null) {
615 for (int i = 0; i < streamedInput.size(); i++) {
616 String inputString = (String)theEntityValues.get(streamedInput.get(i));
617 pstmt.setBytes(i + 1, inputString.getBytes());
620 int ret = pstmt.executeUpdate();
625 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
626 ResultSet rs = pstmt.executeQuery();
628 returnId = rs.getString(1);
629 theEntity.setId(returnId);
630 } catch (SQLException sqe) {
631 throwSQLException(sqe, "insert");
634 con.setAutoCommit(true);
635 } catch (Exception e) {
638 freeConnection(con, pstmt);
644 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
645 * wird automatisch mit dem aktuellen Datum gefuellt.
649 public void update (Entity theEntity) throws StorageObjectException {
650 Connection con = null;
651 PreparedStatement pstmt = null;
652 ArrayList streamedInput = theEntity.streamedInput();
653 HashMap theEntityValues = theEntity.getValues();
654 String id = theEntity.getId();
656 StringBuffer fv = new StringBuffer();
657 boolean firstField = true;
659 invalidatePopupCache();
660 // build sql statement
661 for (int i = 0; i < getFields().size(); i++) {
662 aField = (String)metadataFields.get(i);
664 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
665 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
666 if (theEntityValues.containsKey(aField)) {
667 if (firstField == false) {
673 fv.append(aField).append("='").append(StringUtil.quote((String)theEntityValues.get(aField))).append("'");
677 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
679 if (metadataFields.contains("webdb_lastchange")) {
680 sql.append(",webdb_lastchange=NOW()");
682 if (streamedInput != null) {
683 for (int i = 0; i < streamedInput.size(); i++) {
684 sql.append(",").append(streamedInput.get(i)).append("=?");
687 sql.append(" where id=").append(id);
688 theLog.printInfo("UPDATE: " + sql);
691 con = getPooledCon();
692 con.setAutoCommit(false);
693 pstmt = con.prepareStatement(sql.toString());
694 if (streamedInput != null) {
695 for (int i = 0; i < streamedInput.size(); i++) {
696 String inputString = (String)theEntityValues.get(streamedInput.get(i));
697 pstmt.setBytes(i + 1, inputString.getBytes());
700 pstmt.executeUpdate();
701 } catch (SQLException sqe) {
702 throwSQLException(sqe, "update");
705 con.setAutoCommit(true);
706 } catch (Exception e) {
709 freeConnection(con, pstmt);
715 * @param id des zu loeschenden Datensatzes
716 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
718 public boolean delete (String id) throws StorageObjectException {
719 Statement stmt = null;
720 Connection con = null;
723 // loeschen des caches
724 invalidatePopupCache();
725 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
727 theLog.printInfo("DELETE " + sql);
729 con = getPooledCon();
730 stmt = con.createStatement();
731 res = stmt.executeUpdate(sql);
732 } catch (SQLException sqe) {
733 throwSQLException(sqe, "delete");
735 freeConnection(con, stmt);
738 theLog.printInfo("CACHE: deleted " + id);
741 return (res > 0) ? true : false;
744 /* noch nicht implementiert.
745 * @return immer false
747 public boolean delete (EntityList theEntityList) {
748 invalidatePopupCache();
753 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
754 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
757 public SimpleList getPopupData () throws StorageObjectException {
762 * Holt Daten fuer Popups.
763 * @param name Name des Feldes.
764 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
765 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
767 public SimpleList getPopupData (String name, boolean hasNullValue)
768 throws StorageObjectException {
769 return getPopupData(name, hasNullValue, null);
773 * Holt Daten fuer Popups.
774 * @param name Name des Feldes.
775 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
776 * @param where Schraenkt die Selektion der Datensaetze ein.
777 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
779 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
780 return getPopupData(name, hasNullValue, where, null);
784 * Holt Daten fuer Popups.
785 * @param name Name des Feldes.
786 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
787 * @param where Schraenkt die Selektion der Datensaetze ein.
788 * @param order Gibt ein Feld als Sortierkriterium an.
789 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
791 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
793 if (hasPopupCache && popupCache != null)
795 SimpleList simpleList = null;
796 Connection con = null;
797 Statement stmt = null;
799 StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
800 if (where != null && !(where.length() == 0))
801 sql.append(" where ").append(where);
802 sql.append(" order by ");
803 if (order != null && !(order.length() == 0))
809 con = getPooledCon();
810 stmt = con.createStatement();
811 ResultSet rs = executeSql(stmt, sql.toString());
813 if (evaluatedMetaData == false)
815 simpleList = new SimpleList();
816 SimpleHash popupDict;
818 popupDict = new SimpleHash();
819 popupDict.put("key", "");
820 popupDict.put("value", "--");
821 simpleList.add(popupDict);
824 popupDict = new SimpleHash();
825 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
826 popupDict.put("value", rs.getString(2));
827 simpleList.add(popupDict);
831 } catch (Exception e) {
832 theLog.printDebugInfo(e.toString());
833 throw new StorageObjectException(e.toString());
835 freeConnection(con, stmt);
838 popupCache = simpleList;
844 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
845 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
846 * Tabellen Verwendung finden.
847 * @return SimpleHash mit den Tabellezeilen.
849 public SimpleHash getHashData () {
850 if (hashCache == null) {
852 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
854 } catch (StorageObjectException e) {
855 theLog.printDebugInfo(e.toString());
861 /* invalidates the popupCache
863 protected void invalidatePopupCache () {
865 /** @todo invalidates toooo much */
871 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
872 * @param stmt Statemnt
873 * @param sql Sql-String
875 * @exception StorageObjectException
877 public ResultSet executeSql (Statement stmt, String sql)
878 throws StorageObjectException, SQLException
881 long startTime = (new java.util.Date()).getTime();
883 rs = stmt.executeQuery(sql);
884 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
887 catch (SQLException e)
889 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
898 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
899 * getimed und geloggt.
900 * @param stmt PreparedStatement mit der SQL-Anweisung
901 * @return Liefert ResultSet des Statements zurueck.
902 * @exception StorageObjectException, SQLException
904 public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
907 long startTime = (new java.util.Date()).getTime();
908 ResultSet rs = stmt.executeQuery();
909 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
914 * returns the number of rows in the table
916 public int getSize(String where)
917 throws SQLException,StorageObjectException
919 long startTime = (new java.util.Date()).getTime();
920 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
921 //theLog.printDebugInfo("trying: "+ sql);
922 Connection con = null;
923 Statement stmt = null;
927 con = getPooledCon();
928 stmt = con.createStatement();
929 ResultSet rs = executeSql(stmt,sql);
931 result = rs.getInt(1);
933 } catch (SQLException e) {
934 theLog.printError(e.toString());
936 freeConnection(con,stmt);
938 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
939 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
943 public int executeUpdate(Statement stmt, String sql)
944 throws StorageObjectException, SQLException
947 long startTime = (new java.util.Date()).getTime();
950 rs = stmt.executeUpdate(sql);
951 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
953 catch (SQLException e)
955 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
962 public int executeUpdate(String sql)
963 throws StorageObjectException, SQLException
966 long startTime = (new java.util.Date()).getTime();
967 Connection con=null;PreparedStatement pstmt=null;
970 pstmt = con.prepareStatement(sql);
971 result = pstmt.executeUpdate();
973 catch (Exception e) {
974 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
975 throw new StorageObjectException("executeUpdate failed: "+e.toString());
977 finally { freeConnection(con,pstmt); }
978 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
983 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
984 * @param md ResultSetMetaData
985 * @exception StorageObjectException
987 private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
988 this.evaluatedMetaData = true;
989 this.metadataFields = new ArrayList();
990 this.metadataLabels = new ArrayList();
991 this.metadataNotNullFields = new ArrayList();
993 int numFields = md.getColumnCount();
994 this.metadataTypes = new int[numFields];
997 for (int i = 1; i <= numFields; i++) {
998 aField = md.getColumnName(i);
999 metadataFields.add(aField);
1000 metadataLabels.add(md.getColumnLabel(i));
1001 aType = md.getColumnType(i);
1002 metadataTypes[i - 1] = aType;
1003 if (aField.equals(thePKeyName)) {
1004 thePKeyType = aType;
1006 if (md.isNullable(i) == md.columnNullable) {
1007 metadataNotNullFields.add(aField);
1010 } catch (SQLException e) {
1011 throwSQLException(e, "evalMetaData");
1016 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1017 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1019 private void get_meta_data () throws StorageObjectException {
1020 Connection con = null;
1021 PreparedStatement pstmt = null;
1022 String sql = "select * from " + theTable + " where 0=1";
1024 con = getPooledCon();
1025 pstmt = con.prepareStatement(sql);
1026 theLog.printInfo("METADATA: " + sql);
1027 ResultSet rs = pstmt.executeQuery();
1028 evalMetaData(rs.getMetaData());
1030 } catch (SQLException e) {
1031 throwSQLException(e, "get_meta_data");
1033 freeConnection(con, pstmt);
1038 * Datenbankverbindung wird geschlossen
1040 public void disconnectPool () throws StorageObjectException {
1042 myBroker.destroy(100);
1043 } catch (SQLException sqe) {
1044 throwSQLException(sqe, "disconnectPool");
1049 * Returns Connection-Object out of the PoolBroker.
1051 * @return Connection Object.
1053 public Connection getPooledCon () throws StorageObjectException {
1054 if (myBroker != null) {
1055 Connection con = myBroker.getConnection();
1059 throw new StorageObjectException("No connection to database!");
1063 * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1065 * @param con Connection zur Datenbank
1066 * @param stmt Statement-Objekt
1068 public void freeConnection (Connection con, Statement stmt)
1069 throws StorageObjectException {
1073 } catch (SQLException e1) {
1074 theLog.printDebugInfo(e1.toString());
1075 throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1078 myBroker.freeConnection(con);
1080 theLog.printDebugInfo("Con was null!");
1081 throw new StorageObjectException("Con was null!");
1086 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1087 * @param sqe SQLException
1088 * @param wo Funktonsname, in der die SQLException geworfen wurde
1089 * @exception StorageObjectException
1091 protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1093 String message = "";
1096 state = sqe.getSQLState();
1097 message = sqe.getMessage();
1098 vendor = sqe.getErrorCode();
1100 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1102 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1107 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1108 * @param message Nachricht mit dem Fehler
1109 * @exception StorageObjectException
1111 void throwStorageObjectException (String message) throws StorageObjectException {
1112 theLog.printError(message);
1113 throw new StorageObjectException(message);