2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with the com.oreilly.servlet library, any library
22 * licensed under the Apache Software License, The Sun (tm) Java Advanced
23 * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24 * the above that use the same license as the above), and distribute linked
25 * combinations including the two. You must obey the GNU General Public
26 * License in all respects for all of the code used other than the above
27 * mentioned libraries. If you modify this file, you may extend this exception
28 * to your version of the file, but you are not obligated to do so. If you do
29 * not wish to do so, delete this exception statement from your version.
38 import java.text.SimpleDateFormat;
39 import java.text.ParseException;
40 import freemarker.template.*;
41 import com.codestudio.sql.*;
42 import com.codestudio.util.*;
44 import mir.storage.StorageObject;
45 import mir.storage.store.*;
51 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
52 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
53 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
54 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
55 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
58 * @version $Revision: 1.23 $ $Date: 2002/09/01 22:05:52 $
59 * @author $Author: mh $
61 * $Log: Database.java,v $
62 * Revision 1.23 2002/09/01 22:05:52 mh
65 * Revision 1.22 2002/08/25 19:00:09 mh
66 * merge of localization branch into HEAD. mh and zap
68 * Revision 1.21 2002/08/04 23:38:22 mh
69 * fix up the webdb_create update stuff
71 * Revision 1.20 2002/07/21 22:32:25 mh
72 * on insert, the "webdb_lastchange" field should get a value
74 * Revision 1.19 2002/06/29 15:44:46 mh
75 * make the webdb_create update be called webdb_create_update. it breaks things otherwise. a fixme case I know..
77 * Revision 1.18 2002/06/28 20:42:13 mh
78 * added necessary bits in templates and Database.java to make webdb_create modifiable. make the conversion from sql/Timestamp to String more robust
82 public class Database implements StorageObject {
84 protected String theTable;
85 protected String theCoreTable=null;
86 protected String thePKeyName="id";
87 protected int thePKeyType, thePKeyIndex;
88 protected boolean evaluatedMetaData=false;
89 protected ArrayList metadataFields,metadataLabels,
90 metadataNotNullFields;
91 protected int[] metadataTypes;
92 protected Class theEntityClass;
93 protected StorageObject myselfDatabase;
94 protected SimpleList popupCache=null;
95 protected boolean hasPopupCache = false;
96 protected SimpleHash hashCache=null;
97 protected boolean hasTimestamp=true;
98 private String database_driver, database_url;
99 private int defaultLimit;
100 protected DatabaseAdaptor theAdaptor;
101 protected Logfile theLog;
102 private static Class GENERIC_ENTITY_CLASS=null,
103 STORABLE_OBJECT_ENTITY_CLASS=null;
104 private static SimpleHash POPUP_EMTYLINE=new SimpleHash();
105 protected static final ObjectStore o_store=ObjectStore.getInstance();
106 private SimpleDateFormat _dateFormatterOut =
107 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
108 private SimpleDateFormat _dateFormatterIn =
109 new SimpleDateFormat("yyyy-MM-dd HH:mm");
110 private Calendar _cal = new GregorianCalendar();
112 private static final int _millisPerHour = 60 * 60 * 1000;
113 private static final int _millisPerMinute = 60 * 1000;
116 // always same object saves a little space
117 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
119 GENERIC_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
120 STORABLE_OBJECT_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
122 catch (Exception e) {
123 System.err.println("FATAL: Database.java could not initialize" + e.toString());
129 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
130 * Aus diesem file werden <code>Database.Logfile</code>,
131 * <code>Database.Username</code>,<code>Database.Password</code>,
132 * <code>Database.Host</code> und <code>Database.Adaptor</code>
133 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
136 * @param String confFilename Dateiname der Konfigurationsdatei
138 public Database() throws StorageObjectException {
139 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
140 MirConfig.getProp("Database.Logfile"));
141 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
142 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
144 theEntityClass = GENERIC_ENTITY_CLASS;
145 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
146 } catch (Exception e){
147 theLog.printError("Error in Database() constructor with "+
148 theAdaptorName + " -- " +e.toString());
149 throw new StorageObjectException("Error in Database() constructor with "
152 /*String database_username=MirConfig.getProp("Database.Username");
153 String database_password=MirConfig.getProp("Database.Password");
154 String database_host=MirConfig.getProp("Database.Host");
156 database_driver=theAdaptor.getDriver();
157 database_url=theAdaptor.getURL(database_username,database_password,
159 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
161 MirConfig.addBroker(database_driver,database_url);
162 //myBroker=MirConfig.getBroker();
167 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
168 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
169 * wird eine mir.entity.GenericEntity erzeugt.
171 * @return Class-Objekt der Entity
173 public java.lang.Class getEntityClass () {
174 return theEntityClass;
178 * Liefert die Standardbeschränkung von select-Statements zurück, also
179 * wieviel Datensätze per Default selektiert werden.
181 * @return Standard-Anzahl der Datensätze
183 public int getLimit () {
188 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
189 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
190 * @return Name des Primary-Keys
192 public String getIdName () {
197 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
199 * @return Name der Tabelle
201 public String getTableName () {
206 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
207 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
209 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
213 public String getCoreTable(){
214 if (theCoreTable!=null) return theCoreTable;
215 else return theTable;
219 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
220 * @return int-Array mit den Typen der Felder
221 * @exception StorageObjectException
223 public int[] getTypes () throws StorageObjectException {
224 if (metadataTypes == null)
226 return metadataTypes;
230 * Liefert eine Liste der Labels der Tabellenfelder
231 * @return ArrayListe mit Labeln
232 * @exception StorageObjectException
234 public ArrayList getLabels () throws StorageObjectException {
235 if (metadataLabels == null)
237 return metadataLabels;
241 * Liefert eine Liste der Felder der Tabelle
242 * @return ArrayList mit Feldern
243 * @exception StorageObjectException
245 public ArrayList getFields () throws StorageObjectException {
246 if (metadataFields == null)
248 return metadataFields;
253 * Gets value out of ResultSet according to type and converts to String
254 * @param inValue Wert aus ResultSet.
255 * @param aType Datenbanktyp.
256 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
257 * dann /unsupported value/
259 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
260 String outValue = null;
264 case java.sql.Types.BIT:
265 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
267 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
268 int out = rs.getInt(valueIndex);
270 outValue = new Integer(out).toString();
272 case java.sql.Types.NUMERIC:
273 /** @todo Numeric can be float or double depending upon
274 * metadata.getScale() / especially with oracle */
275 long outl = rs.getLong(valueIndex);
277 outValue = new Long(outl).toString();
279 case java.sql.Types.REAL:
280 float tempf = rs.getFloat(valueIndex);
284 int tempf_int = (int)tempf;
285 tempf = (float)tempf_int;
287 outValue = "" + tempf;
288 outValue = outValue.replace('.', ',');
291 case java.sql.Types.DOUBLE:
292 double tempd = rs.getDouble(valueIndex);
296 int tempd_int = (int)tempd;
297 tempd = (double)tempd_int;
299 outValue = "" + tempd;
300 outValue = outValue.replace('.', ',');
303 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
304 outValue = rs.getString(valueIndex);
305 //if (outValue != null)
306 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
308 case java.sql.Types.LONGVARBINARY:
309 outValue = rs.getString(valueIndex);
310 //if (outValue != null)
311 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
313 case java.sql.Types.TIMESTAMP:
314 // it's important to use Timestamp here as getting it
315 // as a string is undefined and is only there for debugging
316 // according to the API. we can make it a string through formatting.
318 Timestamp timestamp = (rs.getTimestamp(valueIndex));
320 java.util.Date date = new java.util.Date(timestamp.getTime());
321 outValue = _dateFormatterOut.format(date);
323 int offset = _cal.get(Calendar.ZONE_OFFSET)+
324 _cal.get(Calendar.DST_OFFSET);
325 String tzOffset = StringUtil.zeroPaddingNumber(
326 offset/_millisPerHour,2,2);
327 outValue = outValue+"+"+tzOffset;
331 outValue = "<unsupported value>";
332 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
335 } catch (SQLException e) {
336 throw new StorageObjectException("Could not get Value out of Resultset -- "
344 * select-Operator um einen Datensatz zu bekommen.
345 * @param id Primaerschluessel des Datensatzes.
346 * @return liefert EntityObject des gefundenen Datensatzes oder null.
348 public Entity selectById(String id) throws StorageObjectException
350 if (id==null||id.equals(""))
351 throw new StorageObjectException("id war null");
353 // ask object store for object
354 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
355 String uniqueId = id;
356 if ( theEntityClass.equals(StorableObjectEntity.class) )
357 uniqueId+="@"+theTable;
358 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
359 theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
360 Entity hit = (Entity)o_store.use(search_sid);
361 if ( hit!=null ) return hit;
364 Statement stmt=null;Connection con=getPooledCon();
365 Entity returnEntity=null;
368 /** @todo better prepared statement */
369 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
370 stmt = con.createStatement();
371 rs = executeSql(stmt, selectSql);
373 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
375 returnEntity = makeEntityFromResultSet(rs);
376 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
380 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
383 catch (SQLException sqe){
384 throwSQLException(sqe,"selectById"); return null;
386 catch (NumberFormatException e) {
387 theLog.printError("ID ist keine Zahl: " + id);
389 finally { freeConnection(con,stmt); }
391 /** @todo OS: Entity should be saved in ostore */
397 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
398 * @param key Datenbankfeld der Bedingung.
399 * @param value Wert die der key anehmen muss.
400 * @return EntityList mit den gematchten Entities
402 public EntityList selectByFieldValue(String aField, String aValue)
403 throws StorageObjectException
405 return selectByFieldValue(aField, aValue, 0);
409 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
410 * @param key Datenbankfeld der Bedingung.
411 * @param value Wert die der key anehmen muss.
412 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
413 * @return EntityList mit den gematchten Entities
415 public EntityList selectByFieldValue(String aField, String aValue, int offset)
416 throws StorageObjectException
418 return selectByWhereClause(aField + "=" + aValue, offset);
423 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
424 * Also offset wird der erste Datensatz genommen.
426 * @param wc where-Clause
427 * @return EntityList mit den gematchten Entities
428 * @exception StorageObjectException
430 public EntityList selectByWhereClause(String where)
431 throws StorageObjectException
433 return selectByWhereClause(where, 0);
438 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
439 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
441 * @param wc where-Clause
442 * @param offset ab welchem Datensatz.
443 * @return EntityList mit den gematchten Entities
444 * @exception StorageObjectException
446 public EntityList selectByWhereClause(String whereClause, int offset)
447 throws StorageObjectException
449 return selectByWhereClause(whereClause, null, offset);
454 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
455 * Also offset wird der erste Datensatz genommen.
456 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
458 * @param wc where-Clause
459 * @param ob orderBy-Clause
460 * @return EntityList mit den gematchten Entities
461 * @exception StorageObjectException
464 public EntityList selectByWhereClause(String where, String order)
465 throws StorageObjectException {
466 return selectByWhereClause(where, order, 0);
471 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
472 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
474 * @param wc where-Clause
475 * @param ob orderBy-Clause
476 * @param offset ab welchem Datensatz
477 * @return EntityList mit den gematchten Entities
478 * @exception StorageObjectException
481 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
482 throws StorageObjectException {
483 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
488 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
489 * @param wc where-Clause
490 * @param ob orderBy-Clause
491 * @param offset ab welchem Datensatz
492 * @param limit wieviele Datensätze
493 * @return EntityList mit den gematchten Entities
494 * @exception StorageObjectException
497 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
498 throws StorageObjectException
501 // check o_store for entitylist
502 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
503 StoreIdentifier search_sid =
504 new StoreIdentifier( theEntityClass,
505 StoreContainerType.STOC_TYPE_ENTITYLIST,
506 StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
507 EntityList hit = (EntityList)o_store.use(search_sid);
509 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
515 EntityList theReturnList=null;
516 Connection con=null; Statement stmt=null;
518 int offsetCount = 0, count=0;
520 // build sql-statement
522 /** @todo count sql string should only be assembled if we really count
523 * see below at the end of method //rk */
525 if (wc != null && wc.length() == 0) {
528 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
529 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
531 selectSql.append(" where ").append(wc);
532 countSql.append(" where ").append(wc);
534 if (ob != null && !(ob.length() == 0)) {
535 selectSql.append(" order by ").append(ob);
537 if (theAdaptor.hasLimit()) {
538 if (limit > -1 && offset > -1) {
539 selectSql.append(" limit ");
540 if (theAdaptor.reverseLimit()) {
541 selectSql.append(limit).append(",").append(offset);
544 selectSql.append(offset).append(",").append(limit);
551 con = getPooledCon();
552 stmt = con.createStatement();
555 rs = executeSql(stmt, selectSql.toString());
557 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
559 theReturnList = new EntityList();
560 Entity theResultEntity;
562 theResultEntity = makeEntityFromResultSet(rs);
563 theReturnList.add(theResultEntity);
569 // making entitylist infos
570 if (!(theAdaptor.hasLimit())) count = offsetCount;
572 if (theReturnList != null) {
573 // now we decide if we have to know an overall count...
575 if (limit > -1 && offset > -1) {
576 if (offsetCount==limit) {
577 /** @todo counting should be deffered to entitylist
578 * getSize() should be used */
579 rs = executeSql(stmt, countSql.toString());
581 if ( rs.next() ) count = rs.getInt(1);
584 else theLog.printError("Could not count: " + countSql);
587 theReturnList.setCount(count);
588 theReturnList.setOffset(offset);
589 theReturnList.setWhere(wc);
590 theReturnList.setOrder(ob);
591 theReturnList.setStorage(this);
592 theReturnList.setLimit(limit);
593 if ( offset >= limit )
594 theReturnList.setPrevBatch(offset - limit);
595 if ( offset+offsetCount < count )
596 theReturnList.setNextBatch(offset + limit);
597 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
598 StoreIdentifier sid=theReturnList.getStoreIdentifier();
599 theLog.printDebugInfo("CACHE (add): " + sid.toString());
604 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
605 finally { freeConnection(con, stmt); }
607 return theReturnList;
612 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
614 * @param rs Das ResultSetObjekt.
615 * @return Entity Die Entity.
617 private Entity makeEntityFromResultSet (ResultSet rs)
618 throws StorageObjectException
620 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
621 HashMap theResultHash = new HashMap();
622 String theResult = null;
624 Entity returnEntity = null;
626 int size = metadataFields.size();
627 for (int i = 0; i < size; i++) {
628 // alle durchlaufen bis nix mehr da
630 theType = metadataTypes[i];
631 if (theType == java.sql.Types.LONGVARBINARY) {
632 InputStreamReader is = (InputStreamReader)rs.getCharacterStream(i + 1);
634 char[] data = new char[32768];
635 StringBuffer theResultString = new StringBuffer();
637 while ((len = is.read(data)) > 0) {
638 theResultString.append(data, 0, len);
641 theResult = theResultString.toString();
648 theResult = getValueAsString(rs, (i + 1), theType);
650 if (theResult != null) {
651 theResultHash.put(metadataFields.get(i), theResult);
654 if (theEntityClass != null) {
655 returnEntity = (Entity)theEntityClass.newInstance();
656 returnEntity.setValues(theResultHash);
657 returnEntity.setStorage(myselfDatabase);
658 if ( returnEntity instanceof StorableObject ) {
659 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
660 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
663 throwStorageObjectException("Internal Error: theEntityClass not set!");
665 } catch (IllegalAccessException e) {
666 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
667 } catch (IOException e) {
668 throwStorageObjectException("IOException! -- " + e.toString());
669 } catch (InstantiationException e) {
670 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
671 } catch (SQLException sqe) {
672 throwSQLException(sqe, "makeEntityFromResultSet");
679 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
680 * wird automatisch mit dem aktuellen Datum gefuellt.
683 * @return der Wert des Primary-keys der eingefügten Entity
685 public String insert (Entity theEntity) throws StorageObjectException {
687 invalidatePopupCache();
689 // invalidating all EntityLists corresponding with theEntityClass
690 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
691 StoreContainerType stoc_type =
692 StoreContainerType.valueOf( theEntityClass,
693 StoreContainerType.STOC_TYPE_ENTITYLIST);
694 o_store.invalidate(stoc_type);
697 String returnId = null;
698 Connection con = null; PreparedStatement pstmt = null;
701 ArrayList streamedInput = theEntity.streamedInput();
702 StringBuffer f = new StringBuffer();
703 StringBuffer v = new StringBuffer();
704 String aField, aValue;
705 boolean firstField = true;
707 for (int i = 0; i < getFields().size(); i++) {
708 aField = (String)getFields().get(i);
709 if (!aField.equals(thePKeyName)) {
712 if (aField.equals("webdb_create") ||
713 aField.equals("webdb_lastchange")) {
717 if (streamedInput != null && streamedInput.contains(aField)) {
721 if (theEntity.hasValueForField(aField)) {
722 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
727 // wenn Wert gegeben, dann einbauen
728 if (aValue != null) {
729 if (firstField == false) {
742 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
743 String sql = sqlBuf.toString();
744 theLog.printInfo("INSERT: " + sql);
745 con = getPooledCon();
746 con.setAutoCommit(false);
747 pstmt = con.prepareStatement(sql);
748 if (streamedInput != null) {
749 for (int i = 0; i < streamedInput.size(); i++) {
750 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
751 pstmt.setBytes(i + 1, inputString.getBytes());
754 int ret = pstmt.executeUpdate();
759 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
760 ResultSet rs = pstmt.executeQuery();
762 returnId = rs.getString(1);
763 theEntity.setId(returnId);
764 } catch (SQLException sqe) {
765 throwSQLException(sqe, "insert");
768 con.setAutoCommit(true);
769 } catch (Exception e) {
772 freeConnection(con, pstmt);
774 /** @todo store entity in o_store */
779 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
780 * wird automatisch mit dem aktuellen Datum gefuellt.
784 public void update (Entity theEntity) throws StorageObjectException
786 Connection con = null; PreparedStatement pstmt = null;
787 /** @todo this is stupid: why do we prepare statement, when we
788 * throw it away afterwards. should be regular statement
789 * update/insert could better be one routine called save()
790 * that chooses to either insert or update depending if we
791 * have a primary key in the entity. i don't know if we
792 * still need the streamed input fields. // rk */
794 /** @todo extension: check if Entity did change, otherwise we don't need
795 * the roundtrip to the database */
797 /** invalidating corresponding entitylists in o_store*/
798 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
799 StoreContainerType stoc_type =
800 StoreContainerType.valueOf( theEntityClass,
801 StoreContainerType.STOC_TYPE_ENTITYLIST);
802 o_store.invalidate(stoc_type);
805 ArrayList streamedInput = theEntity.streamedInput();
806 String id = theEntity.getId();
808 StringBuffer fv = new StringBuffer();
809 boolean firstField = true;
811 invalidatePopupCache();
812 // build sql statement
813 for (int i = 0; i < getFields().size(); i++) {
814 aField = (String)metadataFields.get(i);
816 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
817 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
818 if (theEntity.hasValueForField(aField)) {
819 if (firstField == false) {
825 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
829 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
831 if (metadataFields.contains("webdb_lastchange")) {
832 sql.append(",webdb_lastchange=NOW()");
834 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
835 // format so anything extra will be ignored. -mh
836 if (metadataFields.contains("webdb_create") &&
837 theEntity.hasValueForField("webdb_create")) {
838 // minimum of 10 (yyyy-mm-dd)...
839 if (theEntity.getValue("webdb_create").length() >= 10) {
840 String dateString = theEntity.getValue("webdb_create");
841 // if only 10, then add 00:00 so it doesn't throw a ParseException
842 if (dateString.length() == 10)
843 dateString=dateString+" 00:00";
847 java.util.Date d = _dateFormatterIn.parse(dateString);
848 Timestamp tStamp = new Timestamp(d.getTime());
849 sql.append(",webdb_create='"+tStamp.toString()+"'");
850 } catch (ParseException e) {
851 throw new StorageObjectException(e.toString());
855 if (streamedInput != null) {
856 for (int i = 0; i < streamedInput.size(); i++) {
857 sql.append(",").append(streamedInput.get(i)).append("=?");
860 sql.append(" where id=").append(id);
861 theLog.printInfo("UPDATE: " + sql);
864 con = getPooledCon();
865 con.setAutoCommit(false);
866 pstmt = con.prepareStatement(sql.toString());
867 if (streamedInput != null) {
868 for (int i = 0; i < streamedInput.size(); i++) {
869 String inputString = theEntity.getValue((String)streamedInput.get(i));
870 pstmt.setBytes(i + 1, inputString.getBytes());
873 pstmt.executeUpdate();
874 } catch (SQLException sqe) {
875 throwSQLException(sqe, "update");
878 con.setAutoCommit(true);
879 } catch (Exception e) {
882 freeConnection(con, pstmt);
888 * @param id des zu loeschenden Datensatzes
889 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
891 public boolean delete (String id) throws StorageObjectException {
893 invalidatePopupCache();
894 // ostore send notification
895 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
896 String uniqueId = id;
897 if ( theEntityClass.equals(StorableObjectEntity.class) )
898 uniqueId+="@"+theTable;
899 theLog.printInfo("CACHE: (del) " + id);
900 StoreIdentifier search_sid =
901 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
902 o_store.invalidate(search_sid);
905 /** @todo could be prepared Statement */
906 Statement stmt = null; Connection con = null;
908 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
909 theLog.printInfo("DELETE " + sql);
911 con = getPooledCon(); stmt = con.createStatement();
912 res = stmt.executeUpdate(sql);
914 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
915 finally { freeConnection(con, stmt); }
917 return (res > 0) ? true : false;
920 /* noch nicht implementiert.
921 * @return immer false
923 public boolean delete (EntityList theEntityList) {
924 invalidatePopupCache();
929 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
930 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
933 public SimpleList getPopupData () throws StorageObjectException {
938 * Holt Daten fuer Popups.
939 * @param name Name des Feldes.
940 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
941 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
943 public SimpleList getPopupData (String name, boolean hasNullValue)
944 throws StorageObjectException {
945 return getPopupData(name, hasNullValue, null);
949 * Holt Daten fuer Popups.
950 * @param name Name des Feldes.
951 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
952 * @param where Schraenkt die Selektion der Datensaetze ein.
953 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
955 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
956 return getPopupData(name, hasNullValue, where, null);
960 * Holt Daten fuer Popups.
961 * @param name Name des Feldes.
962 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
963 * @param where Schraenkt die Selektion der Datensaetze ein.
964 * @param order Gibt ein Feld als Sortierkriterium an.
965 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
967 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
969 if (hasPopupCache && popupCache != null)
971 SimpleList simpleList = null;
972 Connection con = null;
973 Statement stmt = null;
975 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
976 .append(",").append(name).append(" from ")
978 if (where != null && !(where.length() == 0))
979 sql.append(" where ").append(where);
980 sql.append(" order by ");
981 if (order != null && !(order.length() == 0))
987 con = getPooledCon();
988 } catch (Exception e) {
989 throw new StorageObjectException(e.toString());
992 stmt = con.createStatement();
993 ResultSet rs = executeSql(stmt, sql.toString());
996 if (!evaluatedMetaData) get_meta_data();
997 simpleList = new SimpleList();
998 // if popup has null-selector
999 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
1001 SimpleHash popupDict;
1003 popupDict = new SimpleHash();
1004 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
1005 popupDict.put("value", rs.getString(2));
1006 simpleList.add(popupDict);
1010 } catch (Exception e) {
1011 theLog.printError("getPopupData: "+e.toString());
1012 throw new StorageObjectException(e.toString());
1014 freeConnection(con, stmt);
1017 if (hasPopupCache) popupCache = simpleList;
1022 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
1023 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
1024 * Tabellen Verwendung finden.
1025 * @return SimpleHash mit den Tabellezeilen.
1027 public SimpleHash getHashData () {
1028 /** @todo dangerous! this should have a flag to be enabled, otherwise
1029 * very big Hashes could be returned */
1030 if (hashCache == null) {
1032 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
1034 } catch (StorageObjectException e) {
1035 theLog.printDebugInfo(e.toString());
1041 /* invalidates the popupCache
1043 protected void invalidatePopupCache () {
1044 /** @todo invalidates toooo much */
1050 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1051 * @param stmt Statemnt
1052 * @param sql Sql-String
1054 * @exception StorageObjectException
1056 public ResultSet executeSql (Statement stmt, String sql)
1057 throws StorageObjectException, SQLException
1059 long startTime = System.currentTimeMillis();
1062 rs = stmt.executeQuery(sql);
1063 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1066 catch (SQLException e)
1068 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
1069 - startTime) + "ms. for: "+ sql);
1077 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
1078 * getimed und geloggt.
1079 * @param stmt PreparedStatement mit der SQL-Anweisung
1080 * @return Liefert ResultSet des Statements zurueck.
1081 * @exception StorageObjectException, SQLException
1083 public ResultSet executeSql (PreparedStatement stmt)
1084 throws StorageObjectException, SQLException {
1086 long startTime = (new java.util.Date()).getTime();
1087 ResultSet rs = stmt.executeQuery();
1088 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1093 * returns the number of rows in the table
1095 public int getSize(String where)
1096 throws SQLException,StorageObjectException
1098 long startTime = System.currentTimeMillis();
1099 String sql = "SELECT Count(*) FROM "+ theTable;
1100 if (where != null && !(where.length() == 0))
1101 sql = sql + " where " + where;
1102 Connection con = null;
1103 Statement stmt = null;
1107 con = getPooledCon();
1108 stmt = con.createStatement();
1109 ResultSet rs = executeSql(stmt,sql);
1111 result = rs.getInt(1);
1113 } catch (SQLException e) {
1114 theLog.printError(e.toString());
1116 freeConnection(con,stmt);
1118 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1119 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1124 public int executeUpdate(Statement stmt, String sql)
1125 throws StorageObjectException, SQLException
1128 long startTime = (new java.util.Date()).getTime();
1131 rs = stmt.executeUpdate(sql);
1132 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1135 catch (SQLException e)
1137 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1138 - startTime) + "ms. for: "+ sql);
1144 public int executeUpdate(String sql)
1145 throws StorageObjectException, SQLException
1148 long startTime = (new java.util.Date()).getTime();
1149 Connection con=null;PreparedStatement pstmt=null;
1152 pstmt = con.prepareStatement(sql);
1153 result = pstmt.executeUpdate();
1155 catch (Exception e) {
1156 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1157 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1159 finally { freeConnection(con,pstmt); }
1160 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1166 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1167 * @param md ResultSetMetaData
1168 * @exception StorageObjectException
1170 private void evalMetaData (ResultSetMetaData md)
1171 throws StorageObjectException {
1173 this.evaluatedMetaData = true;
1174 this.metadataFields = new ArrayList();
1175 this.metadataLabels = new ArrayList();
1176 this.metadataNotNullFields = new ArrayList();
1178 int numFields = md.getColumnCount();
1179 this.metadataTypes = new int[numFields];
1182 for (int i = 1; i <= numFields; i++) {
1183 aField = md.getColumnName(i);
1184 metadataFields.add(aField);
1185 metadataLabels.add(md.getColumnLabel(i));
1186 aType = md.getColumnType(i);
1187 metadataTypes[i - 1] = aType;
1188 if (aField.equals(thePKeyName)) {
1189 thePKeyType = aType; thePKeyIndex = i;
1191 if (md.isNullable(i) == md.columnNullable) {
1192 metadataNotNullFields.add(aField);
1195 } catch (SQLException e) {
1196 throwSQLException(e, "evalMetaData");
1201 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1202 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1204 private void get_meta_data () throws StorageObjectException {
1205 Connection con = null;
1206 PreparedStatement pstmt = null;
1207 String sql = "select * from " + theTable + " where 0=1";
1209 con = getPooledCon();
1210 pstmt = con.prepareStatement(sql);
1211 theLog.printInfo("METADATA: " + sql);
1212 ResultSet rs = pstmt.executeQuery();
1213 evalMetaData(rs.getMetaData());
1215 } catch (SQLException e) {
1216 throwSQLException(e, "get_meta_data");
1218 freeConnection(con, pstmt);
1223 public Connection getPooledCon() throws StorageObjectException {
1224 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1226 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1227 } catch (Exception e){
1228 throw new StorageObjectException("Could not find the PoolMan Driver"
1231 Connection con = null;
1233 con = SQLManager.getInstance().requestConnection();
1234 } catch(SQLException e){
1235 theLog.printError("could not connect to the database "+e.toString());
1236 System.err.println("could not connect to the database "+e.toString());
1237 throw new StorageObjectException("Could not connect to the database"+
1243 public void freeConnection (Connection con, Statement stmt)
1244 throws StorageObjectException {
1245 SQLManager.getInstance().closeStatement(stmt);
1246 SQLManager.getInstance().returnConnection(con);
1250 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1251 * @param sqe SQLException
1252 * @param wo Funktonsname, in der die SQLException geworfen wurde
1253 * @exception StorageObjectException
1255 protected void throwSQLException (SQLException sqe, String wo)
1256 throws StorageObjectException {
1258 String message = "";
1261 state = sqe.getSQLState();
1262 message = sqe.getMessage();
1263 vendor = sqe.getErrorCode();
1265 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1267 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1271 protected void _throwStorageObjectException (Exception e, String wo)
1272 throws StorageObjectException {
1274 theLog.printError(e.toString()+ wo);
1275 throw new StorageObjectException(wo + e.toString());
1277 theLog.printError(wo);
1278 throw new StorageObjectException(wo);
1284 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1285 * eine StorageObjectException
1286 * @param message Nachricht mit dem Fehler
1287 * @exception StorageObjectException
1289 void throwStorageObjectException (String message)
1290 throws StorageObjectException {
1291 _throwStorageObjectException(null, message);