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 any library licensed under the Apache Software License,
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23 * (or with modified versions of the above that use the same license as the above),
24 * and distribute linked combinations including the two. You must obey the
25 * GNU General Public License in all respects for all of the code used other than
26 * the above mentioned libraries. If you modify this file, you may extend this
27 * exception to your version of the file, but you are not obligated to do so.
28 * If you do not wish to do so, delete this exception statement from your version.
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.sql.Connection;
35 import java.sql.PreparedStatement;
36 import java.sql.ResultSet;
37 import java.sql.ResultSetMetaData;
38 import java.sql.SQLException;
39 import java.sql.Statement;
40 import java.sql.Timestamp;
41 import java.text.ParseException;
42 import java.text.SimpleDateFormat;
43 import java.util.ArrayList;
44 import java.util.Calendar;
45 import java.util.GregorianCalendar;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.List;
50 import java.util.TimeZone;
51 import java.util.Vector;
53 import mir.config.MirPropertiesConfiguration;
54 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
55 import mir.entity.Entity;
56 import mir.entity.EntityList;
57 import mir.entity.StorableObjectEntity;
58 import mir.log.LoggerWrapper;
59 import mir.misc.StringUtil;
60 import mir.storage.store.ObjectStore;
61 import mir.storage.store.StorableObject;
62 import mir.storage.store.StoreContainerType;
63 import mir.storage.store.StoreIdentifier;
64 import mir.storage.store.StoreUtil;
65 import mir.util.JDBCStringRoutines;
67 import com.codestudio.util.SQLManager;
71 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
72 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
73 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
74 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
75 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
78 * @version $Id: Database.java,v 1.44.2.7 2003/10/23 14:55:29 rk Exp $
82 public class Database implements StorageObject {
83 private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
84 private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
87 private static Map POPUP_EMPTYLINE = new HashMap();
88 protected static final ObjectStore o_store = ObjectStore.getInstance();
89 private static final int _millisPerHour = 60 * 60 * 1000;
90 private static final int _millisPerMinute = 60 * 1000;
93 // always same object saves a little space
94 POPUP_EMPTYLINE.put("key", "");
95 POPUP_EMPTYLINE.put("value", "--");
98 protected LoggerWrapper logger;
99 protected MirPropertiesConfiguration configuration;
100 protected String theTable;
101 protected String theCoreTable = null;
102 protected String thePKeyName = "id";
103 protected int thePKeyType;
104 protected int thePKeyIndex;
105 protected boolean evaluatedMetaData = false;
106 protected ArrayList metadataFields;
107 protected ArrayList metadataLabels;
108 protected ArrayList metadataNotNullFields;
109 protected int[] metadataTypes;
110 protected Class theEntityClass;
111 protected List popupCache = null;
112 protected boolean hasPopupCache = false;
113 protected Map hashCache = null;
114 protected boolean hasTimestamp = true;
115 private String database_driver;
116 private String database_url;
117 private int defaultLimit;
120 SimpleDateFormat internalDateFormat;
121 SimpleDateFormat userInputDateFormat;
123 private SimpleDateFormat _dateFormatterOut;
124 private SimpleDateFormat _dateFormatterIn;
125 _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
126 _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");
130 * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
131 * Aus diesem file werden <code>Database.Logfile</code>,
132 * <code>Database.Username</code>,<code>Database.Password</code>,
133 * <code>Database.Host</code> und <code>Database.Adaptor</code>
134 * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
137 * @param String confFilename Dateiname der Konfigurationsdatei
139 public Database() throws StorageObjectFailure {
141 configuration = MirPropertiesConfiguration.instance();
143 catch (PropertiesConfigExc e) {
144 throw new StorageObjectFailure(e);
146 logger = new LoggerWrapper("Database");
147 timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
148 internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
149 internalDateFormat.setTimeZone(timezone);
151 userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
152 userInputDateFormat.setTimeZone(timezone);
155 String theAdaptorName = configuration.getString("Database.Adaptor");
156 defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
159 theEntityClass = GENERIC_ENTITY_CLASS;
161 catch (Throwable e) {
162 logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
163 throw new StorageObjectFailure("Error in Database() constructor.", e);
168 * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
169 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
170 * wird eine mir.entity.GenericEntity erzeugt.
172 * @return Class-Objekt der Entity
174 public java.lang.Class getEntityClass() {
175 return theEntityClass;
179 * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
180 * wieviel Datens?tze per Default selektiert werden.
182 * @return Standard-Anzahl der Datens?tze
184 public int getLimit() {
189 * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
190 * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
191 * @return Name des Primary-Keys
193 public String getIdName() {
198 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
200 * @return Name der Tabelle
202 public String getTableName() {
207 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
208 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
210 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
213 public String getCoreTable() {
214 if (theCoreTable != null) {
223 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
224 * @return int-Array mit den Typen der Felder
225 * @exception StorageObjectException
227 public int[] getTypes() throws StorageObjectFailure {
228 if (metadataTypes == null) {
232 return metadataTypes;
236 * Liefert eine Liste der Labels der Tabellenfelder
237 * @return ArrayListe mit Labeln
238 * @exception StorageObjectException
240 public List getLabels() throws StorageObjectFailure {
241 if (metadataLabels == null) {
245 return metadataLabels;
249 * Liefert eine Liste der Felder der Tabelle
250 * @return ArrayList mit Feldern
251 * @exception StorageObjectException
253 public List getFields() throws StorageObjectFailure {
254 if (metadataFields == null) {
258 return metadataFields;
262 * Gets value out of ResultSet according to type and converts to String
263 * @param inValue Wert aus ResultSet.
264 * @param aType Datenbanktyp.
265 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
266 * dann /unsupported value/
268 private String getValueAsString(ResultSet rs, int valueIndex, int aType)
269 throws StorageObjectFailure {
270 String outValue = null;
275 case java.sql.Types.BIT:
276 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
280 case java.sql.Types.INTEGER:
281 case java.sql.Types.SMALLINT:
282 case java.sql.Types.TINYINT:
283 case java.sql.Types.BIGINT:
285 int out = rs.getInt(valueIndex);
288 outValue = new Integer(out).toString();
293 case java.sql.Types.NUMERIC:
295 /** @todo Numeric can be float or double depending upon
296 * metadata.getScale() / especially with oracle */
297 long outl = rs.getLong(valueIndex);
300 outValue = new Long(outl).toString();
305 case java.sql.Types.REAL:
307 float tempf = rs.getFloat(valueIndex);
313 int tempf_int = (int) tempf;
314 tempf = (float) tempf_int;
316 outValue = "" + tempf;
317 outValue = outValue.replace('.', ',');
322 case java.sql.Types.DOUBLE:
324 double tempd = rs.getDouble(valueIndex);
330 int tempd_int = (int) tempd;
331 tempd = (double) tempd_int;
333 outValue = "" + tempd;
334 outValue = outValue.replace('.', ',');
339 case java.sql.Types.CHAR:
340 case java.sql.Types.VARCHAR:
341 case java.sql.Types.LONGVARCHAR:
342 outValue = rs.getString(valueIndex);
346 case java.sql.Types.LONGVARBINARY:
347 outValue = rs.getString(valueIndex);
351 case java.sql.Types.TIMESTAMP:
353 // it's important to use Timestamp here as getting it
354 // as a string is undefined and is only there for debugging
355 // according to the API. we can make it a string through formatting.
357 Timestamp timestamp = (rs.getTimestamp(valueIndex));
360 java.util.Date date = new java.util.Date(timestamp.getTime());
362 Calendar calendar = new GregorianCalendar();
363 calendar.setTime(date);
364 calendar.setTimeZone(timezone);
365 outValue = internalDateFormat.format(date);
367 int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
368 String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
371 outValue = outValue + "-";
373 outValue = outValue + "+";
374 outValue = outValue + tzOffset;
380 outValue = "<unsupported value>";
381 logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
383 } catch (SQLException e) {
384 throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
393 * select-Operator um einen Datensatz zu bekommen.
394 * @param id Primaerschluessel des Datensatzes.
395 * @return liefert EntityObject des gefundenen Datensatzes oder null.
397 public Entity selectById(String id) throws StorageObjectExc {
398 if ((id == null) || id.equals("")) {
399 throw new StorageObjectExc("Database.selectById: Missing id");
402 // ask object store for object
403 if (StoreUtil.implementsStorableObject(theEntityClass)) {
404 String uniqueId = id;
406 if (theEntityClass.equals(StorableObjectEntity.class)) {
407 uniqueId += ("@" + theTable);
410 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
411 logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
413 Entity hit = (Entity) o_store.use(search_sid);
420 Statement stmt = null;
421 Connection con = getPooledCon();
422 Entity returnEntity = null;
427 /** @todo better prepared statement */
429 "select * from " + theTable + " where " + thePKeyName + "=" + id;
430 stmt = con.createStatement();
431 rs = executeSql(stmt, selectSql);
434 if (evaluatedMetaData == false) {
435 evalMetaData(rs.getMetaData());
439 returnEntity = makeEntityFromResultSet(rs);
442 logger.debug("No data for id: " + id + " in table " + theTable);
448 logger.debug("No Data for Id " + id + " in Table " + theTable);
451 catch (SQLException sqe) {
452 throwSQLException(sqe, "selectById");
455 catch (NumberFormatException e) {
456 logger.error("ID is no number: " + id);
459 freeConnection(con, stmt);
466 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
467 * @param key Datenbankfeld der Bedingung.
468 * @param value Wert die der key anehmen muss.
469 * @return EntityList mit den gematchten Entities
471 public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
472 return selectByFieldValue(aField, aValue, 0);
476 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
477 * @param key Datenbankfeld der Bedingung.
478 * @param value Wert die der key anehmen muss.
479 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
480 * @return EntityList mit den gematchten Entities
482 public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
483 return selectByWhereClause(aField + "=" + aValue, offset);
487 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
488 * Also offset wird der erste Datensatz genommen.
490 * @param wc where-Clause
491 * @return EntityList mit den gematchten Entities
492 * @exception StorageObjectException
494 public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
495 return selectByWhereClause(where, 0);
499 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
500 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
502 * @param wc where-Clause
503 * @param offset ab welchem Datensatz.
504 * @return EntityList mit den gematchten Entities
505 * @exception StorageObjectException
507 public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
508 return selectByWhereClause(whereClause, null, offset);
512 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
513 * Also offset wird der erste Datensatz genommen.
514 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
516 * @param wc where-Clause
517 * @param ob orderBy-Clause
518 * @return EntityList mit den gematchten Entities
519 * @exception StorageObjectException
521 public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
522 return selectByWhereClause(where, order, 0);
526 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
527 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
529 * @param wc where-Clause
530 * @param ob orderBy-Clause
531 * @param offset ab welchem Datensatz
532 * @return EntityList mit den gematchten Entities
533 * @exception StorageObjectException
535 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
536 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
540 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
541 * @param aWhereClause where-Clause
542 * @param anOrderByClause orderBy-Clause
543 * @param offset ab welchem Datensatz
544 * @param limit wieviele Datens?tze
545 * @return EntityList mit den gematchten Entities
546 * @exception StorageObjectException
548 public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
549 int offset, int limit) throws StorageObjectFailure {
551 // check o_store for entitylist
552 if (StoreUtil.implementsStorableObject(theEntityClass)) {
553 StoreIdentifier search_sid =
555 theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
556 StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));
557 EntityList hit = (EntityList) o_store.use(search_sid);
560 logger.debug("CACHE (hit): " + search_sid.toString());
567 EntityList theReturnList = null;
568 Connection con = null;
569 Statement stmt = null;
574 // build sql-statement
576 /** @todo count sql string should only be assembled if we really count
577 * see below at the end of method //rk */
578 if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
582 StringBuffer countSql =
583 new StringBuffer("select count(*) from ").append(theTable);
584 StringBuffer selectSql =
585 new StringBuffer("select * from ").append(theTable);
587 if (aWhereClause != null) {
588 selectSql.append(" where ").append(aWhereClause);
589 countSql.append(" where ").append(aWhereClause);
592 if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
593 selectSql.append(" order by ").append(anOrderByClause);
596 if ((limit > -1) && (offset > -1)) {
597 selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
602 con = getPooledCon();
603 stmt = con.createStatement();
606 rs = executeSql(stmt, selectSql.toString());
609 if (!evaluatedMetaData) {
610 evalMetaData(rs.getMetaData());
613 theReturnList = new EntityList();
615 Entity theResultEntity;
618 theResultEntity = makeEntityFromResultSet(rs);
619 theReturnList.add(theResultEntity);
626 // making entitylist infos
629 if (theReturnList != null) {
630 // now we decide if we have to know an overall count...
633 if ((limit > -1) && (offset > -1)) {
634 if (offsetCount == limit) {
635 /** @todo counting should be deffered to entitylist
636 * getSize() should be used */
637 rs = executeSql(stmt, countSql.toString());
641 count = rs.getInt(1);
647 logger.error("Could not count: " + countSql);
652 theReturnList.setCount(count);
653 theReturnList.setOffset(offset);
654 theReturnList.setWhere(aWhereClause);
655 theReturnList.setOrder(anOrderByClause);
656 theReturnList.setStorage(this);
657 theReturnList.setLimit(limit);
659 if (offset >= limit) {
660 theReturnList.setPrevBatch(offset - limit);
663 if ((offset + offsetCount) < count) {
664 theReturnList.setNextBatch(offset + limit);
667 if (StoreUtil.implementsStorableObject(theEntityClass)) {
668 StoreIdentifier sid = theReturnList.getStoreIdentifier();
669 logger.debug("CACHE (add): " + sid.toString());
674 catch (SQLException sqe) {
675 throwSQLException(sqe, "selectByWhereClause");
680 freeConnection(con, stmt);
682 } catch (Throwable t) {
686 return theReturnList;
690 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
692 * @param rs Das ResultSetObjekt.
693 * @return Entity Die Entity.
695 private Entity makeEntityFromResultSet(ResultSet rs)
696 throws StorageObjectFailure {
697 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
698 Map theResultHash = new HashMap();
699 String theResult = null;
701 Entity returnEntity = null;
704 int size = metadataFields.size();
706 for (int i = 0; i < size; i++) {
707 // alle durchlaufen bis nix mehr da
708 theType = metadataTypes[i];
710 if (theType == java.sql.Types.LONGVARBINARY) {
711 InputStreamReader is =
712 (InputStreamReader) rs.getCharacterStream(i + 1);
715 char[] data = new char[32768];
716 StringBuffer theResultString = new StringBuffer();
719 while ((len = is.read(data)) > 0) {
720 theResultString.append(data, 0, len);
724 theResult = theResultString.toString();
729 theResult = getValueAsString(rs, (i + 1), theType);
732 if (theResult != null) {
733 theResultHash.put(metadataFields.get(i), theResult);
737 if (theEntityClass != null) {
738 returnEntity = (Entity) theEntityClass.newInstance();
739 returnEntity.setStorage(this);
740 returnEntity.setValues(theResultHash);
742 if (returnEntity instanceof StorableObject) {
743 logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
744 o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
747 throwStorageObjectException("Internal Error: theEntityClass not set!");
750 catch (IllegalAccessException e) {
751 throwStorageObjectException("No access! -- " + e.getMessage());
753 catch (IOException e) {
754 throwStorageObjectException("IOException! -- " + e.getMessage());
756 catch (InstantiationException e) {
757 throwStorageObjectException("No Instatiation! -- " + e.getMessage());
759 catch (SQLException sqe) {
760 throwSQLException(sqe, "makeEntityFromResultSet");
769 * Inserts an entity into the database.
772 * @return der Wert des Primary-keys der eingef?gten Entity
774 public String insert(Entity theEntity) throws StorageObjectFailure {
776 invalidatePopupCache();
778 // invalidating all EntityLists corresponding with theEntityClass
779 if (StoreUtil.implementsStorableObject(theEntityClass)) {
780 StoreContainerType stoc_type =
781 StoreContainerType.valueOf(theEntityClass,
782 StoreContainerType.STOC_TYPE_ENTITYLIST);
783 o_store.invalidate(stoc_type);
786 String returnId = null;
787 Connection con = null;
788 PreparedStatement pstmt = null;
791 List streamedInput = theEntity.streamedInput();
792 StringBuffer f = new StringBuffer();
793 StringBuffer v = new StringBuffer();
796 boolean firstField = true;
799 for (int i = 0; i < getFields().size(); i++) {
800 aField = (String) getFields().get(i);
802 if (!aField.equals(thePKeyName)) {
806 if (!theEntity.hasValueForField(aField) && (
807 aField.equals("webdb_create") ||
808 aField.equals("webdb_lastchange"))) {
812 if ((streamedInput != null) && streamedInput.contains(aField)) {
816 if (theEntity.hasValueForField(aField)) {
819 JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";
824 // wenn Wert gegeben, dann einbauen
825 if (aValue != null) {
826 if (firstField == false) {
842 StringBuffer sqlBuf =
843 new StringBuffer("insert into ").append(theTable).append("(").append(f)
844 .append(") values (").append(v).append(")");
845 String sql = sqlBuf.toString();
847 logger.debug("INSERT: " + sql);
848 con = getPooledCon();
849 con.setAutoCommit(false);
850 pstmt = con.prepareStatement(sql);
852 if (streamedInput != null) {
853 for (int i = 0; i < streamedInput.size(); i++) {
855 (String) theEntity.getValue((String) streamedInput.get(i));
856 pstmt.setBytes(i + 1, inputString.getBytes());
860 int ret = pstmt.executeUpdate();
867 pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");
869 ResultSet rs = pstmt.executeQuery();
871 returnId = rs.getString(1);
872 theEntity.setId(returnId);
874 catch (SQLException sqe) {
875 throwSQLException(sqe, "insert");
879 con.setAutoCommit(true);
881 catch (Exception e) {
884 freeConnection(con, pstmt);
887 /** @todo store entity in o_store */
892 * Updates an entity in the database
896 public void update(Entity theEntity) throws StorageObjectFailure {
897 Connection con = null;
898 PreparedStatement pstmt = null;
900 /** @todo this is stupid: why do we prepare statement, when we
901 * throw it away afterwards. should be regular statement
902 * update/insert could better be one routine called save()
903 * that chooses to either insert or update depending if we
904 * have a primary key in the entity. i don't know if we
905 * still need the streamed input fields. // rk */
906 /** @todo extension: check if Entity did change, otherwise we don't need
907 * the roundtrip to the database */
908 /** invalidating corresponding entitylists in o_store*/
909 if (StoreUtil.implementsStorableObject(theEntityClass)) {
910 StoreContainerType stoc_type =
911 StoreContainerType.valueOf(theEntityClass,
912 StoreContainerType.STOC_TYPE_ENTITYLIST);
913 o_store.invalidate(stoc_type);
916 List streamedInput = theEntity.streamedInput();
917 String id = theEntity.getId();
919 StringBuffer fv = new StringBuffer();
920 boolean firstField = true;
923 invalidatePopupCache();
925 // build sql statement
926 for (int i = 0; i < getFields().size(); i++) {
927 aField = (String) metadataFields.get(i);
930 if ( !(aField.equals(thePKeyName) ||
931 aField.equals("webdb_create") ||
932 aField.equals("webdb_lastchange") ||
933 ((streamedInput != null) && streamedInput.contains(aField)))) {
934 if (theEntity.hasValueForField(aField)) {
935 if (firstField == false) {
942 fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
944 // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
950 new StringBuffer("update ").append(theTable).append(" set ").append(fv);
953 if (metadataFields.contains("webdb_lastchange")) {
954 sql.append(",webdb_lastchange=NOW()");
957 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
958 // format so anything extra will be ignored. -mh
959 if (metadataFields.contains("webdb_create") &&
960 theEntity.hasValueForField("webdb_create")) {
961 // minimum of 10 (yyyy-mm-dd)...
962 if (theEntity.getValue("webdb_create").length() >= 10) {
963 String dateString = theEntity.getValue("webdb_create");
965 // if only 10, then add 00:00 so it doesn't throw a ParseException
966 if (dateString.length() == 10) {
967 dateString = dateString + " 00:00";
972 java.util.Date d = userInputDateFormat.parse(dateString);
973 // Timestamp tStamp = new Timestamp(d.getTime());
974 sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
976 catch (ParseException e) {
977 throw new StorageObjectFailure(e);
982 if (streamedInput != null) {
983 for (int i = 0; i < streamedInput.size(); i++) {
984 sql.append(",").append(streamedInput.get(i)).append("=?");
988 sql.append(" where id=").append(id);
989 logger.debug("UPDATE: " + sql);
992 con = getPooledCon();
993 con.setAutoCommit(false);
994 pstmt = con.prepareStatement(sql.toString());
996 if (streamedInput != null) {
997 for (int i = 0; i < streamedInput.size(); i++) {
999 theEntity.getValue((String) streamedInput.get(i));
1000 pstmt.setBytes(i + 1, inputString.getBytes());
1004 pstmt.executeUpdate();
1006 catch (SQLException sqe) {
1007 throwSQLException(sqe, "update");
1011 con.setAutoCommit(true);
1013 catch (Exception e) {
1017 freeConnection(con, pstmt);
1023 * @param id des zu loeschenden Datensatzes
1024 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
1026 public boolean delete(String id) throws StorageObjectFailure {
1027 invalidatePopupCache();
1029 // ostore send notification
1030 if (StoreUtil.implementsStorableObject(theEntityClass)) {
1031 String uniqueId = id;
1033 if (theEntityClass.equals(StorableObjectEntity.class)) {
1034 uniqueId += ("@" + theTable);
1037 logger.debug("CACHE: (del) " + id);
1039 StoreIdentifier search_sid =
1040 new StoreIdentifier(theEntityClass,
1041 StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
1042 o_store.invalidate(search_sid);
1045 /** @todo could be prepared Statement */
1046 Statement stmt = null;
1047 Connection con = null;
1050 "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
1052 //theLog.printInfo("DELETE " + sql);
1054 con = getPooledCon();
1055 stmt = con.createStatement();
1056 res = stmt.executeUpdate(sql);
1057 } catch (SQLException sqe) {
1058 throwSQLException(sqe, "delete");
1060 freeConnection(con, stmt);
1063 return (res > 0) ? true : false;
1067 * Deletes entities based on a where clause
1069 * @param aWhereClause
1071 * @throws StorageObjectFailure
1073 public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
1074 invalidatePopupCache();
1075 if (StoreUtil.implementsStorableObject(theEntityClass)) {
1076 StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
1077 o_store.invalidate(stoc_type);
1080 Statement stmt = null;
1081 Connection con = null;
1084 "delete from " + theTable + " where " + aWhereClause;
1086 //theLog.printInfo("DELETE " + sql);
1088 con = getPooledCon();
1089 stmt = con.createStatement();
1090 res = stmt.executeUpdate(sql);
1092 catch (SQLException sqe) {
1093 throwSQLException(sqe, "delete");
1096 freeConnection(con, stmt);
1102 /* noch nicht implementiert.
1103 * @return immer false
1105 public boolean delete(EntityList theEntityList) {
1106 invalidatePopupCache();
1111 /* invalidates the popupCache
1113 protected void invalidatePopupCache() {
1114 /** @todo invalidates toooo much */
1120 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1121 * @param stmt Statemnt
1122 * @param sql Sql-String
1124 * @exception StorageObjectException
1126 public ResultSet executeSql(Statement stmt, String sql)
1127 throws StorageObjectFailure, SQLException {
1129 long startTime = System.currentTimeMillis();
1132 rs = stmt.executeQuery(sql);
1134 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1136 catch (SQLException e) {
1137 logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1144 public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
1145 long startTime = System.currentTimeMillis();
1146 Connection connection = null;
1147 Statement statement = null;
1150 connection = getPooledCon();
1151 statement = connection.createStatement();
1154 result = statement.executeQuery(sql);
1156 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1159 catch (Throwable e) {
1160 logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1161 throw new StorageObjectFailure(e);
1164 if (connection!=null) {
1165 freeConnection(connection, statement);
1170 private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
1172 Map result = new HashMap();
1173 ResultSetMetaData metaData = aResultSet.getMetaData();
1174 int nrColumns = metaData.getColumnCount();
1175 for (int i=0; i<nrColumns; i++) {
1176 result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
1181 catch (Throwable e) {
1182 throw new StorageObjectFailure(e);
1186 public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
1187 Connection connection = null;
1188 Statement statement = null;
1190 List result = new Vector();
1191 connection = getPooledCon();
1192 statement = connection.createStatement();
1193 ResultSet resultset = executeSql(statement, sql);
1195 while (resultset.next() && result.size() < aLimit) {
1196 result.add(processRow(resultset));
1205 catch (Throwable e) {
1206 throw new StorageObjectFailure(e);
1209 if (connection!=null) {
1210 freeConnection(connection, statement);
1215 public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
1217 List resultList = executeFreeSql(anSqlStatement, 1);
1219 if (resultList.size()>0)
1220 return (Map) resultList.get(0);
1227 catch (Throwable t) {
1228 throw new StorageObjectFailure(t);
1232 public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
1233 Map row = executeFreeSingleRowSql(sql);
1238 Iterator i = row.values().iterator();
1240 return (String) i.next();
1246 * returns the number of rows in the table
1248 public int getSize(String where) throws SQLException, StorageObjectFailure {
1249 long startTime = System.currentTimeMillis();
1250 String sql = "SELECT Count(*) FROM " + theTable;
1252 if ((where != null) && (where.length() != 0)) {
1253 sql = sql + " where " + where;
1256 Connection con = null;
1257 Statement stmt = null;
1261 con = getPooledCon();
1262 stmt = con.createStatement();
1264 ResultSet rs = executeSql(stmt, sql);
1267 result = rs.getInt(1);
1270 catch (SQLException e) {
1271 logger.error("Database.getSize: " + e.getMessage());
1274 freeConnection(con, stmt);
1277 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1278 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1283 public int executeUpdate(Statement stmt, String sql)
1284 throws StorageObjectFailure, SQLException {
1286 long startTime = System.currentTimeMillis();
1289 rs = stmt.executeUpdate(sql);
1291 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1293 catch (SQLException e) {
1294 logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1301 public int executeUpdate(String sql)
1302 throws StorageObjectFailure, SQLException {
1304 long startTime = System.currentTimeMillis();
1305 Connection con = null;
1306 PreparedStatement pstmt = null;
1309 con = getPooledCon();
1310 pstmt = con.prepareStatement(sql);
1311 result = pstmt.executeUpdate();
1313 catch (Throwable e) {
1314 logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
1315 throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
1318 freeConnection(con, pstmt);
1321 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1326 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1327 * @param md ResultSetMetaData
1328 * @exception StorageObjectException
1330 private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
1331 this.evaluatedMetaData = true;
1332 this.metadataFields = new ArrayList();
1333 this.metadataLabels = new ArrayList();
1334 this.metadataNotNullFields = new ArrayList();
1337 int numFields = md.getColumnCount();
1338 this.metadataTypes = new int[numFields];
1343 for (int i = 1; i <= numFields; i++) {
1344 aField = md.getColumnName(i);
1345 metadataFields.add(aField);
1346 metadataLabels.add(md.getColumnLabel(i));
1347 aType = md.getColumnType(i);
1348 metadataTypes[i - 1] = aType;
1350 if (aField.equals(thePKeyName)) {
1351 thePKeyType = aType;
1355 if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
1356 metadataNotNullFields.add(aField);
1360 catch (SQLException e) {
1361 throwSQLException(e, "evalMetaData");
1366 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1367 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1369 private void get_meta_data() throws StorageObjectFailure {
1370 Connection con = null;
1371 PreparedStatement pstmt = null;
1372 String sql = "select * from " + theTable + " where 0=1";
1375 con = getPooledCon();
1376 pstmt = con.prepareStatement(sql);
1378 logger.debug("METADATA: " + sql);
1379 ResultSet rs = pstmt.executeQuery();
1380 evalMetaData(rs.getMetaData());
1383 catch (SQLException e) {
1384 throwSQLException(e, "get_meta_data");
1387 freeConnection(con, pstmt);
1391 public Connection getPooledCon() throws StorageObjectFailure {
1392 Connection con = null;
1395 con = SQLManager.getInstance().requestConnection();
1397 catch (SQLException e) {
1398 logger.error("could not connect to the database " + e.getMessage());
1400 throw new StorageObjectFailure("Could not connect to the database", e);
1406 public void freeConnection(Connection con, Statement stmt)
1407 throws StorageObjectFailure {
1408 SQLManager.closeStatement(stmt);
1409 SQLManager.getInstance().returnConnection(con);
1413 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1414 * @param sqe SQLException
1415 * @param wo Funktonsname, in der die SQLException geworfen wurde
1416 * @exception StorageObjectException
1418 protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {
1420 String message = "";
1424 state = sqe.getSQLState();
1425 message = sqe.getMessage();
1426 vendor = sqe.getErrorCode();
1429 String information =
1432 ", vendor= " + vendor +
1433 ", message=" + message +
1434 ", function= " + aFunction;
1436 logger.error(information);
1438 throw new StorageObjectFailure(information, sqe);
1441 protected void _throwStorageObjectException(Exception e, String aFunction)
1442 throws StorageObjectFailure {
1445 logger.error(e.getMessage() + aFunction);
1446 throw new StorageObjectFailure(aFunction, e);
1451 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1452 * eine StorageObjectException
1453 * @param message Nachricht mit dem Fehler
1454 * @exception StorageObjectException
1456 void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
1457 logger.error(aMessage);
1458 throw new StorageObjectFailure(aMessage, null);