2 * put your module comment here
10 import freemarker.template.*;
11 import com.codestudio.sql.*;
12 import com.codestudio.util.*;
14 import mir.storage.StorageObject;
15 import mir.storage.store.*;
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 String theTable;
34 protected String theCoreTable=null;
35 protected String thePKeyName="id";
36 protected int thePKeyType, thePKeyIndex;
37 protected boolean evaluatedMetaData=false;
38 protected ArrayList metadataFields,metadataLabels,
39 metadataNotNullFields;
40 protected int[] metadataTypes;
41 protected Class theEntityClass;
42 protected StorageObject myselfDatabase;
43 protected SimpleList popupCache=null;
44 protected boolean hasPopupCache = false;
45 protected SimpleHash hashCache=null;
46 protected boolean hasTimestamp=true;
47 private String database_driver, database_url;
48 private int defaultLimit;
49 protected DatabaseAdaptor theAdaptor;
50 protected Logfile theLog;
51 private static Class GENERIC_ENTITY_CLASS=null,
52 STORABLE_OBJECT_ENTITY_CLASS=null;
53 private static SimpleHash POPUP_EMTYLINE=new SimpleHash();
54 protected static final ObjectStore o_store=ObjectStore.getInstance();
57 // always same object saves a little space
58 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
60 GENERIC_ENTITY_CLASS = Class.forName("mir.entity.GenericEntity");
61 STORABLE_OBJECT_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
64 System.err.println("FATAL: Database.java could not initialize" + e.toString());
70 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
71 * Aus diesem file werden <code>Database.Logfile</code>,
72 * <code>Database.Username</code>,<code>Database.Password</code>,
73 * <code>Database.Host</code> und <code>Database.Adaptor</code>
74 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
77 * @param String confFilename Dateiname der Konfigurationsdatei
79 public Database() throws StorageObjectException {
80 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
81 MirConfig.getProp("Database.Logfile"));
82 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
83 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
85 theEntityClass = GENERIC_ENTITY_CLASS;
86 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
87 } catch (Exception e){
88 theLog.printError("Error in Database() constructor with "+
89 theAdaptorName + " -- " +e.toString());
90 throw new StorageObjectException("Error in Database() constructor with "
93 /*String database_username=MirConfig.getProp("Database.Username");
94 String database_password=MirConfig.getProp("Database.Password");
95 String database_host=MirConfig.getProp("Database.Host");
97 database_driver=theAdaptor.getDriver();
98 database_url=theAdaptor.getURL(database_username,database_password,
100 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
102 MirConfig.addBroker(database_driver,database_url);
103 //myBroker=MirConfig.getBroker();
108 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
109 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
110 * wird eine mir.entity.GenericEntity erzeugt.
112 * @return Class-Objekt der Entity
114 public java.lang.Class getEntityClass () {
115 return theEntityClass;
119 * Liefert die Standardbeschränkung von select-Statements zurück, also
120 * wieviel Datensätze per Default selektiert werden.
122 * @return Standard-Anzahl der Datensätze
124 public int getLimit () {
129 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
130 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
131 * @return Name des Primary-Keys
133 public String getIdName () {
138 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
140 * @return Name der Tabelle
142 public String getTableName () {
147 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
148 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
150 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
154 public String getCoreTable(){
155 if (theCoreTable!=null) return theCoreTable;
156 else return theTable;
160 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
161 * @return int-Array mit den Typen der Felder
162 * @exception StorageObjectException
164 public int[] getTypes () throws StorageObjectException {
165 if (metadataTypes == null)
167 return metadataTypes;
171 * Liefert eine Liste der Labels der Tabellenfelder
172 * @return ArrayListe mit Labeln
173 * @exception StorageObjectException
175 public ArrayList getLabels () throws StorageObjectException {
176 if (metadataLabels == null)
178 return metadataLabels;
182 * Liefert eine Liste der Felder der Tabelle
183 * @return ArrayList mit Feldern
184 * @exception StorageObjectException
186 public ArrayList getFields () throws StorageObjectException {
187 if (metadataFields == null)
189 return metadataFields;
194 * Gets value out of ResultSet according to type and converts to String
195 * @param inValue Wert aus ResultSet.
196 * @param aType Datenbanktyp.
197 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
198 * dann /unsupported value/
200 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
201 String outValue = null;
205 case java.sql.Types.BIT:
206 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
208 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
209 int out = rs.getInt(valueIndex);
211 outValue = new Integer(out).toString();
213 case java.sql.Types.NUMERIC:
214 /** @todo Numeric can be float or double depending upon
215 * metadata.getScale() / especially with oracle */
216 long outl = rs.getLong(valueIndex);
218 outValue = new Long(outl).toString();
220 case java.sql.Types.REAL:
221 float tempf = rs.getFloat(valueIndex);
225 int tempf_int = (int)tempf;
226 tempf = (float)tempf_int;
228 outValue = "" + tempf;
229 outValue = outValue.replace('.', ',');
232 case java.sql.Types.DOUBLE:
233 double tempd = rs.getDouble(valueIndex);
237 int tempd_int = (int)tempd;
238 tempd = (double)tempd_int;
240 outValue = "" + tempd;
241 outValue = outValue.replace('.', ',');
244 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
245 outValue = rs.getString(valueIndex);
246 //if (outValue != null)
247 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
249 case java.sql.Types.LONGVARBINARY:
250 outValue = rs.getString(valueIndex);
251 //if (outValue != null)
252 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
254 case java.sql.Types.TIMESTAMP:
255 Timestamp timestamp = (rs.getTimestamp(valueIndex));
257 outValue = timestamp.toString();
261 outValue = "<unsupported value>";
262 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
265 } catch (SQLException e) {
266 throw new StorageObjectException("Could not get Value out of Resultset -- "
274 * select-Operator um einen Datensatz zu bekommen.
275 * @param id Primaerschluessel des Datensatzes.
276 * @return liefert EntityObject des gefundenen Datensatzes oder null.
278 public Entity selectById(String id) throws StorageObjectException
280 if (id==null||id.equals(""))
281 throw new StorageObjectException("id war null");
283 // ask object store for object
284 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
285 String uniqueId = id;
286 if ( theEntityClass.equals(StorableObjectEntity.class) )
287 uniqueId+="@"+theTable;
288 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
289 theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
290 Entity hit = (Entity)o_store.use(search_sid);
291 if ( hit!=null ) return hit;
294 Statement stmt=null;Connection con=getPooledCon();
295 Entity returnEntity=null;
298 /** @todo better prepared statement */
299 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
300 stmt = con.createStatement();
301 rs = executeSql(stmt, selectSql);
303 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
305 returnEntity = makeEntityFromResultSet(rs);
306 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
310 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
313 catch (SQLException sqe){
314 throwSQLException(sqe,"selectById"); return null;
316 catch (NumberFormatException e) {
317 theLog.printError("ID ist keine Zahl: " + id);
319 finally { freeConnection(con,stmt); }
321 /** @todo OS: Entity should be saved in ostore */
327 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
328 * @param key Datenbankfeld der Bedingung.
329 * @param value Wert die der key anehmen muss.
330 * @return EntityList mit den gematchten Entities
332 public EntityList selectByFieldValue(String aField, String aValue)
333 throws StorageObjectException
335 return selectByFieldValue(aField, aValue, 0);
339 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
340 * @param key Datenbankfeld der Bedingung.
341 * @param value Wert die der key anehmen muss.
342 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
343 * @return EntityList mit den gematchten Entities
345 public EntityList selectByFieldValue(String aField, String aValue, int offset)
346 throws StorageObjectException
348 return selectByWhereClause(aField + "=" + aValue, offset);
353 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
354 * Also offset wird der erste Datensatz genommen.
356 * @param wc where-Clause
357 * @return EntityList mit den gematchten Entities
358 * @exception StorageObjectException
360 public EntityList selectByWhereClause(String where)
361 throws StorageObjectException
363 return selectByWhereClause(where, 0);
368 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
369 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
371 * @param wc where-Clause
372 * @param offset ab welchem Datensatz.
373 * @return EntityList mit den gematchten Entities
374 * @exception StorageObjectException
376 public EntityList selectByWhereClause(String whereClause, int offset)
377 throws StorageObjectException
379 return selectByWhereClause(whereClause, null, offset);
384 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
385 * Also offset wird der erste Datensatz genommen.
386 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
388 * @param wc where-Clause
389 * @param ob orderBy-Clause
390 * @return EntityList mit den gematchten Entities
391 * @exception StorageObjectException
394 public EntityList selectByWhereClause(String where, String order)
395 throws StorageObjectException {
396 return selectByWhereClause(where, order, 0);
401 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
402 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
404 * @param wc where-Clause
405 * @param ob orderBy-Clause
406 * @param offset ab welchem Datensatz
407 * @return EntityList mit den gematchten Entities
408 * @exception StorageObjectException
411 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
412 throws StorageObjectException {
413 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
418 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
419 * @param wc where-Clause
420 * @param ob orderBy-Clause
421 * @param offset ab welchem Datensatz
422 * @param limit wieviele Datensätze
423 * @return EntityList mit den gematchten Entities
424 * @exception StorageObjectException
427 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
428 throws StorageObjectException
431 // check o_store for entitylist
432 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
433 StoreIdentifier search_sid =
434 new StoreIdentifier( theEntityClass,
435 StoreContainerType.STOC_TYPE_ENTITYLIST,
436 StoreUtil.getEntityListUniqueIdentifierFor(wc,ob,offset,limit) );
437 EntityList hit = (EntityList)o_store.use(search_sid);
439 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
445 EntityList theReturnList=null;
446 Connection con=null; Statement stmt=null;
448 int offsetCount = 0, count=0;
450 // build sql-statement
452 /** @todo count sql string should only be assembled if we really count
453 * see below at the end of method //rk */
455 if (wc != null && wc.length() == 0) {
458 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
459 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
461 selectSql.append(" where ").append(wc);
462 countSql.append(" where ").append(wc);
464 if (ob != null && !(ob.length() == 0)) {
465 selectSql.append(" order by ").append(ob);
467 if (theAdaptor.hasLimit()) {
468 if (limit > -1 && offset > -1) {
469 selectSql.append(" limit ");
470 if (theAdaptor.reverseLimit()) {
471 selectSql.append(limit).append(",").append(offset);
474 selectSql.append(offset).append(",").append(limit);
481 con = getPooledCon();
482 stmt = con.createStatement();
485 rs = executeSql(stmt, selectSql.toString());
487 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
489 theReturnList = new EntityList();
490 Entity theResultEntity;
492 theResultEntity = makeEntityFromResultSet(rs);
493 theReturnList.add(theResultEntity);
499 // making entitylist infos
500 if (!(theAdaptor.hasLimit())) count = offsetCount;
502 if (theReturnList != null) {
503 // now we decide if we have to know an overall count...
505 if (limit > -1 && offset > -1) {
506 if (offsetCount==limit) {
507 /** @todo counting should be deffered to entitylist
508 * getSize() should be used */
509 rs = executeSql(stmt, countSql.toString());
511 if ( rs.next() ) count = rs.getInt(1);
514 else theLog.printError("Could not count: " + countSql);
517 theReturnList.setCount(count);
518 theReturnList.setOffset(offset);
519 theReturnList.setWhere(wc);
520 theReturnList.setOrder(ob);
521 theReturnList.setEntityClass(theEntityClass);
522 theReturnList.setLimit(limit);
523 if ( offset >= limit )
524 theReturnList.setPrevBatch(offset - limit);
525 if ( offset+offsetCount < count )
526 theReturnList.setNextBatch(offset + limit);
527 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
528 StoreIdentifier sid=theReturnList.getStoreIdentifier();
529 theLog.printDebugInfo("CACHE (add): " + sid.toString());
534 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
535 finally { freeConnection(con, stmt); }
537 return theReturnList;
542 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
544 * @param rs Das ResultSetObjekt.
545 * @return Entity Die Entity.
547 private Entity makeEntityFromResultSet (ResultSet rs)
548 throws StorageObjectException
550 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
551 HashMap theResultHash = new HashMap();
552 String theResult = null;
554 Entity returnEntity = null;
556 int size = metadataFields.size();
557 for (int i = 0; i < size; i++) {
558 // alle durchlaufen bis nix mehr da
559 theType = metadataTypes[i];
560 if (theType == java.sql.Types.LONGVARBINARY) {
561 InputStream us = rs.getAsciiStream(i + 1);
563 InputStreamReader is = new InputStreamReader(us);
564 char[] data = new char[32768];
565 StringBuffer theResultString = new StringBuffer();
567 while ((len = is.read(data)) > 0) {
568 theResultString.append(data, 0, len);
571 theResult = theResultString.toString();
578 theResult = getValueAsString(rs, (i + 1), theType);
580 if (theResult != null) {
581 theResultHash.put(metadataFields.get(i), theResult);
584 if (theEntityClass != null) {
585 returnEntity = (Entity)theEntityClass.newInstance();
586 returnEntity.setValues(theResultHash);
587 returnEntity.setStorage(myselfDatabase);
588 if ( returnEntity instanceof StorableObject ) {
589 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
590 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
593 throwStorageObjectException("Internal Error: theEntityClass not set!");
595 } catch (IllegalAccessException e) {
596 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
597 } catch (IOException e) {
598 throwStorageObjectException("IOException! -- " + e.toString());
599 } catch (InstantiationException e) {
600 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
601 } catch (SQLException sqe) {
602 throwSQLException(sqe, "makeEntityFromResultSet");
609 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
610 * wird automatisch mit dem aktuellen Datum gefuellt.
613 * @return der Wert des Primary-keys der eingefügten Entity
615 public String insert (Entity theEntity) throws StorageObjectException {
616 String returnId = null;
617 Connection con = null;
618 PreparedStatement pstmt = null;
620 invalidatePopupCache();
621 /** @todo OS: if Entity is StorableObject, invalidate in ObjectStore
622 * careful: Entity has no id yet! */
624 ArrayList streamedInput = theEntity.streamedInput();
625 StringBuffer f = new StringBuffer();
626 StringBuffer v = new StringBuffer();
627 String aField, aValue;
628 boolean firstField = true;
630 for (int i = 0; i < getFields().size(); i++) {
631 aField = (String)getFields().get(i);
632 if (!aField.equals(thePKeyName)) {
635 if (aField.equals("webdb_create")) {
639 if (streamedInput != null && streamedInput.contains(aField)) {
643 if (theEntity.hasValueForField(aField)) {
644 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
649 // wenn Wert gegeben, dann einbauen
650 if (aValue != null) {
651 if (firstField == false) {
664 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
665 String sql = sqlBuf.toString();
666 theLog.printInfo("INSERT: " + sql);
667 con = getPooledCon();
668 con.setAutoCommit(false);
669 pstmt = con.prepareStatement(sql);
670 if (streamedInput != null) {
671 for (int i = 0; i < streamedInput.size(); i++) {
672 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
673 pstmt.setBytes(i + 1, inputString.getBytes());
676 int ret = pstmt.executeUpdate();
681 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
682 ResultSet rs = pstmt.executeQuery();
684 returnId = rs.getString(1);
685 theEntity.setId(returnId);
686 } catch (SQLException sqe) {
687 throwSQLException(sqe, "insert");
690 con.setAutoCommit(true);
691 } catch (Exception e) {
694 freeConnection(con, pstmt);
700 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
701 * wird automatisch mit dem aktuellen Datum gefuellt.
705 public void update (Entity theEntity) throws StorageObjectException
707 Connection con = null; PreparedStatement pstmt = null;
708 /** @todo this is stupid: why do we prepare statement, when we
709 * throw it away afterwards. should be regular statement
710 * update/insert could better be one routine called save()
711 * that chooses to either insert or update depending if we
712 * have a primary key in the entity. i don't know if we
713 * still need the streamed input fields. // rk */
715 /** @todo extension: check if Entity did change, otherwise we don't need */
716 /** @todo OS: invalidate in Ostore if Entity is StorableObject */
718 ArrayList streamedInput = theEntity.streamedInput();
719 String id = theEntity.getId();
721 StringBuffer fv = new StringBuffer();
722 boolean firstField = true;
724 invalidatePopupCache();
725 // build sql statement
726 for (int i = 0; i < getFields().size(); i++) {
727 aField = (String)metadataFields.get(i);
729 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
730 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
731 if (theEntity.hasValueForField(aField)) {
732 if (firstField == false) {
738 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
742 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
744 if (metadataFields.contains("webdb_lastchange")) {
745 sql.append(",webdb_lastchange=NOW()");
747 if (streamedInput != null) {
748 for (int i = 0; i < streamedInput.size(); i++) {
749 sql.append(",").append(streamedInput.get(i)).append("=?");
752 sql.append(" where id=").append(id);
753 theLog.printInfo("UPDATE: " + sql);
756 con = getPooledCon();
757 con.setAutoCommit(false);
758 pstmt = con.prepareStatement(sql.toString());
759 if (streamedInput != null) {
760 for (int i = 0; i < streamedInput.size(); i++) {
761 String inputString = theEntity.getValue((String)streamedInput.get(i));
762 pstmt.setBytes(i + 1, inputString.getBytes());
765 pstmt.executeUpdate();
766 } catch (SQLException sqe) {
767 throwSQLException(sqe, "update");
770 con.setAutoCommit(true);
771 } catch (Exception e) {
774 freeConnection(con, pstmt);
780 * @param id des zu loeschenden Datensatzes
781 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
783 public boolean delete (String id) throws StorageObjectException {
785 invalidatePopupCache();
786 // ostore send notification
787 if (StoreUtil.implementsStorableObject(theEntityClass) ) {
788 theLog.printInfo("CACHE: (del) " + id);
789 StoreIdentifier search_sid =
790 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, id);
791 o_store.invalidate(search_sid);
794 /** @todo could be prepared Statement */
795 Statement stmt = null; Connection con = null;
797 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
798 theLog.printInfo("DELETE " + sql);
800 con = getPooledCon(); stmt = con.createStatement();
801 res = stmt.executeUpdate(sql);
803 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
804 finally { freeConnection(con, stmt); }
806 return (res > 0) ? true : false;
809 /* noch nicht implementiert.
810 * @return immer false
812 public boolean delete (EntityList theEntityList) {
813 invalidatePopupCache();
818 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
819 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
822 public SimpleList getPopupData () throws StorageObjectException {
827 * Holt Daten fuer Popups.
828 * @param name Name des Feldes.
829 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
830 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
832 public SimpleList getPopupData (String name, boolean hasNullValue)
833 throws StorageObjectException {
834 return getPopupData(name, hasNullValue, null);
838 * Holt Daten fuer Popups.
839 * @param name Name des Feldes.
840 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
841 * @param where Schraenkt die Selektion der Datensaetze ein.
842 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
844 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
845 return getPopupData(name, hasNullValue, where, null);
849 * Holt Daten fuer Popups.
850 * @param name Name des Feldes.
851 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
852 * @param where Schraenkt die Selektion der Datensaetze ein.
853 * @param order Gibt ein Feld als Sortierkriterium an.
854 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
856 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
858 if (hasPopupCache && popupCache != null)
860 SimpleList simpleList = null;
861 Connection con = null;
862 Statement stmt = null;
864 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
865 .append(",").append(name).append(" from ")
867 if (where != null && !(where.length() == 0))
868 sql.append(" where ").append(where);
869 sql.append(" order by ");
870 if (order != null && !(order.length() == 0))
876 con = getPooledCon();
877 } catch (Exception e) {
878 throw new StorageObjectException(e.toString());
881 stmt = con.createStatement();
882 ResultSet rs = executeSql(stmt, sql.toString());
885 if (!evaluatedMetaData) get_meta_data();
886 simpleList = new SimpleList();
887 // if popup has null-selector
888 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
890 SimpleHash popupDict;
892 popupDict = new SimpleHash();
893 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
894 popupDict.put("value", rs.getString(2));
895 simpleList.add(popupDict);
899 } catch (Exception e) {
900 theLog.printError("getPopupData: "+e.toString());
901 throw new StorageObjectException(e.toString());
903 freeConnection(con, stmt);
906 if (hasPopupCache) popupCache = simpleList;
911 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
912 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
913 * Tabellen Verwendung finden.
914 * @return SimpleHash mit den Tabellezeilen.
916 public SimpleHash getHashData () {
917 /** @todo dangerous! this should have a flag to be enabled, otherwise
918 * very big Hashes could be returned */
919 if (hashCache == null) {
921 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
923 } catch (StorageObjectException e) {
924 theLog.printDebugInfo(e.toString());
930 /* invalidates the popupCache
932 protected void invalidatePopupCache () {
933 /** @todo invalidates toooo much */
939 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
940 * @param stmt Statemnt
941 * @param sql Sql-String
943 * @exception StorageObjectException
945 public ResultSet executeSql (Statement stmt, String sql)
946 throws StorageObjectException, SQLException
948 long startTime = System.currentTimeMillis();
951 rs = stmt.executeQuery(sql);
952 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
955 catch (SQLException e)
957 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
958 - startTime) + "ms. for: "+ sql);
966 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
967 * getimed und geloggt.
968 * @param stmt PreparedStatement mit der SQL-Anweisung
969 * @return Liefert ResultSet des Statements zurueck.
970 * @exception StorageObjectException, SQLException
972 public ResultSet executeSql (PreparedStatement stmt)
973 throws StorageObjectException, SQLException {
975 long startTime = (new java.util.Date()).getTime();
976 ResultSet rs = stmt.executeQuery();
977 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
982 * returns the number of rows in the table
984 public int getSize(String where)
985 throws SQLException,StorageObjectException
987 long startTime = System.currentTimeMillis();
988 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
989 Connection con = null;
990 Statement stmt = null;
994 con = getPooledCon();
995 stmt = con.createStatement();
996 ResultSet rs = executeSql(stmt,sql);
998 result = rs.getInt(1);
1000 } catch (SQLException e) {
1001 theLog.printError(e.toString());
1003 freeConnection(con,stmt);
1005 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1006 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1011 public int executeUpdate(Statement stmt, String sql)
1012 throws StorageObjectException, SQLException
1015 long startTime = (new java.util.Date()).getTime();
1018 rs = stmt.executeUpdate(sql);
1019 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1022 catch (SQLException e)
1024 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1025 - startTime) + "ms. for: "+ sql);
1031 public int executeUpdate(String sql)
1032 throws StorageObjectException, SQLException
1035 long startTime = (new java.util.Date()).getTime();
1036 Connection con=null;PreparedStatement pstmt=null;
1039 pstmt = con.prepareStatement(sql);
1040 result = pstmt.executeUpdate();
1042 catch (Exception e) {
1043 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1044 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1046 finally { freeConnection(con,pstmt); }
1047 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1053 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1054 * @param md ResultSetMetaData
1055 * @exception StorageObjectException
1057 private void evalMetaData (ResultSetMetaData md)
1058 throws StorageObjectException {
1060 this.evaluatedMetaData = true;
1061 this.metadataFields = new ArrayList();
1062 this.metadataLabels = new ArrayList();
1063 this.metadataNotNullFields = new ArrayList();
1065 int numFields = md.getColumnCount();
1066 this.metadataTypes = new int[numFields];
1069 for (int i = 1; i <= numFields; i++) {
1070 aField = md.getColumnName(i);
1071 metadataFields.add(aField);
1072 metadataLabels.add(md.getColumnLabel(i));
1073 aType = md.getColumnType(i);
1074 metadataTypes[i - 1] = aType;
1075 if (aField.equals(thePKeyName)) {
1076 thePKeyType = aType; thePKeyIndex = i;
1078 if (md.isNullable(i) == md.columnNullable) {
1079 metadataNotNullFields.add(aField);
1082 } catch (SQLException e) {
1083 throwSQLException(e, "evalMetaData");
1088 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1089 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1091 private void get_meta_data () throws StorageObjectException {
1092 Connection con = null;
1093 PreparedStatement pstmt = null;
1094 String sql = "select * from " + theTable + " where 0=1";
1096 con = getPooledCon();
1097 pstmt = con.prepareStatement(sql);
1098 theLog.printInfo("METADATA: " + sql);
1099 ResultSet rs = pstmt.executeQuery();
1100 evalMetaData(rs.getMetaData());
1102 } catch (SQLException e) {
1103 throwSQLException(e, "get_meta_data");
1105 freeConnection(con, pstmt);
1110 public Connection getPooledCon() throws StorageObjectException {
1111 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1113 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1114 } catch (Exception e){
1115 throw new StorageObjectException("Could not find the PoolMan Driver"
1118 Connection con = null;
1120 con = SQLManager.getInstance().requestConnection();
1121 } catch(SQLException e){
1122 theLog.printError("could not connect to the database "+e.toString());
1123 System.err.println("could not connect to the database "+e.toString());
1124 throw new StorageObjectException("Could not connect to the database"+
1130 public void freeConnection (Connection con, Statement stmt)
1131 throws StorageObjectException {
1132 SQLManager.getInstance().closeStatement(stmt);
1133 SQLManager.getInstance().returnConnection(con);
1137 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1138 * @param sqe SQLException
1139 * @param wo Funktonsname, in der die SQLException geworfen wurde
1140 * @exception StorageObjectException
1142 protected void throwSQLException (SQLException sqe, String wo)
1143 throws StorageObjectException {
1145 String message = "";
1148 state = sqe.getSQLState();
1149 message = sqe.getMessage();
1150 vendor = sqe.getErrorCode();
1152 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1154 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1158 protected void _throwStorageObjectException (Exception e, String wo)
1159 throws StorageObjectException {
1161 theLog.printError(e.toString()+ wo);
1162 throw new StorageObjectException(wo + e.toString());
1164 theLog.printError(wo);
1165 throw new StorageObjectException(wo);
1171 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1172 * eine StorageObjectException
1173 * @param message Nachricht mit dem Fehler
1174 * @exception StorageObjectException
1176 void throwStorageObjectException (String message)
1177 throws StorageObjectException {
1178 _throwStorageObjectException(null, message);