2 * put your module comment here
10 import java.text.SimpleDateFormat;
11 import java.text.ParseException;
12 import freemarker.template.*;
13 import com.codestudio.sql.*;
14 import com.codestudio.util.*;
16 import mir.storage.StorageObject;
17 import mir.storage.store.*;
23 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
24 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
25 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
26 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
27 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
30 * @version $Revision: 1.19 $ $Date: 2002/06/29 15:44:46 $
31 * @author $Author: mh $
33 * $Log: Database.java,v $
34 * Revision 1.19 2002/06/29 15:44:46 mh
35 * make the webdb_create update be called webdb_create_update. it breaks things otherwise. a fixme case I know..
37 * Revision 1.18 2002/06/28 20:42:13 mh
38 * added necessary bits in templates and Database.java to make webdb_create modifiable. make the conversion from sql/Timestamp to String more robust
42 public class Database implements StorageObject {
44 protected String theTable;
45 protected String theCoreTable=null;
46 protected String thePKeyName="id";
47 protected int thePKeyType, thePKeyIndex;
48 protected boolean evaluatedMetaData=false;
49 protected ArrayList metadataFields,metadataLabels,
50 metadataNotNullFields;
51 protected int[] metadataTypes;
52 protected Class theEntityClass;
53 protected StorageObject myselfDatabase;
54 protected SimpleList popupCache=null;
55 protected boolean hasPopupCache = false;
56 protected SimpleHash hashCache=null;
57 protected boolean hasTimestamp=true;
58 private String database_driver, database_url;
59 private int defaultLimit;
60 protected DatabaseAdaptor theAdaptor;
61 protected Logfile theLog;
62 private static Class GENERIC_ENTITY_CLASS=null,
63 STORABLE_OBJECT_ENTITY_CLASS=null;
64 private static SimpleHash POPUP_EMTYLINE=new SimpleHash();
65 protected static final ObjectStore o_store=ObjectStore.getInstance();
66 private SimpleDateFormat _dateFormatterOut =
67 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
68 private SimpleDateFormat _dateFormatterIn =
69 new SimpleDateFormat("yyyy-MM-dd");
70 private Calendar _cal = new GregorianCalendar();
72 private static final int _millisPerHour = 60 * 60 * 1000;
73 private static final int _millisPerMinute = 60 * 1000;
76 // always same object saves a little space
77 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
79 GENERIC_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
80 STORABLE_OBJECT_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
83 System.err.println("FATAL: Database.java could not initialize" + e.toString());
89 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
90 * Aus diesem file werden <code>Database.Logfile</code>,
91 * <code>Database.Username</code>,<code>Database.Password</code>,
92 * <code>Database.Host</code> und <code>Database.Adaptor</code>
93 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
96 * @param String confFilename Dateiname der Konfigurationsdatei
98 public Database() throws StorageObjectException {
99 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
100 MirConfig.getProp("Database.Logfile"));
101 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
102 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
104 theEntityClass = GENERIC_ENTITY_CLASS;
105 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
106 } catch (Exception e){
107 theLog.printError("Error in Database() constructor with "+
108 theAdaptorName + " -- " +e.toString());
109 throw new StorageObjectException("Error in Database() constructor with "
112 /*String database_username=MirConfig.getProp("Database.Username");
113 String database_password=MirConfig.getProp("Database.Password");
114 String database_host=MirConfig.getProp("Database.Host");
116 database_driver=theAdaptor.getDriver();
117 database_url=theAdaptor.getURL(database_username,database_password,
119 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
121 MirConfig.addBroker(database_driver,database_url);
122 //myBroker=MirConfig.getBroker();
127 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
128 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
129 * wird eine mir.entity.GenericEntity erzeugt.
131 * @return Class-Objekt der Entity
133 public java.lang.Class getEntityClass () {
134 return theEntityClass;
138 * Liefert die Standardbeschränkung von select-Statements zurück, also
139 * wieviel Datensätze per Default selektiert werden.
141 * @return Standard-Anzahl der Datensätze
143 public int getLimit () {
148 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
149 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
150 * @return Name des Primary-Keys
152 public String getIdName () {
157 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
159 * @return Name der Tabelle
161 public String getTableName () {
166 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
167 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
169 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
173 public String getCoreTable(){
174 if (theCoreTable!=null) return theCoreTable;
175 else return theTable;
179 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
180 * @return int-Array mit den Typen der Felder
181 * @exception StorageObjectException
183 public int[] getTypes () throws StorageObjectException {
184 if (metadataTypes == null)
186 return metadataTypes;
190 * Liefert eine Liste der Labels der Tabellenfelder
191 * @return ArrayListe mit Labeln
192 * @exception StorageObjectException
194 public ArrayList getLabels () throws StorageObjectException {
195 if (metadataLabels == null)
197 return metadataLabels;
201 * Liefert eine Liste der Felder der Tabelle
202 * @return ArrayList mit Feldern
203 * @exception StorageObjectException
205 public ArrayList getFields () throws StorageObjectException {
206 if (metadataFields == null)
208 return metadataFields;
213 * Gets value out of ResultSet according to type and converts to String
214 * @param inValue Wert aus ResultSet.
215 * @param aType Datenbanktyp.
216 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
217 * dann /unsupported value/
219 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
220 String outValue = null;
224 case java.sql.Types.BIT:
225 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
227 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
228 int out = rs.getInt(valueIndex);
230 outValue = new Integer(out).toString();
232 case java.sql.Types.NUMERIC:
233 /** @todo Numeric can be float or double depending upon
234 * metadata.getScale() / especially with oracle */
235 long outl = rs.getLong(valueIndex);
237 outValue = new Long(outl).toString();
239 case java.sql.Types.REAL:
240 float tempf = rs.getFloat(valueIndex);
244 int tempf_int = (int)tempf;
245 tempf = (float)tempf_int;
247 outValue = "" + tempf;
248 outValue = outValue.replace('.', ',');
251 case java.sql.Types.DOUBLE:
252 double tempd = rs.getDouble(valueIndex);
256 int tempd_int = (int)tempd;
257 tempd = (double)tempd_int;
259 outValue = "" + tempd;
260 outValue = outValue.replace('.', ',');
263 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
264 outValue = rs.getString(valueIndex);
265 //if (outValue != null)
266 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
268 case java.sql.Types.LONGVARBINARY:
269 outValue = rs.getString(valueIndex);
270 //if (outValue != null)
271 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
273 case java.sql.Types.TIMESTAMP:
274 // it's important to use Timestamp here as getting it
275 // as a string is undefined and is only there for debugging
276 // according to the API. we can make it a string through formatting.
278 Timestamp timestamp = (rs.getTimestamp(valueIndex));
280 java.util.Date date = new java.util.Date(timestamp.getTime());
281 outValue = _dateFormatterOut.format(date);
283 int offset = _cal.get(Calendar.ZONE_OFFSET)+
284 _cal.get(Calendar.DST_OFFSET);
285 String tzOffset = StringUtil.zeroPaddingNumber(
286 offset/_millisPerHour,2,2);
287 outValue = outValue+"+"+tzOffset;
291 outValue = "<unsupported value>";
292 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
295 } catch (SQLException e) {
296 throw new StorageObjectException("Could not get Value out of Resultset -- "
304 * select-Operator um einen Datensatz zu bekommen.
305 * @param id Primaerschluessel des Datensatzes.
306 * @return liefert EntityObject des gefundenen Datensatzes oder null.
308 public Entity selectById(String id) throws StorageObjectException
310 if (id==null||id.equals(""))
311 throw new StorageObjectException("id war null");
313 // ask object store for object
314 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
315 String uniqueId = id;
316 if ( theEntityClass.equals(StorableObjectEntity.class) )
317 uniqueId+="@"+theTable;
318 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
319 theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
320 Entity hit = (Entity)o_store.use(search_sid);
321 if ( hit!=null ) return hit;
324 Statement stmt=null;Connection con=getPooledCon();
325 Entity returnEntity=null;
328 /** @todo better prepared statement */
329 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
330 stmt = con.createStatement();
331 rs = executeSql(stmt, selectSql);
333 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
335 returnEntity = makeEntityFromResultSet(rs);
336 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
340 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
343 catch (SQLException sqe){
344 throwSQLException(sqe,"selectById"); return null;
346 catch (NumberFormatException e) {
347 theLog.printError("ID ist keine Zahl: " + id);
349 finally { freeConnection(con,stmt); }
351 /** @todo OS: Entity should be saved in ostore */
357 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
358 * @param key Datenbankfeld der Bedingung.
359 * @param value Wert die der key anehmen muss.
360 * @return EntityList mit den gematchten Entities
362 public EntityList selectByFieldValue(String aField, String aValue)
363 throws StorageObjectException
365 return selectByFieldValue(aField, aValue, 0);
369 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
370 * @param key Datenbankfeld der Bedingung.
371 * @param value Wert die der key anehmen muss.
372 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
373 * @return EntityList mit den gematchten Entities
375 public EntityList selectByFieldValue(String aField, String aValue, int offset)
376 throws StorageObjectException
378 return selectByWhereClause(aField + "=" + aValue, offset);
383 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
384 * Also offset wird der erste Datensatz genommen.
386 * @param wc where-Clause
387 * @return EntityList mit den gematchten Entities
388 * @exception StorageObjectException
390 public EntityList selectByWhereClause(String where)
391 throws StorageObjectException
393 return selectByWhereClause(where, 0);
398 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
399 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
401 * @param wc where-Clause
402 * @param offset ab welchem Datensatz.
403 * @return EntityList mit den gematchten Entities
404 * @exception StorageObjectException
406 public EntityList selectByWhereClause(String whereClause, int offset)
407 throws StorageObjectException
409 return selectByWhereClause(whereClause, null, offset);
414 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
415 * Also offset wird der erste Datensatz genommen.
416 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
418 * @param wc where-Clause
419 * @param ob orderBy-Clause
420 * @return EntityList mit den gematchten Entities
421 * @exception StorageObjectException
424 public EntityList selectByWhereClause(String where, String order)
425 throws StorageObjectException {
426 return selectByWhereClause(where, order, 0);
431 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
432 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
434 * @param wc where-Clause
435 * @param ob orderBy-Clause
436 * @param offset ab welchem Datensatz
437 * @return EntityList mit den gematchten Entities
438 * @exception StorageObjectException
441 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
442 throws StorageObjectException {
443 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
448 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
449 * @param wc where-Clause
450 * @param ob orderBy-Clause
451 * @param offset ab welchem Datensatz
452 * @param limit wieviele Datensätze
453 * @return EntityList mit den gematchten Entities
454 * @exception StorageObjectException
457 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
458 throws StorageObjectException
461 // check o_store for entitylist
462 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
463 StoreIdentifier search_sid =
464 new StoreIdentifier( theEntityClass,
465 StoreContainerType.STOC_TYPE_ENTITYLIST,
466 StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
467 EntityList hit = (EntityList)o_store.use(search_sid);
469 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
475 EntityList theReturnList=null;
476 Connection con=null; Statement stmt=null;
478 int offsetCount = 0, count=0;
480 // build sql-statement
482 /** @todo count sql string should only be assembled if we really count
483 * see below at the end of method //rk */
485 if (wc != null && wc.length() == 0) {
488 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
489 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
491 selectSql.append(" where ").append(wc);
492 countSql.append(" where ").append(wc);
494 if (ob != null && !(ob.length() == 0)) {
495 selectSql.append(" order by ").append(ob);
497 if (theAdaptor.hasLimit()) {
498 if (limit > -1 && offset > -1) {
499 selectSql.append(" limit ");
500 if (theAdaptor.reverseLimit()) {
501 selectSql.append(limit).append(",").append(offset);
504 selectSql.append(offset).append(",").append(limit);
511 con = getPooledCon();
512 stmt = con.createStatement();
515 rs = executeSql(stmt, selectSql.toString());
517 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
519 theReturnList = new EntityList();
520 Entity theResultEntity;
522 theResultEntity = makeEntityFromResultSet(rs);
523 theReturnList.add(theResultEntity);
529 // making entitylist infos
530 if (!(theAdaptor.hasLimit())) count = offsetCount;
532 if (theReturnList != null) {
533 // now we decide if we have to know an overall count...
535 if (limit > -1 && offset > -1) {
536 if (offsetCount==limit) {
537 /** @todo counting should be deffered to entitylist
538 * getSize() should be used */
539 rs = executeSql(stmt, countSql.toString());
541 if ( rs.next() ) count = rs.getInt(1);
544 else theLog.printError("Could not count: " + countSql);
547 theReturnList.setCount(count);
548 theReturnList.setOffset(offset);
549 theReturnList.setWhere(wc);
550 theReturnList.setOrder(ob);
551 theReturnList.setStorage(this);
552 theReturnList.setLimit(limit);
553 if ( offset >= limit )
554 theReturnList.setPrevBatch(offset - limit);
555 if ( offset+offsetCount < count )
556 theReturnList.setNextBatch(offset + limit);
557 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
558 StoreIdentifier sid=theReturnList.getStoreIdentifier();
559 theLog.printDebugInfo("CACHE (add): " + sid.toString());
564 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
565 finally { freeConnection(con, stmt); }
567 return theReturnList;
572 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
574 * @param rs Das ResultSetObjekt.
575 * @return Entity Die Entity.
577 private Entity makeEntityFromResultSet (ResultSet rs)
578 throws StorageObjectException
580 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
581 HashMap theResultHash = new HashMap();
582 String theResult = null;
584 Entity returnEntity = null;
586 int size = metadataFields.size();
587 for (int i = 0; i < size; i++) {
588 // alle durchlaufen bis nix mehr da
589 theType = metadataTypes[i];
590 if (theType == java.sql.Types.LONGVARBINARY) {
591 InputStreamReader is = (InputStreamReader)rs.getCharacterStream(i + 1);
593 char[] data = new char[32768];
594 StringBuffer theResultString = new StringBuffer();
596 while ((len = is.read(data)) > 0) {
597 theResultString.append(data, 0, len);
600 theResult = theResultString.toString();
607 theResult = getValueAsString(rs, (i + 1), theType);
609 if (theResult != null) {
610 theResultHash.put(metadataFields.get(i), theResult);
613 if (theEntityClass != null) {
614 returnEntity = (Entity)theEntityClass.newInstance();
615 returnEntity.setValues(theResultHash);
616 returnEntity.setStorage(myselfDatabase);
617 if ( returnEntity instanceof StorableObject ) {
618 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
619 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
622 throwStorageObjectException("Internal Error: theEntityClass not set!");
624 } catch (IllegalAccessException e) {
625 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
626 } catch (IOException e) {
627 throwStorageObjectException("IOException! -- " + e.toString());
628 } catch (InstantiationException e) {
629 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
630 } catch (SQLException sqe) {
631 throwSQLException(sqe, "makeEntityFromResultSet");
638 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
639 * wird automatisch mit dem aktuellen Datum gefuellt.
642 * @return der Wert des Primary-keys der eingefügten Entity
644 public String insert (Entity theEntity) throws StorageObjectException {
646 invalidatePopupCache();
648 // invalidating all EntityLists corresponding with theEntityClass
649 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
650 StoreContainerType stoc_type =
651 StoreContainerType.valueOf( theEntityClass,
652 StoreContainerType.STOC_TYPE_ENTITYLIST);
653 o_store.invalidate(stoc_type);
656 String returnId = null;
657 Connection con = null; PreparedStatement pstmt = null;
660 ArrayList streamedInput = theEntity.streamedInput();
661 StringBuffer f = new StringBuffer();
662 StringBuffer v = new StringBuffer();
663 String aField, aValue;
664 boolean firstField = true;
666 for (int i = 0; i < getFields().size(); i++) {
667 aField = (String)getFields().get(i);
668 if (!aField.equals(thePKeyName)) {
671 if (aField.equals("webdb_create")) {
675 if (streamedInput != null && streamedInput.contains(aField)) {
679 if (theEntity.hasValueForField(aField)) {
680 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
685 // wenn Wert gegeben, dann einbauen
686 if (aValue != null) {
687 if (firstField == false) {
700 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
701 String sql = sqlBuf.toString();
702 theLog.printInfo("INSERT: " + sql);
703 con = getPooledCon();
704 con.setAutoCommit(false);
705 pstmt = con.prepareStatement(sql);
706 if (streamedInput != null) {
707 for (int i = 0; i < streamedInput.size(); i++) {
708 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
709 pstmt.setBytes(i + 1, inputString.getBytes());
712 int ret = pstmt.executeUpdate();
717 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
718 ResultSet rs = pstmt.executeQuery();
720 returnId = rs.getString(1);
721 theEntity.setId(returnId);
722 } catch (SQLException sqe) {
723 throwSQLException(sqe, "insert");
726 con.setAutoCommit(true);
727 } catch (Exception e) {
730 freeConnection(con, pstmt);
732 /** @todo store entity in o_store */
737 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
738 * wird automatisch mit dem aktuellen Datum gefuellt.
742 public void update (Entity theEntity) throws StorageObjectException
744 Connection con = null; PreparedStatement pstmt = null;
745 /** @todo this is stupid: why do we prepare statement, when we
746 * throw it away afterwards. should be regular statement
747 * update/insert could better be one routine called save()
748 * that chooses to either insert or update depending if we
749 * have a primary key in the entity. i don't know if we
750 * still need the streamed input fields. // rk */
752 /** @todo extension: check if Entity did change, otherwise we don't need
753 * the roundtrip to the database */
755 /** invalidating corresponding entitylists in o_store*/
756 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
757 StoreContainerType stoc_type =
758 StoreContainerType.valueOf( theEntityClass,
759 StoreContainerType.STOC_TYPE_ENTITYLIST);
760 o_store.invalidate(stoc_type);
763 ArrayList streamedInput = theEntity.streamedInput();
764 String id = theEntity.getId();
766 StringBuffer fv = new StringBuffer();
767 boolean firstField = true;
769 invalidatePopupCache();
770 // build sql statement
771 for (int i = 0; i < getFields().size(); i++) {
772 aField = (String)metadataFields.get(i);
774 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
775 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
776 if (theEntity.hasValueForField(aField)) {
777 if (firstField == false) {
783 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
787 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
789 if (metadataFields.contains("webdb_lastchange")) {
790 sql.append(",webdb_lastchange=NOW()");
792 // special case: the webdb_create requires the field in yyyy-mm-dd format
793 // so anything extra will be ignored. which breaks actual updating when a
794 // a change in date is not desired but the values hash has the correct and
795 // full "webdb_create" field and value in it. solution make it so the update
796 // must be called webdb_create_update. a hack I know.. hopefully
797 // we can replace this whole layer soon. -mh
798 if (metadataFields.contains("webdb_create") &&
799 theEntity.hasValueForField("webdb_create_update")) {
802 java.util.Date d = _dateFormatterIn.parse(
803 theEntity.getValue("webdb_create"));
804 Timestamp tStamp = new Timestamp(d.getTime());
805 sql.append(",webdb_create='"+tStamp.toString()+"'");
806 } catch (ParseException e) {
807 throw new StorageObjectException(e.toString());
810 if (streamedInput != null) {
811 for (int i = 0; i < streamedInput.size(); i++) {
812 sql.append(",").append(streamedInput.get(i)).append("=?");
815 sql.append(" where id=").append(id);
816 theLog.printInfo("UPDATE: " + sql);
819 con = getPooledCon();
820 con.setAutoCommit(false);
821 pstmt = con.prepareStatement(sql.toString());
822 if (streamedInput != null) {
823 for (int i = 0; i < streamedInput.size(); i++) {
824 String inputString = theEntity.getValue((String)streamedInput.get(i));
825 pstmt.setBytes(i + 1, inputString.getBytes());
828 pstmt.executeUpdate();
829 } catch (SQLException sqe) {
830 throwSQLException(sqe, "update");
833 con.setAutoCommit(true);
834 } catch (Exception e) {
837 freeConnection(con, pstmt);
843 * @param id des zu loeschenden Datensatzes
844 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
846 public boolean delete (String id) throws StorageObjectException {
848 invalidatePopupCache();
849 // ostore send notification
850 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
851 String uniqueId = id;
852 if ( theEntityClass.equals(StorableObjectEntity.class) )
853 uniqueId+="@"+theTable;
854 theLog.printInfo("CACHE: (del) " + id);
855 StoreIdentifier search_sid =
856 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
857 o_store.invalidate(search_sid);
860 /** @todo could be prepared Statement */
861 Statement stmt = null; Connection con = null;
863 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
864 theLog.printInfo("DELETE " + sql);
866 con = getPooledCon(); stmt = con.createStatement();
867 res = stmt.executeUpdate(sql);
869 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
870 finally { freeConnection(con, stmt); }
872 return (res > 0) ? true : false;
875 /* noch nicht implementiert.
876 * @return immer false
878 public boolean delete (EntityList theEntityList) {
879 invalidatePopupCache();
884 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
885 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
888 public SimpleList getPopupData () throws StorageObjectException {
893 * Holt Daten fuer Popups.
894 * @param name Name des Feldes.
895 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
896 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
898 public SimpleList getPopupData (String name, boolean hasNullValue)
899 throws StorageObjectException {
900 return getPopupData(name, hasNullValue, null);
904 * Holt Daten fuer Popups.
905 * @param name Name des Feldes.
906 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
907 * @param where Schraenkt die Selektion der Datensaetze ein.
908 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
910 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
911 return getPopupData(name, hasNullValue, where, null);
915 * Holt Daten fuer Popups.
916 * @param name Name des Feldes.
917 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
918 * @param where Schraenkt die Selektion der Datensaetze ein.
919 * @param order Gibt ein Feld als Sortierkriterium an.
920 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
922 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
924 if (hasPopupCache && popupCache != null)
926 SimpleList simpleList = null;
927 Connection con = null;
928 Statement stmt = null;
930 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
931 .append(",").append(name).append(" from ")
933 if (where != null && !(where.length() == 0))
934 sql.append(" where ").append(where);
935 sql.append(" order by ");
936 if (order != null && !(order.length() == 0))
942 con = getPooledCon();
943 } catch (Exception e) {
944 throw new StorageObjectException(e.toString());
947 stmt = con.createStatement();
948 ResultSet rs = executeSql(stmt, sql.toString());
951 if (!evaluatedMetaData) get_meta_data();
952 simpleList = new SimpleList();
953 // if popup has null-selector
954 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
956 SimpleHash popupDict;
958 popupDict = new SimpleHash();
959 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
960 popupDict.put("value", rs.getString(2));
961 simpleList.add(popupDict);
965 } catch (Exception e) {
966 theLog.printError("getPopupData: "+e.toString());
967 throw new StorageObjectException(e.toString());
969 freeConnection(con, stmt);
972 if (hasPopupCache) popupCache = simpleList;
977 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
978 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
979 * Tabellen Verwendung finden.
980 * @return SimpleHash mit den Tabellezeilen.
982 public SimpleHash getHashData () {
983 /** @todo dangerous! this should have a flag to be enabled, otherwise
984 * very big Hashes could be returned */
985 if (hashCache == null) {
987 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
989 } catch (StorageObjectException e) {
990 theLog.printDebugInfo(e.toString());
996 /* invalidates the popupCache
998 protected void invalidatePopupCache () {
999 /** @todo invalidates toooo much */
1005 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1006 * @param stmt Statemnt
1007 * @param sql Sql-String
1009 * @exception StorageObjectException
1011 public ResultSet executeSql (Statement stmt, String sql)
1012 throws StorageObjectException, SQLException
1014 long startTime = System.currentTimeMillis();
1017 rs = stmt.executeQuery(sql);
1018 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1021 catch (SQLException e)
1023 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
1024 - startTime) + "ms. for: "+ sql);
1032 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
1033 * getimed und geloggt.
1034 * @param stmt PreparedStatement mit der SQL-Anweisung
1035 * @return Liefert ResultSet des Statements zurueck.
1036 * @exception StorageObjectException, SQLException
1038 public ResultSet executeSql (PreparedStatement stmt)
1039 throws StorageObjectException, SQLException {
1041 long startTime = (new java.util.Date()).getTime();
1042 ResultSet rs = stmt.executeQuery();
1043 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1048 * returns the number of rows in the table
1050 public int getSize(String where)
1051 throws SQLException,StorageObjectException
1053 long startTime = System.currentTimeMillis();
1054 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
1055 Connection con = null;
1056 Statement stmt = null;
1060 con = getPooledCon();
1061 stmt = con.createStatement();
1062 ResultSet rs = executeSql(stmt,sql);
1064 result = rs.getInt(1);
1066 } catch (SQLException e) {
1067 theLog.printError(e.toString());
1069 freeConnection(con,stmt);
1071 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1072 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1077 public int executeUpdate(Statement stmt, String sql)
1078 throws StorageObjectException, SQLException
1081 long startTime = (new java.util.Date()).getTime();
1084 rs = stmt.executeUpdate(sql);
1085 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1088 catch (SQLException e)
1090 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1091 - startTime) + "ms. for: "+ sql);
1097 public int executeUpdate(String sql)
1098 throws StorageObjectException, SQLException
1101 long startTime = (new java.util.Date()).getTime();
1102 Connection con=null;PreparedStatement pstmt=null;
1105 pstmt = con.prepareStatement(sql);
1106 result = pstmt.executeUpdate();
1108 catch (Exception e) {
1109 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1110 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1112 finally { freeConnection(con,pstmt); }
1113 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1119 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1120 * @param md ResultSetMetaData
1121 * @exception StorageObjectException
1123 private void evalMetaData (ResultSetMetaData md)
1124 throws StorageObjectException {
1126 this.evaluatedMetaData = true;
1127 this.metadataFields = new ArrayList();
1128 this.metadataLabels = new ArrayList();
1129 this.metadataNotNullFields = new ArrayList();
1131 int numFields = md.getColumnCount();
1132 this.metadataTypes = new int[numFields];
1135 for (int i = 1; i <= numFields; i++) {
1136 aField = md.getColumnName(i);
1137 metadataFields.add(aField);
1138 metadataLabels.add(md.getColumnLabel(i));
1139 aType = md.getColumnType(i);
1140 metadataTypes[i - 1] = aType;
1141 if (aField.equals(thePKeyName)) {
1142 thePKeyType = aType; thePKeyIndex = i;
1144 if (md.isNullable(i) == md.columnNullable) {
1145 metadataNotNullFields.add(aField);
1148 } catch (SQLException e) {
1149 throwSQLException(e, "evalMetaData");
1154 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1155 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1157 private void get_meta_data () throws StorageObjectException {
1158 Connection con = null;
1159 PreparedStatement pstmt = null;
1160 String sql = "select * from " + theTable + " where 0=1";
1162 con = getPooledCon();
1163 pstmt = con.prepareStatement(sql);
1164 theLog.printInfo("METADATA: " + sql);
1165 ResultSet rs = pstmt.executeQuery();
1166 evalMetaData(rs.getMetaData());
1168 } catch (SQLException e) {
1169 throwSQLException(e, "get_meta_data");
1171 freeConnection(con, pstmt);
1176 public Connection getPooledCon() throws StorageObjectException {
1177 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1179 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1180 } catch (Exception e){
1181 throw new StorageObjectException("Could not find the PoolMan Driver"
1184 Connection con = null;
1186 con = SQLManager.getInstance().requestConnection();
1187 } catch(SQLException e){
1188 theLog.printError("could not connect to the database "+e.toString());
1189 System.err.println("could not connect to the database "+e.toString());
1190 throw new StorageObjectException("Could not connect to the database"+
1196 public void freeConnection (Connection con, Statement stmt)
1197 throws StorageObjectException {
1198 SQLManager.getInstance().closeStatement(stmt);
1199 SQLManager.getInstance().returnConnection(con);
1203 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1204 * @param sqe SQLException
1205 * @param wo Funktonsname, in der die SQLException geworfen wurde
1206 * @exception StorageObjectException
1208 protected void throwSQLException (SQLException sqe, String wo)
1209 throws StorageObjectException {
1211 String message = "";
1214 state = sqe.getSQLState();
1215 message = sqe.getMessage();
1216 vendor = sqe.getErrorCode();
1218 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1220 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1224 protected void _throwStorageObjectException (Exception e, String wo)
1225 throws StorageObjectException {
1227 theLog.printError(e.toString()+ wo);
1228 throw new StorageObjectException(wo + e.toString());
1230 theLog.printError(wo);
1231 throw new StorageObjectException(wo);
1237 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1238 * eine StorageObjectException
1239 * @param message Nachricht mit dem Fehler
1240 * @exception StorageObjectException
1242 void throwStorageObjectException (String message)
1243 throws StorageObjectException {
1244 _throwStorageObjectException(null, message);