2 * put your module comment here
10 import freemarker.template.*;
11 import com.javaexchange.dbConnectionBroker.*;
12 import mir.storage.StorageObject;
15 import com.codestudio.sql.*;
16 import com.codestudio.sql.*;
17 import com.codestudio.util.*;
21 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
22 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
23 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
24 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
25 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
31 public class Database implements StorageObject {
33 protected DbConnectionBroker myBroker;
34 protected String theTable;
35 protected String theCoreTable=null;
36 protected String thePKeyName="id";
37 protected int thePKeyType;
38 protected boolean evaluatedMetaData=false;
39 protected ArrayList metadataFields,metadataLabels,metadataNotNullFields;
40 protected int[] metadataTypes;
41 protected Class theEntityClass;
42 protected StorageObject myselfDatabase;
43 protected DatabaseCache cache;
44 protected SimpleList popupCache=null;
45 protected boolean hasPopupCache = false;
46 protected SimpleHash hashCache=null;
47 protected boolean hasTimestamp=true;
48 private String database_driver;
49 private String database_url;
50 private int defaultLimit;
51 protected DatabaseAdaptor theAdaptor;
52 protected Logfile theLog;
55 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
56 * Aus diesem file werden <code>Database.Logfile</code>,
57 * <code>Database.Username</code>,<code>Database.Password</code>,
58 * <code>Database.Host</code> und <code>Database.Adaptor</code>
59 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
62 * @param String confFilename Dateiname der Konfigurationsdatei
64 public Database() throws StorageObjectException {
65 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
66 String database_username=MirConfig.getProp("Database.Username");
67 String database_password=MirConfig.getProp("Database.Password");
68 String database_host=MirConfig.getProp("Database.Host");
69 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
71 theEntityClass = Class.forName("mir.entity.GenericEntity");
72 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
73 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
74 database_driver=theAdaptor.getDriver();
75 database_url=theAdaptor.getURL(database_username,database_password,database_host);
76 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
77 MirConfig.addBroker(database_driver,database_url);
78 //myBroker=MirConfig.getBroker();
81 theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
82 throw new StorageObjectException(e.toString());
87 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
88 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
89 * wird eine mir.entity.GenericEntity erzeugt.
91 * @return Class-Objekt der Entity
93 public java.lang.Class getEntityClass () {
94 return theEntityClass;
98 * Liefert die Standardbeschränkung von select-Statements zurück, also
99 * wieviel Datensätze per Default selektiert werden.
101 * @return Standard-Anzahl der Datensätze
103 public int getLimit () {
108 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
109 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
110 * @return Name des Primary-Keys
112 public String getIdName () {
117 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
119 * @return Name der Tabelle
121 public String getTableName () {
126 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
127 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
128 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
132 public String getCoreTable(){
133 if (theCoreTable!=null) return theCoreTable;
134 else return theTable;
138 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
139 * @return int-Array mit den Typen der Felder
140 * @exception StorageObjectException
142 public int[] getTypes () throws StorageObjectException {
143 if (metadataTypes == null)
145 return metadataTypes;
149 * Liefert eine Liste der Labels der Tabellenfelder
150 * @return ArrayListe mit Labeln
151 * @exception StorageObjectException
153 public ArrayList getLabels () throws StorageObjectException {
154 if (metadataLabels == null)
156 return metadataLabels;
160 * Liefert eine Liste der Felder der Tabelle
161 * @return ArrayList mit Feldern
162 * @exception StorageObjectException
164 public ArrayList getFields () throws StorageObjectException {
165 if (metadataFields == null)
167 return metadataFields;
172 * Gets value out of ResultSet according to type and converts to String
173 * @param inValue Wert aus ResultSet.
174 * @param aType Datenbanktyp.
175 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
176 * dann /unsupported value/
178 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
179 String outValue = null;
183 case java.sql.Types.BIT:
184 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
186 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
187 int out = rs.getInt(valueIndex);
189 outValue = new Integer(out).toString();
191 case java.sql.Types.NUMERIC:
192 long outl = rs.getLong(valueIndex);
194 outValue = new Long(outl).toString();
196 case java.sql.Types.REAL:
197 float tempf = rs.getFloat(valueIndex);
201 int tempf_int = (int)tempf;
202 tempf = (float)tempf_int;
204 outValue = "" + tempf;
205 outValue = outValue.replace('.', ',');
208 case java.sql.Types.DOUBLE:
209 double tempd = rs.getDouble(valueIndex);
213 int tempd_int = (int)tempd;
214 tempd = (double)tempd_int;
216 outValue = "" + tempd;
217 outValue = outValue.replace('.', ',');
220 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
221 outValue = rs.getString(valueIndex);
222 //if (outValue != null)
223 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
225 case java.sql.Types.LONGVARBINARY:
226 outValue = rs.getString(valueIndex);
227 //if (outValue != null)
228 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
230 case java.sql.Types.TIMESTAMP:
231 Timestamp timestamp = (rs.getTimestamp(valueIndex));
233 outValue = timestamp.toString();
237 outValue = "<unsupported value>";
238 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
241 } catch (SQLException e) {
242 throw new StorageObjectException("Could not get Value out of Resultset -- "
250 * select-Operator um einen Datensatz zu bekommen.
251 * @param id Primaerschluessel des Datensatzes.
252 * @return liefert EntityObject des gefundenen Datensatzes oder null.
254 public Entity selectById(String id)
255 throws StorageObjectException {
257 if (id==null||id.equals(""))
258 throw new StorageObjectException("id war null");
259 if (cache != null && (cache.containsKey(id) > -1))
260 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
262 Statement stmt=null;Connection con=getPooledCon();
263 Entity returnEntity=null;
266 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
267 stmt = con.createStatement();
268 rs = executeSql(stmt, selectSql);
270 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
272 returnEntity = makeEntityFromResultSet(rs);
273 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
276 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
278 } catch (SQLException sqe){
279 throwSQLException(sqe,"selectById"); return null;
280 } catch (NumberFormatException e) {
281 theLog.printError("ID ist keine Zahl: " + id);
283 freeConnection(con,stmt);
290 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
291 * @param key Datenbankfeld der Bedingung.
292 * @param value Wert die der key anehmen muss.
293 * @return EntityList mit den gematchten Entities
296 public EntityList selectByFieldValue(String aField, String aValue)
297 throws StorageObjectException {
299 return selectByFieldValue(aField, aValue, 0);
303 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
304 * @param key Datenbankfeld der Bedingung.
305 * @param value Wert die der key anehmen muss.
306 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
307 * @return EntityList mit den gematchten Entities
310 public EntityList selectByFieldValue(String aField, String aValue, int offset)
311 throws StorageObjectException {
313 return selectByWhereClause(aField + "=" + aValue, offset);
318 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
319 * Also offset wird der erste Datensatz genommen.
321 * @param wc where-Clause
322 * @return EntityList mit den gematchten Entities
323 * @exception StorageObjectException
325 public EntityList selectByWhereClause(String where)
326 throws StorageObjectException {
328 return selectByWhereClause(where, 0);
333 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
334 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
336 * @param wc where-Clause
337 * @param offset ab welchem Datensatz.
338 * @return EntityList mit den gematchten Entities
339 * @exception StorageObjectException
341 public EntityList selectByWhereClause(String whereClause, int offset)
342 throws StorageObjectException {
344 return selectByWhereClause(whereClause, null, offset);
348 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
349 * Also offset wird der erste Datensatz genommen.
350 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
352 * @param wc where-Clause
353 * @param ob orderBy-Clause
354 * @return EntityList mit den gematchten Entities
355 * @exception StorageObjectException
358 public EntityList selectByWhereClause(String where, String order)
359 throws StorageObjectException {
361 return selectByWhereClause(where, order, 0);
364 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
365 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
367 * @param wc where-Clause
368 * @param ob orderBy-Clause
369 * @param offset ab welchem Datensatz
370 * @return EntityList mit den gematchten Entities
371 * @exception StorageObjectException
374 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
375 throws StorageObjectException {
377 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
382 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
383 * @param wc where-Clause
384 * @param ob orderBy-Clause
385 * @param offset ab welchem Datensatz
386 * @param limit wieviele Datensätze
387 * @return EntityList mit den gematchten Entities
388 * @exception StorageObjectException
391 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
392 throws StorageObjectException {
395 EntityList theReturnList=null;
403 // build sql-statement
404 if (wc != null && wc.length() == 0) {
407 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
408 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
410 selectSql.append(" where ").append(wc);
411 countSql.append(" where ").append(wc);
413 if (ob != null && !(ob.length() == 0)) {
414 selectSql.append(" order by ").append(ob);
416 if (theAdaptor.hasLimit()) {
417 if (limit > -1 && offset > -1) {
418 selectSql.append(" limit ");
419 if (theAdaptor.reverseLimit()) {
420 selectSql.append(limit).append(",").append(offset);
423 selectSql.append(offset).append(",").append(limit);
430 con = getPooledCon();
431 stmt = con.createStatement();
433 if (theAdaptor.hasLimit()) {
434 rs = executeSql(stmt, countSql.toString());
437 count = rs.getInt(1);
439 //nothing in the table: return null
441 freeConnection(con, stmt);
445 theLog.printError("Could not count: " + countSql);
450 rs = executeSql(stmt, selectSql.toString());
452 theReturnList = new EntityList();
453 if (evaluatedMetaData == false) {
454 evalMetaData(rs.getMetaData());
456 Entity theResultEntity;
458 theResultEntity = makeEntityFromResultSet(rs);
459 theReturnList.add(theResultEntity);
465 if (!(theAdaptor.hasLimit()))
467 if (theReturnList != null) {
468 theReturnList.setCount(count);
469 theReturnList.setOffset(offset);
470 theReturnList.setWhere(wc);
471 theReturnList.setOrder(ob);
472 if (offset >= limit) {
473 theReturnList.setPrevBatch(offset - limit);
475 if (offset + offsetCount < count) {
476 theReturnList.setNextBatch(offset + limit);
479 } catch (SQLException sqe) {
480 throwSQLException(sqe, "selectByWhereClause");
482 freeConnection(con, stmt);
484 return theReturnList;
488 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
490 * @param rs Das ResultSetObjekt.
491 * @return Entity Die Entity.
494 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
495 HashMap theResultHash = new HashMap();
496 String theResult = null;
498 Entity returnEntity = null;
500 int size = metadataFields.size();
501 for (int i = 0; i < size; i++) {
502 // alle durchlaufen bis nix mehr da
503 theType = metadataTypes[i];
504 if (theType == java.sql.Types.LONGVARBINARY) {
505 InputStream us = rs.getAsciiStream(i + 1);
507 InputStreamReader is = new InputStreamReader(us);
508 char[] data = new char[32768];
509 StringBuffer theResultString = new StringBuffer();
511 while ((len = is.read(data)) > 0) {
512 theResultString.append(data, 0, len);
515 theResult = theResultString.toString();
522 theResult = getValueAsString(rs, (i + 1), theType);
524 if (theResult != null) {
525 theResultHash.put(metadataFields.get(i), theResult);
528 if (cache != null && theResultHash.containsKey(thePKeyName) &&
529 (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
530 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);
541 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
544 } catch (IllegalAccessException e) {
545 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
546 } catch (IOException e) {
547 throwStorageObjectException("IOException! -- " + e.toString());
548 } catch (InstantiationException e) {
549 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
550 } catch (SQLException sqe) {
551 throwSQLException(sqe, "makeEntityFromResultSet");
558 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
559 * wird automatisch mit dem aktuellen Datum gefuellt.
562 * @return der Wert des Primary-keys der eingefügten Entity
564 public String insert (Entity theEntity) throws StorageObjectException {
565 String returnId = null;
566 Connection con = null;
567 PreparedStatement pstmt = null;
569 invalidatePopupCache();
571 ArrayList streamedInput = theEntity.streamedInput();
572 StringBuffer f = new StringBuffer();
573 StringBuffer v = new StringBuffer();
574 String aField, aValue;
575 boolean firstField = true;
577 for (int i = 0; i < getFields().size(); i++) {
578 aField = (String)getFields().get(i);
579 if (!aField.equals(thePKeyName)) {
582 if (aField.equals("webdb_create")) {
586 if (streamedInput != null && streamedInput.contains(aField)) {
590 if (theEntity.hasValueForField(aField)) {
591 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
596 // wenn Wert gegeben, dann einbauen
597 if (aValue != null) {
598 if (firstField == false) {
611 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
612 String sql = sqlBuf.toString();
613 theLog.printInfo("INSERT: " + sql);
614 con = getPooledCon();
615 con.setAutoCommit(false);
616 pstmt = con.prepareStatement(sql);
617 if (streamedInput != null) {
618 for (int i = 0; i < streamedInput.size(); i++) {
619 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
620 pstmt.setBytes(i + 1, inputString.getBytes());
623 int ret = pstmt.executeUpdate();
628 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
629 ResultSet rs = pstmt.executeQuery();
631 returnId = rs.getString(1);
632 theEntity.setId(returnId);
633 } catch (SQLException sqe) {
634 throwSQLException(sqe, "insert");
637 con.setAutoCommit(true);
638 } catch (Exception e) {
641 freeConnection(con, pstmt);
647 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
648 * wird automatisch mit dem aktuellen Datum gefuellt.
652 public void update (Entity theEntity) throws StorageObjectException {
653 Connection con = null;
654 PreparedStatement pstmt = null;
655 ArrayList streamedInput = theEntity.streamedInput();
656 String id = theEntity.getId();
658 StringBuffer fv = new StringBuffer();
659 boolean firstField = true;
661 invalidatePopupCache();
662 // build sql statement
663 for (int i = 0; i < getFields().size(); i++) {
664 aField = (String)metadataFields.get(i);
666 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
667 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
668 if (theEntity.hasValueForField(aField)) {
669 if (firstField == false) {
675 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
679 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
681 if (metadataFields.contains("webdb_lastchange")) {
682 sql.append(",webdb_lastchange=NOW()");
684 if (streamedInput != null) {
685 for (int i = 0; i < streamedInput.size(); i++) {
686 sql.append(",").append(streamedInput.get(i)).append("=?");
689 sql.append(" where id=").append(id);
690 theLog.printInfo("UPDATE: " + sql);
693 con = getPooledCon();
694 con.setAutoCommit(false);
695 pstmt = con.prepareStatement(sql.toString());
696 if (streamedInput != null) {
697 for (int i = 0; i < streamedInput.size(); i++) {
698 String inputString = theEntity.getValue((String)streamedInput.get(i));
699 pstmt.setBytes(i + 1, inputString.getBytes());
702 pstmt.executeUpdate();
703 } catch (SQLException sqe) {
704 throwSQLException(sqe, "update");
707 con.setAutoCommit(true);
708 } catch (Exception e) {
711 freeConnection(con, pstmt);
717 * @param id des zu loeschenden Datensatzes
718 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
720 public boolean delete (String id) throws StorageObjectException {
721 Statement stmt = null;
722 Connection con = null;
725 // loeschen des caches
726 invalidatePopupCache();
727 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
729 theLog.printInfo("DELETE " + sql);
731 con = getPooledCon();
732 stmt = con.createStatement();
733 res = stmt.executeUpdate(sql);
734 } catch (SQLException sqe) {
735 throwSQLException(sqe, "delete");
737 freeConnection(con, stmt);
740 theLog.printInfo("CACHE: deleted " + id);
743 return (res > 0) ? true : false;
746 /* noch nicht implementiert.
747 * @return immer false
749 public boolean delete (EntityList theEntityList) {
750 invalidatePopupCache();
755 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
756 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
759 public SimpleList getPopupData () throws StorageObjectException {
764 * Holt Daten fuer Popups.
765 * @param name Name des Feldes.
766 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
767 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
769 public SimpleList getPopupData (String name, boolean hasNullValue)
770 throws StorageObjectException {
771 return getPopupData(name, hasNullValue, null);
775 * Holt Daten fuer Popups.
776 * @param name Name des Feldes.
777 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
778 * @param where Schraenkt die Selektion der Datensaetze ein.
779 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
781 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
782 return getPopupData(name, hasNullValue, where, null);
786 * Holt Daten fuer Popups.
787 * @param name Name des Feldes.
788 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
789 * @param where Schraenkt die Selektion der Datensaetze ein.
790 * @param order Gibt ein Feld als Sortierkriterium an.
791 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
793 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
795 if (hasPopupCache && popupCache != null)
797 SimpleList simpleList = null;
798 Connection con = null;
799 Statement stmt = null;
801 StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
802 if (where != null && !(where.length() == 0))
803 sql.append(" where ").append(where);
804 sql.append(" order by ");
805 if (order != null && !(order.length() == 0))
811 con = getPooledCon();
812 stmt = con.createStatement();
813 ResultSet rs = executeSql(stmt, sql.toString());
815 if (evaluatedMetaData == false)
817 simpleList = new SimpleList();
818 SimpleHash popupDict;
820 popupDict = new SimpleHash();
821 popupDict.put("key", "");
822 popupDict.put("value", "--");
823 simpleList.add(popupDict);
826 popupDict = new SimpleHash();
827 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
828 popupDict.put("value", rs.getString(2));
829 simpleList.add(popupDict);
833 } catch (Exception e) {
834 theLog.printDebugInfo(e.toString());
835 throw new StorageObjectException(e.toString());
837 freeConnection(con, stmt);
840 popupCache = simpleList;
846 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
847 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
848 * Tabellen Verwendung finden.
849 * @return SimpleHash mit den Tabellezeilen.
851 public SimpleHash getHashData () {
852 if (hashCache == null) {
854 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
856 } catch (StorageObjectException e) {
857 theLog.printDebugInfo(e.toString());
863 /* invalidates the popupCache
865 protected void invalidatePopupCache () {
867 /** @todo invalidates toooo much */
873 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
874 * @param stmt Statemnt
875 * @param sql Sql-String
877 * @exception StorageObjectException
879 public ResultSet executeSql (Statement stmt, String sql)
880 throws StorageObjectException, SQLException
883 long startTime = (new java.util.Date()).getTime();
885 rs = stmt.executeQuery(sql);
886 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
889 catch (SQLException e)
891 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
900 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
901 * getimed und geloggt.
902 * @param stmt PreparedStatement mit der SQL-Anweisung
903 * @return Liefert ResultSet des Statements zurueck.
904 * @exception StorageObjectException, SQLException
906 public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
909 long startTime = (new java.util.Date()).getTime();
910 ResultSet rs = stmt.executeQuery();
911 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
916 * returns the number of rows in the table
918 public int getSize(String where)
919 throws SQLException,StorageObjectException
921 long startTime = (new java.util.Date()).getTime();
922 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
923 //theLog.printDebugInfo("trying: "+ sql);
924 Connection con = null;
925 Statement stmt = null;
929 con = getPooledCon();
930 stmt = con.createStatement();
931 ResultSet rs = executeSql(stmt,sql);
933 result = rs.getInt(1);
935 } catch (SQLException e) {
936 theLog.printError(e.toString());
938 freeConnection(con,stmt);
940 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
941 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
945 public int executeUpdate(Statement stmt, String sql)
946 throws StorageObjectException, SQLException
949 long startTime = (new java.util.Date()).getTime();
952 rs = stmt.executeUpdate(sql);
953 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
955 catch (SQLException e)
957 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
964 public int executeUpdate(String sql)
965 throws StorageObjectException, SQLException
968 long startTime = (new java.util.Date()).getTime();
969 Connection con=null;PreparedStatement pstmt=null;
972 pstmt = con.prepareStatement(sql);
973 result = pstmt.executeUpdate();
975 catch (Exception e) {
976 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
977 throw new StorageObjectException("executeUpdate failed: "+e.toString());
979 finally { freeConnection(con,pstmt); }
980 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
985 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
986 * @param md ResultSetMetaData
987 * @exception StorageObjectException
989 private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
990 this.evaluatedMetaData = true;
991 this.metadataFields = new ArrayList();
992 this.metadataLabels = new ArrayList();
993 this.metadataNotNullFields = new ArrayList();
995 int numFields = md.getColumnCount();
996 this.metadataTypes = new int[numFields];
999 for (int i = 1; i <= numFields; i++) {
1000 aField = md.getColumnName(i);
1001 metadataFields.add(aField);
1002 metadataLabels.add(md.getColumnLabel(i));
1003 aType = md.getColumnType(i);
1004 metadataTypes[i - 1] = aType;
1005 if (aField.equals(thePKeyName)) {
1006 thePKeyType = aType;
1008 if (md.isNullable(i) == md.columnNullable) {
1009 metadataNotNullFields.add(aField);
1012 } catch (SQLException e) {
1013 throwSQLException(e, "evalMetaData");
1018 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1019 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1021 private void get_meta_data () throws StorageObjectException {
1022 Connection con = null;
1023 PreparedStatement pstmt = null;
1024 String sql = "select * from " + theTable + " where 0=1";
1026 con = getPooledCon();
1027 pstmt = con.prepareStatement(sql);
1028 theLog.printInfo("METADATA: " + sql);
1029 ResultSet rs = pstmt.executeQuery();
1030 evalMetaData(rs.getMetaData());
1032 } catch (SQLException e) {
1033 throwSQLException(e, "get_meta_data");
1035 freeConnection(con, pstmt);
1040 * Datenbankverbindung wird geschlossen
1042 public void disconnectPool () throws StorageObjectException {
1044 myBroker.destroy(100);
1045 } catch (SQLException sqe) {
1046 throwSQLException(sqe, "disconnectPool");
1050 public Connection getPooledCon() throws StorageObjectException {
1052 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1053 } catch (Exception e){
1054 e.printStackTrace();
1055 throw new StorageObjectException("Could not find the PoolMan Driver"+e.toString());
1057 Connection con = null;
1059 con = SQLManager.getInstance().requestConnection();
1060 } catch(SQLException e){
1061 e.printStackTrace();
1062 throw new StorageObjectException("No connection to the database");
1068 * Returns Connection-Object out of the PoolBroker.
1070 * @return Connection Object.
1072 public Connection getPooledCon2() throws StorageObjectException {
1073 if (myBroker != null) {
1074 Connection con = myBroker.getConnection();
1078 throw new StorageObjectException("No connection to database!");
1082 * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1084 * @param con Connection zur Datenbank
1085 * @param stmt Statement-Objekt
1087 public void freeConnection2 (Connection con, Statement stmt)
1088 throws StorageObjectException {
1092 } catch (SQLException e1) {
1093 theLog.printDebugInfo(e1.toString());
1094 throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1097 myBroker.freeConnection(con);
1099 theLog.printDebugInfo("Con was null!");
1100 throw new StorageObjectException("Con was null!");
1104 public void freeConnection (Connection con, Statement stmt)
1105 throws StorageObjectException {
1106 SQLManager.getInstance().closeStatement(stmt);
1107 SQLManager.getInstance().returnConnection(con);
1111 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1112 * @param sqe SQLException
1113 * @param wo Funktonsname, in der die SQLException geworfen wurde
1114 * @exception StorageObjectException
1116 protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1118 String message = "";
1121 state = sqe.getSQLState();
1122 message = sqe.getMessage();
1123 vendor = sqe.getErrorCode();
1125 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1127 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1131 protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1133 theLog.printError(e.toString()+ wo);
1134 throw new StorageObjectException(wo + e.toString());
1136 theLog.printError(wo);
1137 throw new StorageObjectException(wo);
1143 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1144 * @param message Nachricht mit dem Fehler
1145 * @exception StorageObjectException
1147 void throwStorageObjectException (String message) throws StorageObjectException {
1148 _throwStorageObjectException(null, message);