2 * put your module comment here
10 import freemarker.template.*;
11 import com.javaexchange.dbConnectionBroker.*;
12 import mir.storage.StorageObject;
18 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
19 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
20 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
21 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
22 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
28 public class Database implements StorageObject {
30 protected DbConnectionBroker myBroker;
31 protected String theTable;
32 protected String theCoreTable=null;
33 protected String thePKeyName="id";
34 protected int thePKeyType;
35 protected boolean evaluatedMetaData=false;
36 protected ArrayList metadataFields,metadataLabels,metadataNotNullFields;
37 protected int[] metadataTypes;
38 protected Class theEntityClass;
39 protected StorageObject myselfDatabase;
40 protected DatabaseCache cache;
41 protected SimpleList popupCache=null;
42 protected boolean hasPopupCache = false;
43 protected SimpleHash hashCache=null;
44 protected boolean hasTimestamp=true;
45 private String database_driver;
46 private String database_url;
47 private int defaultLimit;
48 protected DatabaseAdaptor theAdaptor;
49 protected Logfile theLog;
52 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
53 * Aus diesem file werden <code>Database.Logfile</code>,
54 * <code>Database.Username</code>,<code>Database.Password</code>,
55 * <code>Database.Host</code> und <code>Database.Adaptor</code>
56 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
59 * @param String confFilename Dateiname der Konfigurationsdatei
61 public Database() throws StorageObjectException {
62 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
63 String database_username=MirConfig.getProp("Database.Username");
64 String database_password=MirConfig.getProp("Database.Password");
65 String database_host=MirConfig.getProp("Database.Host");
66 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
68 theEntityClass = Class.forName("mir.entity.GenericEntity");
69 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
70 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
71 database_driver=theAdaptor.getDriver();
72 database_url=theAdaptor.getURL(database_username,database_password,database_host);
73 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
74 MirConfig.addBroker(database_driver,database_url);
75 myBroker=MirConfig.getBroker();
78 theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
79 throw new StorageObjectException(e.toString());
84 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
85 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
86 * wird eine mir.entity.GenericEntity erzeugt.
88 * @return Class-Objekt der Entity
90 public java.lang.Class getEntityClass () {
91 return theEntityClass;
95 * Liefert die Standardbeschränkung von select-Statements zurück, also
96 * wieviel Datensätze per Default selektiert werden.
98 * @return Standard-Anzahl der Datensätze
100 public int getLimit () {
105 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
106 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
107 * @return Name des Primary-Keys
109 public String getIdName () {
114 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
116 * @return Name der Tabelle
118 public String getTableName () {
123 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
124 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
125 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
129 public String getCoreTable(){
130 if (theCoreTable!=null) return theCoreTable;
131 else return theTable;
135 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
136 * @return int-Array mit den Typen der Felder
137 * @exception StorageObjectException
139 public int[] getTypes () throws StorageObjectException {
140 if (metadataTypes == null)
142 return metadataTypes;
146 * Liefert eine Liste der Labels der Tabellenfelder
147 * @return ArrayListe mit Labeln
148 * @exception StorageObjectException
150 public ArrayList getLabels () throws StorageObjectException {
151 if (metadataLabels == null)
153 return metadataLabels;
157 * Liefert eine Liste der Felder der Tabelle
158 * @return ArrayList mit Feldern
159 * @exception StorageObjectException
161 public ArrayList getFields () throws StorageObjectException {
162 if (metadataFields == null)
164 return metadataFields;
169 * Gets value out of ResultSet according to type and converts to String
170 * @param inValue Wert aus ResultSet.
171 * @param aType Datenbanktyp.
172 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
173 * dann /unsupported value/
175 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
176 String outValue = null;
180 case java.sql.Types.BIT:
181 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
183 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
184 int out = rs.getInt(valueIndex);
186 outValue = new Integer(out).toString();
188 case java.sql.Types.NUMERIC:
189 long outl = rs.getLong(valueIndex);
191 outValue = new Long(outl).toString();
193 case java.sql.Types.REAL:
194 float tempf = rs.getFloat(valueIndex);
198 int tempf_int = (int)tempf;
199 tempf = (float)tempf_int;
201 outValue = "" + tempf;
202 outValue = outValue.replace('.', ',');
205 case java.sql.Types.DOUBLE:
206 double tempd = rs.getDouble(valueIndex);
210 int tempd_int = (int)tempd;
211 tempd = (double)tempd_int;
213 outValue = "" + tempd;
214 outValue = outValue.replace('.', ',');
217 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
218 outValue = rs.getString(valueIndex);
219 //if (outValue != null)
220 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
222 case java.sql.Types.LONGVARBINARY:
223 outValue = rs.getString(valueIndex);
224 //if (outValue != null)
225 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
227 case java.sql.Types.TIMESTAMP:
228 Timestamp timestamp = (rs.getTimestamp(valueIndex));
230 outValue = timestamp.toString();
234 outValue = "<unsupported value>";
235 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
238 } catch (SQLException e) {
239 throw new StorageObjectException("Could not get Value out of Resultset -- "
247 * select-Operator um einen Datensatz zu bekommen.
248 * @param id Primaerschluessel des Datensatzes.
249 * @return liefert EntityObject des gefundenen Datensatzes oder null.
251 public Entity selectById(String id)
252 throws StorageObjectException {
254 if (id==null||id.equals(""))
255 throw new StorageObjectException("id war null");
256 if (cache != null && (cache.containsKey(id) > -1))
257 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
259 Statement stmt=null;Connection con=getPooledCon();
260 Entity returnEntity=null;
263 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
264 stmt = con.createStatement();
265 rs = executeSql(stmt, selectSql);
267 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
269 returnEntity = makeEntityFromResultSet(rs);
270 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
273 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
275 } catch (SQLException sqe){
276 throwSQLException(sqe,"selectById"); return null;
277 } catch (NumberFormatException e) {
278 theLog.printError("ID ist keine Zahl: " + id);
280 freeConnection(con,stmt);
287 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
288 * @param key Datenbankfeld der Bedingung.
289 * @param value Wert die der key anehmen muss.
290 * @return EntityList mit den gematchten Entities
293 public EntityList selectByFieldValue(String aField, String aValue)
294 throws StorageObjectException {
296 return selectByFieldValue(aField, aValue, 0);
300 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
301 * @param key Datenbankfeld der Bedingung.
302 * @param value Wert die der key anehmen muss.
303 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
304 * @return EntityList mit den gematchten Entities
307 public EntityList selectByFieldValue(String aField, String aValue, int offset)
308 throws StorageObjectException {
310 return selectByWhereClause(aField + "=" + aValue, offset);
315 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
316 * Also offset wird der erste Datensatz genommen.
318 * @param wc where-Clause
319 * @return EntityList mit den gematchten Entities
320 * @exception StorageObjectException
322 public EntityList selectByWhereClause(String where)
323 throws StorageObjectException {
325 return selectByWhereClause(where, 0);
330 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
331 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
333 * @param wc where-Clause
334 * @param offset ab welchem Datensatz.
335 * @return EntityList mit den gematchten Entities
336 * @exception StorageObjectException
338 public EntityList selectByWhereClause(String whereClause, int offset)
339 throws StorageObjectException {
341 return selectByWhereClause(whereClause, null, offset);
345 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
346 * Also offset wird der erste Datensatz genommen.
347 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
349 * @param wc where-Clause
350 * @param ob orderBy-Clause
351 * @return EntityList mit den gematchten Entities
352 * @exception StorageObjectException
355 public EntityList selectByWhereClause(String where, String order)
356 throws StorageObjectException {
358 return selectByWhereClause(where, order, 0);
361 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
362 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
364 * @param wc where-Clause
365 * @param ob orderBy-Clause
366 * @param offset ab welchem Datensatz
367 * @return EntityList mit den gematchten Entities
368 * @exception StorageObjectException
371 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
372 throws StorageObjectException {
374 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
379 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
380 * @param wc where-Clause
381 * @param ob orderBy-Clause
382 * @param offset ab welchem Datensatz
383 * @param limit wieviele Datensätze
384 * @return EntityList mit den gematchten Entities
385 * @exception StorageObjectException
388 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
389 throws StorageObjectException {
392 EntityList theReturnList=null;
400 // build sql-statement
401 if (wc != null && wc.length() == 0) {
404 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
405 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
407 selectSql.append(" where ").append(wc);
408 countSql.append(" where ").append(wc);
410 if (ob != null && !(ob.length() == 0)) {
411 selectSql.append(" order by ").append(ob);
413 if (theAdaptor.hasLimit()) {
414 if (limit > -1 && offset > -1) {
415 selectSql.append(" limit ");
416 if (theAdaptor.reverseLimit()) {
417 selectSql.append(limit).append(",").append(offset);
420 selectSql.append(offset).append(",").append(limit);
427 con = getPooledCon();
428 stmt = con.createStatement();
430 if (theAdaptor.hasLimit()) {
431 rs = executeSql(stmt, countSql.toString());
434 count = rs.getInt(1);
436 //nothing in the table: return null
438 freeConnection(con, stmt);
442 theLog.printError("Could not count: " + countSql);
447 rs = executeSql(stmt, selectSql.toString());
449 theReturnList = new EntityList();
450 if (evaluatedMetaData == false) {
451 evalMetaData(rs.getMetaData());
453 Entity theResultEntity;
455 theResultEntity = makeEntityFromResultSet(rs);
456 theReturnList.add(theResultEntity);
462 if (!(theAdaptor.hasLimit()))
464 if (theReturnList != null) {
465 theReturnList.setCount(count);
466 theReturnList.setOffset(offset);
467 theReturnList.setWhere(wc);
468 theReturnList.setOrder(ob);
469 if (offset >= limit) {
470 theReturnList.setPrevBatch(offset - limit);
472 if (offset + offsetCount < count) {
473 theReturnList.setNextBatch(offset + limit);
476 } catch (SQLException sqe) {
477 throwSQLException(sqe, "selectByWhereClause");
479 freeConnection(con, stmt);
481 return theReturnList;
485 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
487 * @param rs Das ResultSetObjekt.
488 * @return Entity Die Entity.
491 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
492 HashMap theResultHash = new HashMap();
493 String theResult = null;
495 Entity returnEntity = null;
497 int size = metadataFields.size();
498 for (int i = 0; i < size; i++) {
499 // alle durchlaufen bis nix mehr da
500 theType = metadataTypes[i];
501 if (theType == java.sql.Types.LONGVARBINARY) {
502 InputStream us = rs.getAsciiStream(i + 1);
504 InputStreamReader is = new InputStreamReader(us);
505 char[] data = new char[32768];
506 StringBuffer theResultString = new StringBuffer();
508 while ((len = is.read(data)) > 0) {
509 theResultString.append(data, 0, len);
512 theResult = theResultString.toString();
519 theResult = getValueAsString(rs, (i + 1), theType);
521 if (theResult != null) {
522 theResultHash.put(metadataFields.get(i), theResult);
525 if (cache != null && theResultHash.containsKey(thePKeyName) &&
526 (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
527 //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
528 System.out.println("containskey: "+cache.containsKey((String)theResultHash.get(thePKeyName)));
529 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
532 if (theEntityClass != null) {
533 returnEntity = (Entity)theEntityClass.newInstance();
534 returnEntity.setValues(theResultHash);
535 returnEntity.setStorage(myselfDatabase);
537 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
538 cache.put(returnEntity.getId(), returnEntity);
542 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
546 catch (IllegalAccessException e) {
547 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
548 } catch (IOException e) {
549 throwStorageObjectException("IOException! -- " + e.toString());
550 } catch (InstantiationException e) {
551 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
552 } catch (SQLException sqe) {
553 throwSQLException(sqe, "makeEntityFromResultSet");
560 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
561 * wird automatisch mit dem aktuellen Datum gefuellt.
564 * @return der Wert des Primary-keys der eingefügten Entity
566 public String insert (Entity theEntity) throws StorageObjectException {
567 String returnId = null;
568 Connection con = null;
569 PreparedStatement pstmt = null;
571 invalidatePopupCache();
573 ArrayList streamedInput = theEntity.streamedInput();
574 StringBuffer f = new StringBuffer();
575 StringBuffer v = new StringBuffer();
576 String aField, aValue;
577 boolean firstField = true;
579 for (int i = 0; i < getFields().size(); i++) {
580 aField = (String)getFields().get(i);
581 if (!aField.equals(thePKeyName)) {
584 if (aField.equals("webdb_create")) {
588 if (streamedInput != null && streamedInput.contains(aField)) {
592 if (theEntity.hasValueForField(aField)) {
593 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
598 // wenn Wert gegeben, dann einbauen
599 if (aValue != null) {
600 if (firstField == false) {
613 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
614 String sql = sqlBuf.toString();
615 theLog.printInfo("INSERT: " + sql);
616 con = getPooledCon();
617 con.setAutoCommit(false);
618 pstmt = con.prepareStatement(sql);
619 if (streamedInput != null) {
620 for (int i = 0; i < streamedInput.size(); i++) {
621 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
622 pstmt.setBytes(i + 1, inputString.getBytes());
625 int ret = pstmt.executeUpdate();
630 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
631 ResultSet rs = pstmt.executeQuery();
633 returnId = rs.getString(1);
634 theEntity.setId(returnId);
635 } catch (SQLException sqe) {
636 throwSQLException(sqe, "insert");
639 con.setAutoCommit(true);
640 } catch (Exception e) {
643 freeConnection(con, pstmt);
649 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
650 * wird automatisch mit dem aktuellen Datum gefuellt.
654 public void update (Entity theEntity) throws StorageObjectException {
655 Connection con = null;
656 PreparedStatement pstmt = null;
657 ArrayList streamedInput = theEntity.streamedInput();
658 String id = theEntity.getId();
660 StringBuffer fv = new StringBuffer();
661 boolean firstField = true;
663 invalidatePopupCache();
664 // build sql statement
665 for (int i = 0; i < getFields().size(); i++) {
666 aField = (String)metadataFields.get(i);
668 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
669 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
670 if (theEntity.hasValueForField(aField)) {
671 if (firstField == false) {
677 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
681 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
683 if (metadataFields.contains("webdb_lastchange")) {
684 sql.append(",webdb_lastchange=NOW()");
686 if (streamedInput != null) {
687 for (int i = 0; i < streamedInput.size(); i++) {
688 sql.append(",").append(streamedInput.get(i)).append("=?");
691 sql.append(" where id=").append(id);
692 theLog.printInfo("UPDATE: " + sql);
695 con = getPooledCon();
696 con.setAutoCommit(false);
697 pstmt = con.prepareStatement(sql.toString());
698 if (streamedInput != null) {
699 for (int i = 0; i < streamedInput.size(); i++) {
700 String inputString = theEntity.getValue((String)streamedInput.get(i));
701 pstmt.setBytes(i + 1, inputString.getBytes());
704 pstmt.executeUpdate();
705 } catch (SQLException sqe) {
706 throwSQLException(sqe, "update");
709 con.setAutoCommit(true);
710 } catch (Exception e) {
713 freeConnection(con, pstmt);
719 * @param id des zu loeschenden Datensatzes
720 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
722 public boolean delete (String id) throws StorageObjectException {
723 Statement stmt = null;
724 Connection con = null;
727 // loeschen des caches
728 invalidatePopupCache();
729 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
731 theLog.printInfo("DELETE " + sql);
733 con = getPooledCon();
734 stmt = con.createStatement();
735 res = stmt.executeUpdate(sql);
736 } catch (SQLException sqe) {
737 throwSQLException(sqe, "delete");
739 freeConnection(con, stmt);
742 theLog.printInfo("CACHE: deleted " + id);
745 return (res > 0) ? true : false;
748 /* noch nicht implementiert.
749 * @return immer false
751 public boolean delete (EntityList theEntityList) {
752 invalidatePopupCache();
757 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
758 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
761 public SimpleList getPopupData () throws StorageObjectException {
766 * Holt Daten fuer Popups.
767 * @param name Name des Feldes.
768 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
769 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
771 public SimpleList getPopupData (String name, boolean hasNullValue)
772 throws StorageObjectException {
773 return getPopupData(name, hasNullValue, null);
777 * Holt Daten fuer Popups.
778 * @param name Name des Feldes.
779 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
780 * @param where Schraenkt die Selektion der Datensaetze ein.
781 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
783 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
784 return getPopupData(name, hasNullValue, where, null);
788 * Holt Daten fuer Popups.
789 * @param name Name des Feldes.
790 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
791 * @param where Schraenkt die Selektion der Datensaetze ein.
792 * @param order Gibt ein Feld als Sortierkriterium an.
793 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
795 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
797 if (hasPopupCache && popupCache != null)
799 SimpleList simpleList = null;
800 Connection con = null;
801 Statement stmt = null;
803 StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
804 if (where != null && !(where.length() == 0))
805 sql.append(" where ").append(where);
806 sql.append(" order by ");
807 if (order != null && !(order.length() == 0))
813 con = getPooledCon();
814 stmt = con.createStatement();
815 ResultSet rs = executeSql(stmt, sql.toString());
817 if (evaluatedMetaData == false)
819 simpleList = new SimpleList();
820 SimpleHash popupDict;
822 popupDict = new SimpleHash();
823 popupDict.put("key", "");
824 popupDict.put("value", "--");
825 simpleList.add(popupDict);
828 popupDict = new SimpleHash();
829 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
830 popupDict.put("value", rs.getString(2));
831 simpleList.add(popupDict);
835 } catch (Exception e) {
836 theLog.printDebugInfo(e.toString());
837 throw new StorageObjectException(e.toString());
839 freeConnection(con, stmt);
842 popupCache = simpleList;
848 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
849 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
850 * Tabellen Verwendung finden.
851 * @return SimpleHash mit den Tabellezeilen.
853 public SimpleHash getHashData () {
854 if (hashCache == null) {
856 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
858 } catch (StorageObjectException e) {
859 theLog.printDebugInfo(e.toString());
865 /* invalidates the popupCache
867 protected void invalidatePopupCache () {
869 /** @todo invalidates toooo much */
875 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
876 * @param stmt Statemnt
877 * @param sql Sql-String
879 * @exception StorageObjectException
881 public ResultSet executeSql (Statement stmt, String sql)
882 throws StorageObjectException, SQLException
885 long startTime = (new java.util.Date()).getTime();
887 rs = stmt.executeQuery(sql);
888 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
891 catch (SQLException e)
893 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
902 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
903 * getimed und geloggt.
904 * @param stmt PreparedStatement mit der SQL-Anweisung
905 * @return Liefert ResultSet des Statements zurueck.
906 * @exception StorageObjectException, SQLException
908 public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
911 long startTime = (new java.util.Date()).getTime();
912 ResultSet rs = stmt.executeQuery();
913 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
918 * returns the number of rows in the table
920 public int getSize(String where)
921 throws SQLException,StorageObjectException
923 long startTime = (new java.util.Date()).getTime();
924 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
925 //theLog.printDebugInfo("trying: "+ sql);
926 Connection con = null;
927 Statement stmt = null;
931 con = getPooledCon();
932 stmt = con.createStatement();
933 ResultSet rs = executeSql(stmt,sql);
935 result = rs.getInt(1);
937 } catch (SQLException e) {
938 theLog.printError(e.toString());
940 freeConnection(con,stmt);
942 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
943 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
947 public int executeUpdate(Statement stmt, String sql)
948 throws StorageObjectException, SQLException
951 long startTime = (new java.util.Date()).getTime();
954 rs = stmt.executeUpdate(sql);
955 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
957 catch (SQLException e)
959 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
966 public int executeUpdate(String sql)
967 throws StorageObjectException, SQLException
970 long startTime = (new java.util.Date()).getTime();
971 Connection con=null;PreparedStatement pstmt=null;
974 pstmt = con.prepareStatement(sql);
975 result = pstmt.executeUpdate();
977 catch (Exception e) {
978 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
979 throw new StorageObjectException("executeUpdate failed: "+e.toString());
981 finally { freeConnection(con,pstmt); }
982 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
987 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
988 * @param md ResultSetMetaData
989 * @exception StorageObjectException
991 private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
992 this.evaluatedMetaData = true;
993 this.metadataFields = new ArrayList();
994 this.metadataLabels = new ArrayList();
995 this.metadataNotNullFields = new ArrayList();
997 int numFields = md.getColumnCount();
998 this.metadataTypes = new int[numFields];
1001 for (int i = 1; i <= numFields; i++) {
1002 aField = md.getColumnName(i);
1003 metadataFields.add(aField);
1004 metadataLabels.add(md.getColumnLabel(i));
1005 aType = md.getColumnType(i);
1006 metadataTypes[i - 1] = aType;
1007 if (aField.equals(thePKeyName)) {
1008 thePKeyType = aType;
1010 if (md.isNullable(i) == md.columnNullable) {
1011 metadataNotNullFields.add(aField);
1014 } catch (SQLException e) {
1015 throwSQLException(e, "evalMetaData");
1020 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1021 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1023 private void get_meta_data () throws StorageObjectException {
1024 Connection con = null;
1025 PreparedStatement pstmt = null;
1026 String sql = "select * from " + theTable + " where 0=1";
1028 con = getPooledCon();
1029 pstmt = con.prepareStatement(sql);
1030 theLog.printInfo("METADATA: " + sql);
1031 ResultSet rs = pstmt.executeQuery();
1032 evalMetaData(rs.getMetaData());
1034 } catch (SQLException e) {
1035 throwSQLException(e, "get_meta_data");
1037 freeConnection(con, pstmt);
1042 * Datenbankverbindung wird geschlossen
1044 public void disconnectPool () throws StorageObjectException {
1046 myBroker.destroy(100);
1047 } catch (SQLException sqe) {
1048 throwSQLException(sqe, "disconnectPool");
1053 * Returns Connection-Object out of the PoolBroker.
1055 * @return Connection Object.
1057 public Connection getPooledCon () throws StorageObjectException {
1058 if (myBroker != null) {
1059 Connection con = myBroker.getConnection();
1063 throw new StorageObjectException("No connection to database!");
1067 * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1069 * @param con Connection zur Datenbank
1070 * @param stmt Statement-Objekt
1072 public void freeConnection (Connection con, Statement stmt)
1073 throws StorageObjectException {
1077 } catch (SQLException e1) {
1078 theLog.printDebugInfo(e1.toString());
1079 throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1082 myBroker.freeConnection(con);
1084 theLog.printDebugInfo("Con was null!");
1085 throw new StorageObjectException("Con was null!");
1090 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1091 * @param sqe SQLException
1092 * @param wo Funktonsname, in der die SQLException geworfen wurde
1093 * @exception StorageObjectException
1095 protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1097 String message = "";
1100 state = sqe.getSQLState();
1101 message = sqe.getMessage();
1102 vendor = sqe.getErrorCode();
1104 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1106 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1110 protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1112 theLog.printError(e.toString()+ wo);
1113 throw new StorageObjectException(wo + e.toString());
1115 theLog.printError(wo);
1116 throw new StorageObjectException(wo);
1122 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1123 * @param message Nachricht mit dem Fehler
1124 * @exception StorageObjectException
1126 void throwStorageObjectException (String message) throws StorageObjectException {
1127 _throwStorageObjectException(null, message);