From b5dfdb12e72c15762c6a9d21a3d37db9ba97c92a Mon Sep 17 00:00:00 2001 From: zapata Date: Thu, 20 Feb 2003 16:05:32 +0000 Subject: [PATCH] support for translations + lots of misc. fixes --- source/mir/entity/Entity.java | 654 +++-- source/mir/entity/QueryBuilder.java | 87 - source/mir/generator/FreemarkerGenerator.java | 685 ++--- source/mir/log/LoggerWrapper.java | 6 + .../mir/producer/reader/ProducerConfigReader.java | 18 +- source/mir/servlet/AbstractServlet.java | 37 +- source/mir/servlet/ServletModule.java | 14 +- source/mir/servlet/ServletModuleException.java | 100 +- source/mir/storage/Database.java | 2932 ++++++++++---------- source/mir/storage/StorageObject.java | 6 +- source/mir/storage/store/ObjectStore.java | 561 ++-- source/mir/util/SQLQueryBuilder.java | 57 + source/mir/util/XMLReader.java | 23 +- source/mircoders/entity/EntityBreaking.java | 81 - source/mircoders/entity/EntityUploadedMedia.java | 4 +- source/mircoders/global/MirGlobal.java | 8 +- .../localizer/MirAdminInterfaceLocalizer.java | 18 + .../basic/MirBasicAdminInterfaceLocalizer.java | 14 +- .../basic/MirBasicDataModelLocalizer.java | 36 + .../basic/MirBasicGeneratorLocalizer.java | 7 +- .../localizer/basic/MirBasicLocalizer.java | 1 - .../basic/MirBasicOpenPostingLocalizer.java | 9 +- .../basic/MirBasicProducerAssistantLocalizer.java | 13 +- .../localizer/basic/MirBasicProducerLocalizer.java | 12 +- source/mircoders/servlet/ServletModuleContent.java | 1084 ++++---- source/mircoders/storage/DatabaseArticleType.java | 2 + source/mircoders/storage/DatabaseAudio.java | 201 +- source/mircoders/storage/DatabaseBreaking.java | 3 +- source/mircoders/storage/DatabaseComment.java | 213 +- .../mircoders/storage/DatabaseCommentStatus.java | 6 +- source/mircoders/storage/DatabaseContent.java | 24 +- .../mircoders/storage/DatabaseContentToMedia.java | 1087 ++++---- .../mircoders/storage/DatabaseContentToTopics.java | 56 +- source/mircoders/storage/DatabaseFeature.java | 156 +- source/mircoders/storage/DatabaseImageColor.java | 146 +- source/mircoders/storage/DatabaseImageFormat.java | 147 +- source/mircoders/storage/DatabaseImageLayout.java | 148 +- source/mircoders/storage/DatabaseImageType.java | 147 +- source/mircoders/storage/DatabaseImages.java | 212 +- source/mircoders/storage/DatabaseLanguage.java | 6 +- source/mircoders/storage/DatabaseLinksImcs.java | 64 +- source/mircoders/storage/DatabaseMedia.java | 39 +- source/mircoders/storage/DatabaseMediaType.java | 17 +- source/mircoders/storage/DatabaseMediafolder.java | 15 +- source/mircoders/storage/DatabaseMessages.java | 10 +- source/mircoders/storage/DatabaseOther.java | 208 +- source/mircoders/storage/DatabaseRights.java | 148 +- source/mircoders/storage/DatabaseTopics.java | 157 +- .../mircoders/storage/DatabaseUploadedMedia.java | 14 +- source/mircoders/storage/DatabaseUsers.java | 152 +- source/mircoders/storage/DatabaseVideo.java | 205 +- 51 files changed, 5061 insertions(+), 4989 deletions(-) delete mode 100755 source/mir/entity/QueryBuilder.java create mode 100755 source/mir/util/SQLQueryBuilder.java delete mode 100755 source/mircoders/entity/EntityBreaking.java diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index 5a69e3e2..e37ea7a0 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -1,332 +1,322 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -/** - * Base class the entities are derived from. Provides base functionality of - * an entity. Entities are used to represent rows of a database table.

- */ - -package mir.entity; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Set; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.misc.Logfile; -import mir.misc.StringUtil; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateHashModel; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateModelRoot; - -/** - * Base Class of Entities - * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant - * - * @version $Id: Entity.java,v 1.13 2003/01/25 17:45:17 idfx Exp $ - * @author rk - * - */ - -public class Entity implements TemplateHashModel, TemplateModelRoot -{ - protected static MirPropertiesConfiguration configuration; - protected static Logfile theLog; - - private boolean changed; - protected HashMap theValuesHash; // tablekey / value - protected StorageObject theStorageObject; - protected ArrayList streamedInput=null; - - - static { - try { - configuration = MirPropertiesConfiguration.instance(); - } catch (PropertiesConfigExc e) { - e.printStackTrace(); - } - theLog = Logfile.getInstance(configuration.getStringWithHome("Entity.Logfile")); - } - - public Entity() { - this.changed = false; - } - - /** - * Constructor - * @param StorageObject The StorageObject of the Entity. - */ - public Entity (StorageObject StorageObject) { - this(); - setStorage(StorageObject); - } - - /* - * Sets the StorageObject of the Entity. - */ - public void setStorage (StorageObject storage) { - this.theStorageObject = storage; - } - - /** - * Sets the values of the Entity. - * @param theStringValues HashMap containing the new values of the Entity - */ - - public void setValues(HashMap theStringValues) - { - /** @todo should be synchronized */ - if (theStringValues!=null) { - theValuesHash = new HashMap(); - String aKey; - Set set = theStringValues.keySet(); - Iterator it = set.iterator(); - int size = set.size(); - for (int i = 0; i < size; i++) { - aKey = (String)it.next(); - theValuesHash.put(aKey, (String)theStringValues.get(aKey)); - } - } - else theLog.printWarning("Entity.setValues called with null HashMap"); - } - - /** - * Returns whether the content of the Entity has changed. - * @return true wenn ja, sonst false - */ - public boolean changed () { - return changed; - } - - /** - * Returns the primary key of the Entity. - * @return String Id - */ - public String getId () { - return (String) getValue(theStorageObject.getIdName()); - } - - /** - * Defines the primary key of the Entity - * @param id - */ - public void setId (String id) { - theValuesHash.put(theStorageObject.getIdName(), id); - } - - /** - * Returns the value of a field by field name. - * @param field The name of the field - * @return value of the field - */ - public String getValue (String field) { - String returnValue = null; - if (field != null) - { - if (field.equals("webdb_create_formatted")) - { - if (hasValueForField("webdb_create")) - returnValue=StringUtil.dateToReadableDate(getValue("webdb_create")); - } - else if (field.equals("webdb_lastchange_formatted")) - { - if (hasValueForField("webdb_lastchange")) - returnValue=StringUtil.dateToReadableDate(getValue("webdb_lastchange")); - } - else - returnValue = (String)theValuesHash.get(field); - } - return returnValue; - } - - public boolean hasValueForField(String field) - { - if (theValuesHash!=null) - return theValuesHash.containsKey(field); - return false; - } - - /** - * Insers Entity into the database via StorageObject - * @return Primary Key of the Entity - * @exception StorageObjectException - */ - public String insert () throws StorageObjectExc { - theLog.printDebugInfo("Entity: trying to insert ..."); - if (theStorageObject != null) { - return theStorageObject.insert((Entity)this); - } - else - throw new StorageObjectExc("Kein StorageObject gesetzt!"); - } - - /** - * Saves changes of this Entity to the database - * @exception StorageObjectException - */ - public void update () throws StorageObjectFailure { - theStorageObject.update((Entity)this); - } - - /** - * Sets the value for a field. Issues a log message if the field name - * supplied was not found in the Entity. - * @param theProp The field name whose value has to be set - * @param theValue The new value of the field - * @exception StorageObjectException - */ - public void setValueForProperty (String theProp, String theValue) - throws StorageObjectFailure { - this.changed = true; - if (isField(theProp)) - theValuesHash.put(theProp, theValue); - else { - theLog.printWarning("Property not found: " + theProp+theValue); - } - - } - - /** - * Returns the field names of the Entity as ArrayListe. - * @return ArrayList with field names - * @exception StorageObjectException is throuwn if database access was impossible - */ - public ArrayList getFields () throws StorageObjectFailure { - return theStorageObject.getFields(); - } - - /** - * Returns an int[] with the types of the fields - * @return int[] that contains the types of the fields - * @exception StorageObjectException - */ - public int[] getTypes () throws StorageObjectFailure { - return theStorageObject.getTypes(); - } - - /** - * Returns an ArrayList with field names - * @return List with field names - * @exception StorageObjectException - */ - public ArrayList getLabels () throws StorageObjectFailure { - return theStorageObject.getLabels(); - } - - /** - * Returns a Hashmap with all values of the Entity. - * @return HashMap with field name as key and the corresponding values - * - * @deprecated This method is deprecated and will be deleted in the next release. - * Entity interfaces freemarker.template.TemplateHashModel now and can - * be used in the same way as SimpleHash. - - */ - public HashMap getValues() { - theLog.printWarning("## using deprecated Entity.getValues() - a waste of resources"); - return theValuesHash; - } - - /** - * Returns an ArrayList with all database fields that can - * be evaluated as streamedInput. - * Could be automated by the types (blob, etc.) - * Until now to be created manually in the inheriting class - * - * Liefert einen ArrayList mit allen Datenbankfeldern, die - * als streamedInput ausgelesen werden muessen. - * Waere automatisierbar ueber die types (blob, etc.) - * Bisher manuell anzulegen in der erbenden Klasse - */ - - public ArrayList streamedInput() { - return streamedInput; - } - - /** Returns whether fieldName is a valid field name of this Entity. - * @param fieldName - * @return true in case fieldName is a field name, else false. - * @exception StorageObjectException - */ - public boolean isField (String fieldName) throws StorageObjectFailure { - return theStorageObject.getFields().contains(fieldName); - } - - - - protected void throwStorageObjectFailure (Exception e, String wo) - throws StorageObjectFailure { - theLog.printError( e.toString() + " Funktion: "+ wo); - e.printStackTrace(System.out); - throw new StorageObjectFailure("Storage Object Exception in entity", e); - } - - // Now implements freemarkers TemplateHashModel - // two methods have to be overridden: - // 1. public boolean isEmpty() throws TemplateModelException - // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException - - public boolean isEmpty() throws TemplateModelException - { - return (theValuesHash==null || theValuesHash.isEmpty()) ? true : false; - } - - public TemplateModel get(java.lang.String key) throws TemplateModelException - { - return new SimpleScalar(getValue(key)); - } - - public void put(java.lang.String key, TemplateModel model) - { - // putting should only take place via setValue and is limited to the - // database fields associated with the entity. no additional freemarker - // stuff will be available via Entity. - theLog.printWarning("### put is called on entity! - the values will be lost!"); - } - - public void remove(java.lang.String key) - { - // do we need this? - } - - - ////////////////////////////////////////////////////////////////////////////////// - - -} - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +/** + * Base class the entities are derived from. Provides base functionality of + * an entity. Entities are used to represent rows of a database table.

+ */ + +package mir.entity; + +import java.util.List; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.misc.Logfile; +import mir.misc.StringUtil; +import mir.storage.StorageObject; +import mir.storage.StorageObjectExc; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleScalar; +import freemarker.template.TemplateHashModel; +import freemarker.template.TemplateModel; +import freemarker.template.TemplateModelException; +import freemarker.template.TemplateModelRoot; + +/** + * Base Class of Entities + * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant + * + * @version $Id: Entity.java,v 1.14 2003/02/20 16:05:32 zapata Exp $ + * @author rk + * + */ + +public class Entity implements TemplateHashModel, TemplateModelRoot +{ + protected static MirPropertiesConfiguration configuration; + protected static Logfile theLog; + + private boolean changed; + protected HashMap theValuesHash; // tablekey / value + protected StorageObject theStorageObject; + protected List streamedInput = null; + + static { + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + e.printStackTrace(); + } + theLog = Logfile.getInstance(configuration.getStringWithHome( + "Entity.Logfile")); + } + + public Entity() { + this.changed = false; + } + + /** + * Constructor + * @param StorageObject The StorageObject of the Entity. + */ + public Entity(StorageObject StorageObject) { + this(); + setStorage(StorageObject); + } + + /* + * Sets the StorageObject of the Entity. + */ + public void setStorage(StorageObject storage) { + this.theStorageObject = storage; + } + + /** + * Sets the values of the Entity. + * @param theStringValues HashMap containing the new values of the Entity + */ + + public void setValues(HashMap theStringValues) { + /** @todo should be synchronized */ + if (theStringValues != null) { + theValuesHash = new HashMap(); + String aKey; + Set set = theStringValues.keySet(); + Iterator it = set.iterator(); + int size = set.size(); + for (int i = 0; i < size; i++) { + aKey = (String) it.next(); + theValuesHash.put(aKey, (String) theStringValues.get(aKey)); + } + } + else + theLog.printWarning("Entity.setValues called with null HashMap"); + } + + /** + * Returns whether the content of the Entity has changed. + * @return true wenn ja, sonst false + */ + public boolean changed() { + return changed; + } + + /** + * Returns the primary key of the Entity. + * @return String Id + */ + public String getId() { + return (String) getValue(theStorageObject.getIdName()); + } + + /** + * Defines the primary key of the Entity + * @param id + */ + public void setId(String id) { + theValuesHash.put(theStorageObject.getIdName(), id); + } + + /** + * Returns the value of a field by field name. + * @param field The name of the field + * @return value of the field + */ + public String getValue(String field) { + String returnValue = null; + if (field != null) { + if (field.equals("webdb_create_formatted")) { + if (hasValueForField("webdb_create")) + returnValue = StringUtil.dateToReadableDate(getValue("webdb_create")); + } + else if (field.equals("webdb_lastchange_formatted")) { + if (hasValueForField("webdb_lastchange")) + returnValue = StringUtil.dateToReadableDate(getValue( + "webdb_lastchange")); + } + else + returnValue = (String) theValuesHash.get(field); + } + return returnValue; + } + + public boolean hasValueForField(String field) { + if (theValuesHash != null) + return theValuesHash.containsKey(field); + return false; + } + + /** + * Insers Entity into the database via StorageObject + * @return Primary Key of the Entity + * @exception StorageObjectException + */ + public String insert() throws StorageObjectExc { + theLog.printDebugInfo("Entity: trying to insert ..."); + if (theStorageObject != null) { + return theStorageObject.insert( (Entity)this); + } + else + throw new StorageObjectExc("Kein StorageObject gesetzt!"); + } + + /** + * Saves changes of this Entity to the database + * @exception StorageObjectException + */ + public void update() throws StorageObjectFailure { + theStorageObject.update( (Entity)this); + } + + /** + * Sets the value for a field. Issues a log message if the field name + * supplied was not found in the Entity. + * @param theProp The field name whose value has to be set + * @param theValue The new value of the field + * @exception StorageObjectException + */ + public void setValueForProperty(String theProp, String theValue) throws + StorageObjectFailure { + this.changed = true; + if (isField(theProp)) + theValuesHash.put(theProp, theValue); + else { + theLog.printWarning("Property not found: " + theProp + theValue); + } + + } + + /** + * Returns the field names of the Entity as ArrayListe. + * @return ArrayList with field names + * @exception StorageObjectException is throuwn if database access was impossible + */ + public List getFields() throws StorageObjectFailure { + return theStorageObject.getFields(); + } + + /** + * Returns an int[] with the types of the fields + * @return int[] that contains the types of the fields + * @exception StorageObjectException + */ + public int[] getTypes() throws StorageObjectFailure { + return theStorageObject.getTypes(); + } + + /** + * Returns an ArrayList with field names + * @return List with field names + * @exception StorageObjectException + */ + public List getLabels() throws StorageObjectFailure { + return theStorageObject.getLabels(); + } + + /** + * Returns a Hashmap with all values of the Entity. + * @return HashMap with field name as key and the corresponding values + * + * @deprecated This method is deprecated and will be deleted in the next release. + * Entity interfaces freemarker.template.TemplateHashModel now and can + * be used in the same way as SimpleHash. + */ + public HashMap getValues() { + theLog.printWarning( + "## using deprecated Entity.getValues() - a waste of resources"); + return theValuesHash; + } + + /** + * Returns an ArrayList with all database fields that can + * be evaluated as streamedInput. + * Could be automated by the types (blob, etc.) + * Until now to be created manually in the inheriting class + * + * Liefert einen ArrayList mit allen Datenbankfeldern, die + * als streamedInput ausgelesen werden muessen. + * Waere automatisierbar ueber die types (blob, etc.) + * Bisher manuell anzulegen in der erbenden Klasse + */ + + public List streamedInput() { + return streamedInput; + } + + /** Returns whether fieldName is a valid field name of this Entity. + * @param fieldName + * @return true in case fieldName is a field name, else false. + * @exception StorageObjectException + */ + public boolean isField(String fieldName) throws StorageObjectFailure { + return theStorageObject.getFields().contains(fieldName); + } + + protected void throwStorageObjectFailure(Exception e, String wo) throws + StorageObjectFailure { + theLog.printError(e.toString() + " Funktion: " + wo); + e.printStackTrace(System.out); + throw new StorageObjectFailure("Storage Object Exception in entity", e); + } + + // Now implements freemarkers TemplateHashModel + // two methods have to be overridden: + // 1. public boolean isEmpty() throws TemplateModelException + // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException + + public boolean isEmpty() throws TemplateModelException { + return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false; + } + + public TemplateModel get(java.lang.String key) throws TemplateModelException { + return new SimpleScalar(getValue(key)); + } + + public void put(java.lang.String key, TemplateModel model) { + // putting should only take place via setValue and is limited to the + // database fields associated with the entity. no additional freemarker + // stuff will be available via Entity. + theLog.printWarning( + "### put is called on entity! - the values will be lost!"); + } + + public void remove(java.lang.String key) { + // do we need this? + } + + ////////////////////////////////////////////////////////////////////////////////// +} + diff --git a/source/mir/entity/QueryBuilder.java b/source/mir/entity/QueryBuilder.java deleted file mode 100755 index 4a3ab1cc..00000000 --- a/source/mir/entity/QueryBuilder.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.entity; - -public class QueryBuilder { - - private String whereClause; - private String orderByClause; - - public QueryBuilder(){ - whereClause = new String(); - orderByClause = new String(); - } - - public void appendDescendingOrder(String anOrder) { - if (orderByClause.length()==0) { - orderByClause=anOrder+" desc"; - } - else { - orderByClause=orderByClause+","+anOrder+" desc"; - } - } - - public void appendAscendingOrder(String anOrder) { - if (orderByClause.length()==0) { - orderByClause=anOrder+" asc"; - } - else { - orderByClause=orderByClause+","+anOrder+" asc"; - } - } - - public void appendAndCondition(String aQualifier) { - if (whereClause.length()==0) { - whereClause = aQualifier; - } - else { - whereClause="("+whereClause+") and ("+aQualifier+")"; - } - } - - public void appendOrCondition(String aQualifier) { - if (whereClause.length()==0) { - whereClause = aQualifier; - } - else { - whereClause="("+whereClause+") or ("+aQualifier+")"; - } - } - - public String getWhereClause() { - return whereClause; - } - - public String getOrderByClause() { - return orderByClause; - } -} \ No newline at end of file diff --git a/source/mir/generator/FreemarkerGenerator.java b/source/mir/generator/FreemarkerGenerator.java index 640550d2..eef3d71f 100755 --- a/source/mir/generator/FreemarkerGenerator.java +++ b/source/mir/generator/FreemarkerGenerator.java @@ -1,339 +1,346 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.generator; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import mir.misc.MessageMethodModel; -import mir.util.RewindableIterator; - -import org.apache.struts.util.MessageResources; - -import freemarker.template.FileTemplateCache; -import freemarker.template.SimpleScalar; -import freemarker.template.Template; -import freemarker.template.TemplateHashModel; -import freemarker.template.TemplateListModel; -import freemarker.template.TemplateMethodModel; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateModelRoot; -import freemarker.template.TemplateScalarModel; - -public class FreemarkerGenerator implements Generator { - private Template template; - - public FreemarkerGenerator(Template aTemplate) { - template = aTemplate; - } - - public void generate(Object anOutputWriter, Map aValues, PrintWriter aLogger) throws GeneratorExc, GeneratorFailure { - if (!(anOutputWriter instanceof PrintWriter)) - throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter"); - - try { - template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter); - } - catch (Throwable t) { - t.printStackTrace(); - aLogger.println("Exception occurred: "+t.getMessage()); - t.printStackTrace(aLogger); - throw new GeneratorFailure( t ); - } - } - - private static TemplateScalarModel makeStringAdapter(String aString) { - return new SimpleScalar(aString); - } - - private static TemplateHashModel makeMapAdapter(Map aMap) { - return new MapAdapter(aMap); - } - - private static TemplateListModel makeIteratorAdapter(Iterator anIterator) { - return new IteratorAdapter(anIterator); - } - - private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) { - return new FunctionAdapter(aFunction); - } - - public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException { - if (anObject == null) - return null; - if (anObject instanceof TemplateModel) - return (TemplateModel) anObject; - else if (anObject instanceof Generator.GeneratorFunction) - return makeFunctionAdapter((Generator.GeneratorFunction) anObject); - else if (anObject instanceof MessageResources) - return new MessageMethodModel((MessageResources) anObject); - else if (anObject instanceof Integer) - return makeStringAdapter(((Integer) anObject).toString()); - else if (anObject instanceof String) - return makeStringAdapter((String) anObject); - else if (anObject instanceof Map) - return makeMapAdapter((Map) anObject); - else if (anObject instanceof Iterator) - return makeIteratorAdapter((Iterator) anObject); - else if (anObject instanceof List) - return makeIteratorAdapter(((List) anObject).iterator()); - else - throw new TemplateModelException("Unadaptable class: " + anObject.getClass().getName()); - } - - private static class MapAdapter implements TemplateModelRoot { - Map map; - Map valuesCache; - - private MapAdapter(Map aMap) { - map = aMap; - valuesCache = new HashMap(); - } - - public void put(String aKey, TemplateModel aModel) { - valuesCache.put(aKey, aModel); - } - - public void remove(String aKey) { - // ML: kinda tricky... - } - - public boolean isEmpty() { - return map.isEmpty(); - } - - public TemplateModel get(String aKey) throws TemplateModelException { - try { - if (!valuesCache.containsKey(aKey)) { - Object value = map.get(aKey); - - if (value == null && !map.containsKey(aKey)) { - throw new TemplateModelException("MapAdapter: no key "+aKey+" available"); - } - - valuesCache.put(aKey, makeAdapter(value)); - } - - return (TemplateModel) valuesCache.get(aKey); - } - catch (TemplateModelException e) { - throw e; - } - catch (Throwable t) { - throw new TemplateModelException(t.getMessage()); - } - } - } - - private static class IteratorAdapter implements TemplateListModel { - Iterator iterator; - List valuesCache; - int position; - - private IteratorAdapter(Iterator anIterator) { - iterator = anIterator; - - valuesCache = new Vector(); - position=0; - - - if (iterator instanceof RewindableIterator) { - ((RewindableIterator) iterator).rewind(); - } - } - - public boolean isEmpty() { - return valuesCache.isEmpty() && !iterator.hasNext(); - } - - private void getUntil(int anIndex) throws TemplateModelException { - while (valuesCache.size()<=anIndex && iterator.hasNext()) - { - valuesCache.add(makeAdapter(iterator.next())); - } - }; - - public TemplateModel get(int anIndex) throws TemplateModelException { - TemplateModel result; - - getUntil(anIndex); - - if (anIndex=valuesCache.size() && i=valuesCache.size() && i - * - * - * @version 28.6.199 - * @author RK - */ - -public final class ServletModuleException extends Exception -{ - public ServletModuleException(String msg) { - super(msg); - } -} - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.servlet; + + +/* + * ServletModuleException - + * wird vom ServletModule geschmissen + * + * + * @version 28.6.199 + * @author RK + */ + +public final class ServletModuleException extends Exception +{ + public ServletModuleException(String msg) { + super(msg); + } +} + diff --git a/source/mir/storage/Database.java b/source/mir/storage/Database.java index e19deef1..6b9cd35a 100755 --- a/source/mir/storage/Database.java +++ b/source/mir/storage/Database.java @@ -1,1473 +1,1459 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ -package mir.storage; - -import com.codestudio.util.SQLManager; - -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - -import mir.config.MirPropertiesConfiguration; - -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; - -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.entity.StorableObjectEntity; - -import mir.misc.HTMLTemplateProcessor; -import mir.misc.Logfile; -import mir.misc.StringUtil; - -import mir.storage.store.ObjectStore; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; - -import mir.util.JDBCStringRoutines; - -import java.io.IOException; -import java.io.InputStreamReader; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; - -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; - - -/** - * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank. - * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse. - * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben. - * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten - * Treiber, Host, User und Passwort, ueber den der Zugriff auf die - * Datenbank erfolgt. - * - * @version $Id: Database.java,v 1.32 2003/01/28 21:47:42 idfx Exp $ - * @author rk - * - */ -public class Database implements StorageObject { - private static Class GENERIC_ENTITY_CLASS = null; - private static Class STORABLE_OBJECT_ENTITY_CLASS = null; - private static SimpleHash POPUP_EMTYLINE = new SimpleHash(); - protected static final ObjectStore o_store = ObjectStore.getInstance(); - private static final int _millisPerHour = 60 * 60 * 1000; - private static final int _millisPerMinute = 60 * 1000; - - static { - // always same object saves a little space - POPUP_EMTYLINE.put("key", ""); - POPUP_EMTYLINE.put("value", "--"); - - try { - GENERIC_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity"); - STORABLE_OBJECT_ENTITY_CLASS = - Class.forName("mir.entity.StorableObjectEntity"); - } catch (Exception e) { - System.err.println("FATAL: Database.java could not initialize" + - e.getMessage()); - } - } - - protected MirPropertiesConfiguration configuration; - protected String theTable; - protected String theCoreTable = null; - protected String thePKeyName = "id"; - protected int thePKeyType; - protected int thePKeyIndex; - protected boolean evaluatedMetaData = false; - protected ArrayList metadataFields; - protected ArrayList metadataLabels; - protected ArrayList metadataNotNullFields; - protected int[] metadataTypes; - protected Class theEntityClass; - protected StorageObject myselfDatabase; - protected SimpleList popupCache = null; - protected boolean hasPopupCache = false; - protected SimpleHash hashCache = null; - protected boolean hasTimestamp = true; - private String database_driver; - private String database_url; - private int defaultLimit; - protected DatabaseAdaptor theAdaptor; - protected Logfile theLog; - private SimpleDateFormat _dateFormatterOut = - new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - private SimpleDateFormat _dateFormatterIn = - new SimpleDateFormat("yyyy-MM-dd HH:mm"); - private Calendar _cal = new GregorianCalendar(); - - /** - * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. - * Aus diesem file werden Database.Logfile, - * Database.Username,Database.Password, - * Database.Host und Database.Adaptor - * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank - * erzeugt. - * - * @param String confFilename Dateiname der Konfigurationsdatei - */ - public Database() throws StorageObjectFailure { - try { - configuration = MirPropertiesConfiguration.instance(); - } catch (PropertiesConfigExc e) { - throw new StorageObjectFailure(e); - } - - theLog = - Logfile.getInstance(configuration.getStringWithHome("Database.Logfile")); - - String theAdaptorName = configuration.getString("Database.Adaptor"); - defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); - - try { - theEntityClass = GENERIC_ENTITY_CLASS; - theAdaptor = - (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance(); - } catch (Exception e) { - theLog.printError("Error in Database() constructor with " + - theAdaptorName + " -- " + e.getMessage()); - throw new StorageObjectFailure("Error in Database() constructor.", e); - } - } - - /** - * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt - * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben, - * wird eine mir.entity.GenericEntity erzeugt. - * - * @return Class-Objekt der Entity - */ - public java.lang.Class getEntityClass() { - return theEntityClass; - } - - /** - * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also - * wieviel Datens?tze per Default selektiert werden. - * - * @return Standard-Anzahl der Datens?tze - */ - public int getLimit() { - return defaultLimit; - } - - /** - * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von - * der erbenden Klasse ?berschrieben, so ist der Wert PKEY - * @return Name des Primary-Keys - */ - public String getIdName() { - return thePKeyName; - } - - /** - * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. - * - * @return Name der Tabelle - */ - public String getTableName() { - return theTable; - } - - /* - * Dient dazu vererbte Tabellen bei objectrelationalen DBMS - * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet - * wird. - * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst - * the Table - */ - public String getCoreTable() { - if (theCoreTable != null) { - return theCoreTable; - } else { - return theTable; - } - } - - /** - * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types) - * @return int-Array mit den Typen der Felder - * @exception StorageObjectException - */ - public int[] getTypes() throws StorageObjectFailure { - if (metadataTypes == null) { - get_meta_data(); - } - - return metadataTypes; - } - - /** - * Liefert eine Liste der Labels der Tabellenfelder - * @return ArrayListe mit Labeln - * @exception StorageObjectException - */ - public ArrayList getLabels() throws StorageObjectFailure { - if (metadataLabels == null) { - get_meta_data(); - } - - return metadataLabels; - } - - /** - * Liefert eine Liste der Felder der Tabelle - * @return ArrayList mit Feldern - * @exception StorageObjectException - */ - public ArrayList getFields() throws StorageObjectFailure { - if (metadataFields == null) { - get_meta_data(); - } - - return metadataFields; - } - - /* - * Gets value out of ResultSet according to type and converts to String - * @param inValue Wert aus ResultSet. - * @param aType Datenbanktyp. - * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich - * dann /unsupported value/ - */ - private String getValueAsString(ResultSet rs, int valueIndex, int aType) - throws StorageObjectFailure { - String outValue = null; - - if (rs != null) { - try { - switch (aType) { - case java.sql.Types.BIT: - outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; - - break; - - case java.sql.Types.INTEGER: - case java.sql.Types.SMALLINT: - case java.sql.Types.TINYINT: - case java.sql.Types.BIGINT: - - int out = rs.getInt(valueIndex); - - if (!rs.wasNull()) { - outValue = new Integer(out).toString(); - } - - break; - - case java.sql.Types.NUMERIC: - - /** @todo Numeric can be float or double depending upon - * metadata.getScale() / especially with oracle */ - long outl = rs.getLong(valueIndex); - - if (!rs.wasNull()) { - outValue = new Long(outl).toString(); - } - - break; - - case java.sql.Types.REAL: - - float tempf = rs.getFloat(valueIndex); - - if (!rs.wasNull()) { - tempf *= 10; - tempf += 0.5; - - int tempf_int = (int) tempf; - tempf = (float) tempf_int; - tempf /= 10; - outValue = "" + tempf; - outValue = outValue.replace('.', ','); - } - - break; - - case java.sql.Types.DOUBLE: - - double tempd = rs.getDouble(valueIndex); - - if (!rs.wasNull()) { - tempd *= 10; - tempd += 0.5; - - int tempd_int = (int) tempd; - tempd = (double) tempd_int; - tempd /= 10; - outValue = "" + tempd; - outValue = outValue.replace('.', ','); - } - - break; - - case java.sql.Types.CHAR: - case java.sql.Types.VARCHAR: - case java.sql.Types.LONGVARCHAR: - outValue = rs.getString(valueIndex); - - break; - - case java.sql.Types.LONGVARBINARY: - outValue = rs.getString(valueIndex); - - break; - - case java.sql.Types.TIMESTAMP: - - // it's important to use Timestamp here as getting it - // as a string is undefined and is only there for debugging - // according to the API. we can make it a string through formatting. - // -mh - Timestamp timestamp = (rs.getTimestamp(valueIndex)); - - if (!rs.wasNull()) { - java.util.Date date = new java.util.Date(timestamp.getTime()); - outValue = _dateFormatterOut.format(date); - _cal.setTime(date); - - int offset = - _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET); - String tzOffset = - StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2); - outValue = outValue + "+" + tzOffset; - } - - break; - - default: - outValue = ""; - theLog.printWarning("Unsupported Datatype: at " + valueIndex + " (" + - aType + ")"); - } - } catch (SQLException e) { - throw new StorageObjectFailure("Could not get Value out of Resultset -- ", - e); - } - } - - return outValue; - } - - /* - * select-Operator um einen Datensatz zu bekommen. - * @param id Primaerschluessel des Datensatzes. - * @return liefert EntityObject des gefundenen Datensatzes oder null. - */ - public Entity selectById(String id) throws StorageObjectExc { - if ((id == null) || id.equals("")) { - throw new StorageObjectExc("id war null"); - } - - // ask object store for object - if (StoreUtil.implementsStorableObject(theEntityClass)) { - String uniqueId = id; - - if (theEntityClass.equals(StorableObjectEntity.class)) { - uniqueId += ("@" + theTable); - } - - StoreIdentifier search_sid = - new StoreIdentifier(theEntityClass, uniqueId); - theLog.printDebugInfo("CACHE: (dbg) looking for sid " + - search_sid.toString()); - - Entity hit = (Entity) o_store.use(search_sid); - - if (hit != null) { - return hit; - } - } - - Statement stmt = null; - Connection con = getPooledCon(); - Entity returnEntity = null; - - try { - ResultSet rs; - - /** @todo better prepared statement */ - String selectSql = - "select * from " + theTable + " where " + thePKeyName + "=" + id; - stmt = con.createStatement(); - rs = executeSql(stmt, selectSql); - - if (rs != null) { - if (evaluatedMetaData == false) { - evalMetaData(rs.getMetaData()); - } - - if (rs.next()) { - returnEntity = makeEntityFromResultSet(rs); - } else { - theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + - theTable); - } - - rs.close(); - } else { - theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable); - } - } catch (SQLException sqe) { - throwSQLException(sqe, "selectById"); - - return null; - } catch (NumberFormatException e) { - theLog.printError("ID ist keine Zahl: " + id); - } finally { - freeConnection(con, stmt); - } - - /** @todo OS: Entity should be saved in ostore */ - return returnEntity; - } - - /** - * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. - * @param key Datenbankfeld der Bedingung. - * @param value Wert die der key anehmen muss. - * @return EntityList mit den gematchten Entities - */ - public EntityList selectByFieldValue(String aField, String aValue) - throws StorageObjectFailure { - return selectByFieldValue(aField, aValue, 0); - } - - /** - * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. - * @param key Datenbankfeld der Bedingung. - * @param value Wert die der key anehmen muss. - * @param offset Gibt an ab welchem Datensatz angezeigt werden soll. - * @return EntityList mit den gematchten Entities - */ - public EntityList selectByFieldValue(String aField, String aValue, int offset) - throws StorageObjectFailure { - return selectByWhereClause(aField + "=" + aValue, offset); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * - * @param wc where-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String where) - throws StorageObjectFailure { - return selectByWhereClause(where, 0); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param offset ab welchem Datensatz. - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String whereClause, int offset) - throws StorageObjectFailure { - return selectByWhereClause(whereClause, null, offset); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param ob orderBy-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String where, String order) - throws StorageObjectFailure { - return selectByWhereClause(where, order, 0); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param ob orderBy-Clause - * @param offset ab welchem Datensatz - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String whereClause, String orderBy, - int offset) throws StorageObjectFailure { - return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * @param wc where-Clause - * @param ob orderBy-Clause - * @param offset ab welchem Datensatz - * @param limit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String wc, String ob, int offset, - int limit) throws StorageObjectFailure { - // check o_store for entitylist - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreIdentifier search_sid = - new StoreIdentifier(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST, - StoreUtil.getEntityListUniqueIdentifierFor(theTable, wc, ob, offset, - limit)); - EntityList hit = (EntityList) o_store.use(search_sid); - - if (hit != null) { - theLog.printDebugInfo("CACHE (hit): " + search_sid.toString()); - - return hit; - } - } - - // local - EntityList theReturnList = null; - Connection con = null; - Statement stmt = null; - ResultSet rs; - int offsetCount = 0; - int count = 0; - - // build sql-statement - - /** @todo count sql string should only be assembled if we really count - * see below at the end of method //rk */ - if ((wc != null) && (wc.length() == 0)) { - wc = null; - } - - StringBuffer countSql = - new StringBuffer("select count(*) from ").append(theTable); - StringBuffer selectSql = - new StringBuffer("select * from ").append(theTable); - - if (wc != null) { - selectSql.append(" where ").append(wc); - countSql.append(" where ").append(wc); - } - - if ((ob != null) && !(ob.length() == 0)) { - selectSql.append(" order by ").append(ob); - } - - if (theAdaptor.hasLimit()) { - if ((limit > -1) && (offset > -1)) { - selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset); - } - } - - // execute sql - try { - con = getPooledCon(); - stmt = con.createStatement(); - - // selecting... - rs = executeSql(stmt, selectSql.toString()); - - if (rs != null) { - if (!evaluatedMetaData) { - evalMetaData(rs.getMetaData()); - } - - theReturnList = new EntityList(); - - Entity theResultEntity; - - while (rs.next()) { - theResultEntity = makeEntityFromResultSet(rs); - theReturnList.add(theResultEntity); - offsetCount++; - } - - rs.close(); - } - - // making entitylist infos - if (!(theAdaptor.hasLimit())) { - count = offsetCount; - } - - if (theReturnList != null) { - // now we decide if we have to know an overall count... - count = offsetCount; - - if ((limit > -1) && (offset > -1)) { - if (offsetCount == limit) { - /** @todo counting should be deffered to entitylist - * getSize() should be used */ - rs = executeSql(stmt, countSql.toString()); - - if (rs != null) { - if (rs.next()) { - count = rs.getInt(1); - } - - rs.close(); - } else { - theLog.printError("Could not count: " + countSql); - } - } - } - - theReturnList.setCount(count); - theReturnList.setOffset(offset); - theReturnList.setWhere(wc); - theReturnList.setOrder(ob); - theReturnList.setStorage(this); - theReturnList.setLimit(limit); - - if (offset >= limit) { - theReturnList.setPrevBatch(offset - limit); - } - - if ((offset + offsetCount) < count) { - theReturnList.setNextBatch(offset + limit); - } - - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreIdentifier sid = theReturnList.getStoreIdentifier(); - theLog.printDebugInfo("CACHE (add): " + sid.toString()); - o_store.add(sid); - } - } - } catch (SQLException sqe) { - throwSQLException(sqe, "selectByWhereClause"); - } finally { - try { - if (con != null) { - freeConnection(con, stmt); - } - } catch (Throwable t) { - } - } - - return theReturnList; - } - - /** - * Bastelt aus einer Zeile der Datenbank ein EntityObjekt. - * - * @param rs Das ResultSetObjekt. - * @return Entity Die Entity. - */ - private Entity makeEntityFromResultSet(ResultSet rs) - throws StorageObjectFailure { - /** @todo OS: get Pkey from ResultSet and consult ObjectStore */ - HashMap theResultHash = new HashMap(); - String theResult = null; - int theType; - Entity returnEntity = null; - - try { - int size = metadataFields.size(); - - for (int i = 0; i < size; i++) { - // alle durchlaufen bis nix mehr da - theType = metadataTypes[i]; - - if (theType == java.sql.Types.LONGVARBINARY) { - InputStreamReader is = - (InputStreamReader) rs.getCharacterStream(i + 1); - - if (is != null) { - char[] data = new char[32768]; - StringBuffer theResultString = new StringBuffer(); - int len; - - while ((len = is.read(data)) > 0) { - theResultString.append(data, 0, len); - } - - is.close(); - theResult = theResultString.toString(); - } else { - theResult = null; - } - } else { - theResult = getValueAsString(rs, (i + 1), theType); - } - - if (theResult != null) { - theResultHash.put(metadataFields.get(i), theResult); - } - } - - if (theEntityClass != null) { - returnEntity = (Entity) theEntityClass.newInstance(); - returnEntity.setValues(theResultHash); - returnEntity.setStorage(myselfDatabase); - - if (returnEntity instanceof StorableObject) { - theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :" + - theTable); - o_store.add(((StorableObject) returnEntity).getStoreIdentifier()); - } - } else { - throwStorageObjectException("Internal Error: theEntityClass not set!"); - } - } catch (IllegalAccessException e) { - throwStorageObjectException("No access! -- " + e.getMessage()); - } catch (IOException e) { - throwStorageObjectException("IOException! -- " + e.getMessage()); - } catch (InstantiationException e) { - throwStorageObjectException("No Instatiation! -- " + e.getMessage()); - } catch (SQLException sqe) { - throwSQLException(sqe, "makeEntityFromResultSet"); - - return null; - } - - return returnEntity; - } - - /** - * insert-Operator: f?gt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE - * wird automatisch mit dem aktuellen Datum gefuellt. - * - * @param theEntity - * @return der Wert des Primary-keys der eingef?gten Entity - */ - public String insert(Entity theEntity) throws StorageObjectFailure { - //cache - invalidatePopupCache(); - - // invalidating all EntityLists corresponding with theEntityClass - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = - StoreContainerType.valueOf(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - String returnId = null; - Connection con = null; - PreparedStatement pstmt = null; - - try { - ArrayList streamedInput = theEntity.streamedInput(); - StringBuffer f = new StringBuffer(); - StringBuffer v = new StringBuffer(); - String aField; - String aValue; - boolean firstField = true; - - // make sql-string - for (int i = 0; i < getFields().size(); i++) { - aField = (String) getFields().get(i); - - if (!aField.equals(thePKeyName)) { - aValue = null; - - // sonderfaelle - if (aField.equals("webdb_create") || - aField.equals("webdb_lastchange")) { - aValue = "NOW()"; - } else { - if ((streamedInput != null) && streamedInput.contains(aField)) { - aValue = "?"; - } else { - if (theEntity.hasValueForField(aField)) { - aValue = - "'" + - JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue( - aField)) + "'"; - } - } - } - - // wenn Wert gegeben, dann einbauen - if (aValue != null) { - if (firstField == false) { - f.append(","); - v.append(","); - } else { - firstField = false; - } - - f.append(aField); - v.append(aValue); - } - } - } - // end for - - // insert into db - StringBuffer sqlBuf = - new StringBuffer("insert into ").append(theTable).append("(").append(f) - .append(") values (").append(v).append(")"); - String sql = sqlBuf.toString(); - - //theLog.printInfo("INSERT: " + sql); - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql); - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = - (String) theEntity.getValue((String) streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - - int ret = pstmt.executeUpdate(); - - if (ret == 0) { - //insert failed - return null; - } - - pstmt = - con.prepareStatement(theAdaptor.getLastInsertSQL( - (Database) myselfDatabase)); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - returnId = rs.getString(1); - theEntity.setId(returnId); - } catch (SQLException sqe) { - throwSQLException(sqe, "insert"); - } finally { - try { - con.setAutoCommit(true); - } catch (Exception e) { - ; - } - - freeConnection(con, pstmt); - } - - /** @todo store entity in o_store */ - return returnId; - } - - /** - * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE - * wird automatisch mit dem aktuellen Datum gefuellt. - * - * @param theEntity - */ - public void update(Entity theEntity) throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - - /** @todo this is stupid: why do we prepare statement, when we - * throw it away afterwards. should be regular statement - * update/insert could better be one routine called save() - * that chooses to either insert or update depending if we - * have a primary key in the entity. i don't know if we - * still need the streamed input fields. // rk */ - /** @todo extension: check if Entity did change, otherwise we don't need - * the roundtrip to the database */ - /** invalidating corresponding entitylists in o_store*/ - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = - StoreContainerType.valueOf(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - ArrayList streamedInput = theEntity.streamedInput(); - String id = theEntity.getId(); - String aField; - StringBuffer fv = new StringBuffer(); - boolean firstField = true; - - //cache - invalidatePopupCache(); - - // build sql statement - for (int i = 0; i < getFields().size(); i++) { - aField = (String) metadataFields.get(i); - - // only normal cases - if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") || - aField.equals("webdb_lastchange") || - ((streamedInput != null) && streamedInput.contains(aField)))) { - if (theEntity.hasValueForField(aField)) { - if (firstField == false) { - fv.append(", "); - } else { - firstField = false; - } - - fv.append(aField).append("='") - .append(JDBCStringRoutines.escapeStringLiteral( - (String) theEntity.getValue(aField))).append("'"); - - // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'"); - } - } - } - - StringBuffer sql = - new StringBuffer("update ").append(theTable).append(" set ").append(fv); - - // exceptions - if (metadataFields.contains("webdb_lastchange")) { - sql.append(",webdb_lastchange=NOW()"); - } - - // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm - // format so anything extra will be ignored. -mh - if (metadataFields.contains("webdb_create") && - theEntity.hasValueForField("webdb_create")) { - // minimum of 10 (yyyy-mm-dd)... - if (theEntity.getValue("webdb_create").length() >= 10) { - String dateString = theEntity.getValue("webdb_create"); - - // if only 10, then add 00:00 so it doesn't throw a ParseException - if (dateString.length() == 10) { - dateString = dateString + " 00:00"; - } - - // TimeStamp stuff - try { - java.util.Date d = _dateFormatterIn.parse(dateString); - Timestamp tStamp = new Timestamp(d.getTime()); - sql.append(",webdb_create='" + tStamp.toString() + "'"); - } catch (ParseException e) { - throw new StorageObjectFailure(e); - } - } - } - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - sql.append(",").append(streamedInput.get(i)).append("=?"); - } - } - - sql.append(" where id=").append(id); - - //theLog.printInfo("UPDATE: " + sql); - // execute sql - try { - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql.toString()); - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = - theEntity.getValue((String) streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - - pstmt.executeUpdate(); - } catch (SQLException sqe) { - throwSQLException(sqe, "update"); - } finally { - try { - con.setAutoCommit(true); - } catch (Exception e) { - ; - } - - freeConnection(con, pstmt); - } - } - - /* - * delete-Operator - * @param id des zu loeschenden Datensatzes - * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. - */ - public boolean delete(String id) throws StorageObjectFailure { - invalidatePopupCache(); - - // ostore send notification - if (StoreUtil.implementsStorableObject(theEntityClass)) { - String uniqueId = id; - - if (theEntityClass.equals(StorableObjectEntity.class)) { - uniqueId += ("@" + theTable); - } - - theLog.printInfo("CACHE: (del) " + id); - - StoreIdentifier search_sid = - new StoreIdentifier(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITY, uniqueId); - o_store.invalidate(search_sid); - } - - /** @todo could be prepared Statement */ - Statement stmt = null; - Connection con = null; - int res = 0; - String sql = - "delete from " + theTable + " where " + thePKeyName + "='" + id + "'"; - - //theLog.printInfo("DELETE " + sql); - try { - con = getPooledCon(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); - } catch (SQLException sqe) { - throwSQLException(sqe, "delete"); - } finally { - freeConnection(con, stmt); - } - - return (res > 0) ? true : false; - } - - /* noch nicht implementiert. - * @return immer false - */ - public boolean delete(EntityList theEntityList) { - invalidatePopupCache(); - - return false; - } - - /** - * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse - * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll. - * @return null - */ - public SimpleList getPopupData() throws StorageObjectFailure { - return null; - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue) - throws StorageObjectFailure { - return getPopupData(name, hasNullValue, null); - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @param where Schraenkt die Selektion der Datensaetze ein. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue, String where) - throws StorageObjectFailure { - return getPopupData(name, hasNullValue, where, null); - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @param where Schraenkt die Selektion der Datensaetze ein. - * @param order Gibt ein Feld als Sortierkriterium an. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue, - String where, String order) throws StorageObjectFailure { - // caching - if (hasPopupCache && (popupCache != null)) { - return popupCache; - } - - SimpleList simpleList = null; - Connection con = null; - Statement stmt = null; - - // build sql - StringBuffer sql = - new StringBuffer("select ").append(thePKeyName).append(",").append(name) - .append(" from ").append(theTable); - - if ((where != null) && !(where.length() == 0)) { - sql.append(" where ").append(where); - } - - sql.append(" order by "); - - if ((order != null) && !(order.length() == 0)) { - sql.append(order); - } else { - sql.append(name); - } - - // execute sql - try { - con = getPooledCon(); - } catch (Exception e) { - throw new StorageObjectFailure(e); - } - - try { - stmt = con.createStatement(); - - ResultSet rs = executeSql(stmt, sql.toString()); - - if (rs != null) { - if (!evaluatedMetaData) { - get_meta_data(); - } - - simpleList = new SimpleList(); - - // if popup has null-selector - if (hasNullValue) { - simpleList.add(POPUP_EMTYLINE); - } - - SimpleHash popupDict; - - while (rs.next()) { - popupDict = new SimpleHash(); - popupDict.put("key", getValueAsString(rs, 1, thePKeyType)); - popupDict.put("value", rs.getString(2)); - simpleList.add(popupDict); - } - - rs.close(); - } - } catch (Exception e) { - theLog.printError("getPopupData: " + e.getMessage()); - throw new StorageObjectFailure(e); - } finally { - freeConnection(con, stmt); - } - - if (hasPopupCache) { - popupCache = simpleList; - } - - return simpleList; - } - - /** - * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt, - * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen - * Tabellen Verwendung finden. - * @return SimpleHash mit den Tabellezeilen. - */ - public SimpleHash getHashData() { - /** @todo dangerous! this should have a flag to be enabled, otherwise - * very big Hashes could be returned */ - if (hashCache == null) { - try { - hashCache = - HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1)); - } catch (StorageObjectFailure e) { - theLog.printDebugInfo(e.getMessage()); - } - } - - return hashCache; - } - - /* invalidates the popupCache - */ - protected void invalidatePopupCache() { - /** @todo invalidates toooo much */ - popupCache = null; - hashCache = null; - } - - /** - * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. - * @param stmt Statemnt - * @param sql Sql-String - * @return ResultSet - * @exception StorageObjectException - */ - public ResultSet executeSql(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { - long startTime = System.currentTimeMillis(); - ResultSet rs; - - try { - rs = stmt.executeQuery(sql); - - //theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - } catch (SQLException e) { - theLog.printDebugInfo("Failed: " + - (System.currentTimeMillis() - startTime) + "ms. for: " + sql); - throw e; - } - - return rs; - } - - /** - * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird - * getimed und geloggt. - * @param stmt PreparedStatement mit der SQL-Anweisung - * @return Liefert ResultSet des Statements zurueck. - * @exception StorageObjectException, SQLException - */ - public ResultSet executeSql(PreparedStatement stmt) - throws StorageObjectFailure, SQLException { - long startTime = (new java.util.Date()).getTime(); - ResultSet rs = stmt.executeQuery(); - theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms."); - - return rs; - } - - /** - * returns the number of rows in the table - */ - public int getSize(String where) throws SQLException, StorageObjectFailure { - long startTime = System.currentTimeMillis(); - String sql = "SELECT Count(*) FROM " + theTable; - - if ((where != null) && !(where.length() == 0)) { - sql = sql + " where " + where; - } - - Connection con = null; - Statement stmt = null; - int result = 0; - - try { - con = getPooledCon(); - stmt = con.createStatement(); - - ResultSet rs = executeSql(stmt, sql); - - while (rs.next()) { - result = rs.getInt(1); - } - } catch (SQLException e) { - theLog.printError(e.getMessage()); - } finally { - freeConnection(con, stmt); - } - - //theLog.printInfo(theTable + " has "+ result +" rows where " + where); - //theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - return result; - } - - public int executeUpdate(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { - int rs; - long startTime = (new java.util.Date()).getTime(); - - try { - rs = stmt.executeUpdate(sql); - - //theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql); - } catch (SQLException e) { - theLog.printDebugInfo("Failed: " + - (new java.util.Date().getTime() - startTime) + "ms. for: " + sql); - throw e; - } - - return rs; - } - - public int executeUpdate(String sql) - throws StorageObjectFailure, SQLException { - int result = -1; - long startTime = (new java.util.Date()).getTime(); - Connection con = null; - PreparedStatement pstmt = null; - - try { - con = getPooledCon(); - pstmt = con.prepareStatement(sql); - result = pstmt.executeUpdate(); - } catch (Exception e) { - theLog.printDebugInfo("executeUpdate failed: " + e.getMessage()); - throw new StorageObjectFailure("executeUpdate failed", e); - } finally { - freeConnection(con, pstmt); - } - - //theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql); - return result; - } - - /** - * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend - * @param md ResultSetMetaData - * @exception StorageObjectException - */ - private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure { - this.evaluatedMetaData = true; - this.metadataFields = new ArrayList(); - this.metadataLabels = new ArrayList(); - this.metadataNotNullFields = new ArrayList(); - - try { - int numFields = md.getColumnCount(); - this.metadataTypes = new int[numFields]; - - String aField; - int aType; - - for (int i = 1; i <= numFields; i++) { - aField = md.getColumnName(i); - metadataFields.add(aField); - metadataLabels.add(md.getColumnLabel(i)); - aType = md.getColumnType(i); - metadataTypes[i - 1] = aType; - - if (aField.equals(thePKeyName)) { - thePKeyType = aType; - thePKeyIndex = i; - } - - if (md.isNullable(i) == ResultSetMetaData.columnNullable) { - metadataNotNullFields.add(aField); - } - } - } catch (SQLException e) { - throwSQLException(e, "evalMetaData"); - } - } - - /** - * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus, - * um die alle Columns und Typen einer Tabelle zu ermitteln. - */ - private void get_meta_data() throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - String sql = "select * from " + theTable + " where 0=1"; - - try { - con = getPooledCon(); - pstmt = con.prepareStatement(sql); - - //theLog.printInfo("METADATA: " + sql); - ResultSet rs = pstmt.executeQuery(); - evalMetaData(rs.getMetaData()); - rs.close(); - } catch (SQLException e) { - throwSQLException(e, "get_meta_data"); - } finally { - freeConnection(con, pstmt); - } - } - - public Connection getPooledCon() throws StorageObjectFailure { - /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh - try{ - Class.forName("com.codestudio.sql.PoolMan").newInstance(); - } catch (Exception e){ - throw new StorageObjectException("Could not find the PoolMan Driver" - +e.toString()); - }*/ - Connection con = null; - - try { - con = SQLManager.getInstance().requestConnection(); - } catch (SQLException e) { - theLog.printError("could not connect to the database " + e.getMessage()); - System.err.println("could not connect to the database " + e.getMessage()); - throw new StorageObjectFailure("Could not connect to the database", e); - } - - return con; - } - - public void freeConnection(Connection con, Statement stmt) - throws StorageObjectFailure { - SQLManager.closeStatement(stmt); - SQLManager.getInstance().returnConnection(con); - } - - /** - * Wertet SQLException aus und wirft dannach eine StorageObjectException - * @param sqe SQLException - * @param wo Funktonsname, in der die SQLException geworfen wurde - * @exception StorageObjectException - */ - protected void throwSQLException(SQLException sqe, String wo) - throws StorageObjectFailure { - String state = ""; - String message = ""; - int vendor = 0; - - if (sqe != null) { - state = sqe.getSQLState(); - message = sqe.getMessage(); - vendor = sqe.getErrorCode(); - } - - theLog.printError(state + ": " + vendor + " : " + message + " Funktion: " + - wo); - throw new StorageObjectFailure((sqe == null) ? "undefined sql exception" - : sqe.getMessage(), sqe); - } - - protected void _throwStorageObjectException(Exception e, String wo) - throws StorageObjectFailure { - if (e != null) { - theLog.printError(e.getMessage() + wo); - throw new StorageObjectFailure(wo, e); - } else { - theLog.printError(wo); - throw new StorageObjectFailure(wo, null); - } - } - - /** - * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach - * eine StorageObjectException - * @param message Nachricht mit dem Fehler - * @exception StorageObjectException - */ - void throwStorageObjectException(String message) throws StorageObjectFailure { - _throwStorageObjectException(null, message); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ +package mir.storage; + +import java.io.IOException; +import java.io.InputStreamReader; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import java.util.ArrayList; +import java.util.List; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; + +import com.codestudio.util.SQLManager; + +import freemarker.template.SimpleHash; +import freemarker.template.SimpleList; + +import mir.config.MirPropertiesConfiguration; + +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; + +import mir.entity.Entity; +import mir.entity.EntityList; +import mir.entity.StorableObjectEntity; + +import mir.log.LoggerWrapper; + +import mir.misc.HTMLTemplateProcessor; +import mir.misc.StringUtil; + +import mir.storage.store.ObjectStore; +import mir.storage.store.StorableObject; +import mir.storage.store.StoreContainerType; +import mir.storage.store.StoreIdentifier; +import mir.storage.store.StoreUtil; + +import mir.util.JDBCStringRoutines; + + +/** + * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank. + * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse. + * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben. + * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten + * Treiber, Host, User und Passwort, ueber den der Zugriff auf die + * Datenbank erfolgt. + * + * @version $Id: Database.java,v 1.33 2003/02/20 16:05:33 zapata Exp $ + * @author rk + * + */ +public class Database implements StorageObject { + private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + + + private static SimpleHash POPUP_EMPTYLINE = new SimpleHash(); + protected static final ObjectStore o_store = ObjectStore.getInstance(); + private static final int _millisPerHour = 60 * 60 * 1000; + private static final int _millisPerMinute = 60 * 1000; + + static { + // always same object saves a little space + POPUP_EMPTYLINE.put("key", ""); + POPUP_EMPTYLINE.put("value", "--"); + } + + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + protected String theTable; + protected String theCoreTable = null; + protected String thePKeyName = "id"; + protected int thePKeyType; + protected int thePKeyIndex; + protected boolean evaluatedMetaData = false; + protected ArrayList metadataFields; + protected ArrayList metadataLabels; + protected ArrayList metadataNotNullFields; + protected int[] metadataTypes; + protected Class theEntityClass; + protected StorageObject myselfDatabase; + protected SimpleList popupCache = null; + protected boolean hasPopupCache = false; + protected SimpleHash hashCache = null; + protected boolean hasTimestamp = true; + private String database_driver; + private String database_url; + private int defaultLimit; + protected DatabaseAdaptor theAdaptor; + private SimpleDateFormat _dateFormatterOut = + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private SimpleDateFormat _dateFormatterIn = + new SimpleDateFormat("yyyy-MM-dd HH:mm"); + private Calendar _cal = new GregorianCalendar(); + + /** + * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. + * Aus diesem file werden Database.Logfile, + * Database.Username,Database.Password, + * Database.Host und Database.Adaptor + * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank + * erzeugt. + * + * @param String confFilename Dateiname der Konfigurationsdatei + */ + public Database() throws StorageObjectFailure { + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new StorageObjectFailure(e); + } + logger = new LoggerWrapper("Database"); + + String theAdaptorName = configuration.getString("Database.Adaptor"); + defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); + + try { + theEntityClass = GENERIC_ENTITY_CLASS; + theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance(); + } + catch (Throwable e) { + logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); + throw new StorageObjectFailure("Error in Database() constructor.", e); + } + } + + /** + * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt + * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben, + * wird eine mir.entity.GenericEntity erzeugt. + * + * @return Class-Objekt der Entity + */ + public java.lang.Class getEntityClass() { + return theEntityClass; + } + + /** + * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also + * wieviel Datens?tze per Default selektiert werden. + * + * @return Standard-Anzahl der Datens?tze + */ + public int getLimit() { + return defaultLimit; + } + + /** + * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von + * der erbenden Klasse ?berschrieben, so ist der Wert PKEY + * @return Name des Primary-Keys + */ + public String getIdName() { + return thePKeyName; + } + + /** + * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. + * + * @return Name der Tabelle + */ + public String getTableName() { + return theTable; + } + + /* + * Dient dazu vererbte Tabellen bei objectrelationalen DBMS + * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet + * wird. + * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst + * the Table + */ + public String getCoreTable() { + if (theCoreTable != null) { + return theCoreTable; + } else { + return theTable; + } + } + + /** + * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types) + * @return int-Array mit den Typen der Felder + * @exception StorageObjectException + */ + public int[] getTypes() throws StorageObjectFailure { + if (metadataTypes == null) { + get_meta_data(); + } + + return metadataTypes; + } + + /** + * Liefert eine Liste der Labels der Tabellenfelder + * @return ArrayListe mit Labeln + * @exception StorageObjectException + */ + public List getLabels() throws StorageObjectFailure { + if (metadataLabels == null) { + get_meta_data(); + } + + return metadataLabels; + } + + /** + * Liefert eine Liste der Felder der Tabelle + * @return ArrayList mit Feldern + * @exception StorageObjectException + */ + public List getFields() throws StorageObjectFailure { + if (metadataFields == null) { + get_meta_data(); + } + + return metadataFields; + } + + /* + * Gets value out of ResultSet according to type and converts to String + * @param inValue Wert aus ResultSet. + * @param aType Datenbanktyp. + * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich + * dann /unsupported value/ + */ + private String getValueAsString(ResultSet rs, int valueIndex, int aType) + throws StorageObjectFailure { + String outValue = null; + + if (rs != null) { + try { + switch (aType) { + case java.sql.Types.BIT: + outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; + + break; + + case java.sql.Types.INTEGER: + case java.sql.Types.SMALLINT: + case java.sql.Types.TINYINT: + case java.sql.Types.BIGINT: + + int out = rs.getInt(valueIndex); + + if (!rs.wasNull()) { + outValue = new Integer(out).toString(); + } + + break; + + case java.sql.Types.NUMERIC: + + /** @todo Numeric can be float or double depending upon + * metadata.getScale() / especially with oracle */ + long outl = rs.getLong(valueIndex); + + if (!rs.wasNull()) { + outValue = new Long(outl).toString(); + } + + break; + + case java.sql.Types.REAL: + + float tempf = rs.getFloat(valueIndex); + + if (!rs.wasNull()) { + tempf *= 10; + tempf += 0.5; + + int tempf_int = (int) tempf; + tempf = (float) tempf_int; + tempf /= 10; + outValue = "" + tempf; + outValue = outValue.replace('.', ','); + } + + break; + + case java.sql.Types.DOUBLE: + + double tempd = rs.getDouble(valueIndex); + + if (!rs.wasNull()) { + tempd *= 10; + tempd += 0.5; + + int tempd_int = (int) tempd; + tempd = (double) tempd_int; + tempd /= 10; + outValue = "" + tempd; + outValue = outValue.replace('.', ','); + } + + break; + + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + outValue = rs.getString(valueIndex); + + break; + + case java.sql.Types.LONGVARBINARY: + outValue = rs.getString(valueIndex); + + break; + + case java.sql.Types.TIMESTAMP: + + // it's important to use Timestamp here as getting it + // as a string is undefined and is only there for debugging + // according to the API. we can make it a string through formatting. + // -mh + Timestamp timestamp = (rs.getTimestamp(valueIndex)); + + if (!rs.wasNull()) { + java.util.Date date = new java.util.Date(timestamp.getTime()); + outValue = _dateFormatterOut.format(date); + _cal.setTime(date); + + int offset = + _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET); + String tzOffset = + StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2); + outValue = outValue + "+" + tzOffset; + } + + break; + + default: + outValue = ""; + logger.warn( "Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); + } + } catch (SQLException e) { + throw new StorageObjectFailure("Could not get Value out of Resultset -- ", + e); + } + } + + return outValue; + } + + /* + * select-Operator um einen Datensatz zu bekommen. + * @param id Primaerschluessel des Datensatzes. + * @return liefert EntityObject des gefundenen Datensatzes oder null. + */ + public Entity selectById(String id) throws StorageObjectExc { + if ((id == null) || id.equals("")) { + throw new StorageObjectExc("Database.selectById: Missing id"); + } + + // ask object store for object + if (StoreUtil.implementsStorableObject(theEntityClass)) { + String uniqueId = id; + + if (theEntityClass.equals(StorableObjectEntity.class)) { + uniqueId += ("@" + theTable); + } + + StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId); + logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString()); + + Entity hit = (Entity) o_store.use(search_sid); + + if (hit != null) { + return hit; + } + } + + Statement stmt = null; + Connection con = getPooledCon(); + Entity returnEntity = null; + + try { + ResultSet rs; + + /** @todo better prepared statement */ + String selectSql = + "select * from " + theTable + " where " + thePKeyName + "=" + id; + stmt = con.createStatement(); + rs = executeSql(stmt, selectSql); + + if (rs != null) { + if (evaluatedMetaData == false) { + evalMetaData(rs.getMetaData()); + } + + if (rs.next()) { + returnEntity = makeEntityFromResultSet(rs); + } + else { + logger.debug("No data for id: " + id + " in table " + theTable); + } + + rs.close(); + } + else { + logger.debug("No Data for Id " + id + " in Table " + theTable); + } + } + catch (SQLException sqe) { + throwSQLException(sqe, "selectById"); + return null; + } + catch (NumberFormatException e) { + logger.error("ID is no number: " + id); + } + finally { + freeConnection(con, stmt); + } + + return returnEntity; + } + + /** + * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. + * @param key Datenbankfeld der Bedingung. + * @param value Wert die der key anehmen muss. + * @return EntityList mit den gematchten Entities + */ + public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure { + return selectByFieldValue(aField, aValue, 0); + } + + /** + * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. + * @param key Datenbankfeld der Bedingung. + * @param value Wert die der key anehmen muss. + * @param offset Gibt an ab welchem Datensatz angezeigt werden soll. + * @return EntityList mit den gematchten Entities + */ + public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure { + return selectByWhereClause(aField + "=" + aValue, offset); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Also offset wird der erste Datensatz genommen. + * + * @param wc where-Clause + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String where) + throws StorageObjectFailure { + return selectByWhereClause(where, 0); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param offset ab welchem Datensatz. + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String whereClause, int offset) + throws StorageObjectFailure { + return selectByWhereClause(whereClause, null, offset); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Also offset wird der erste Datensatz genommen. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param ob orderBy-Clause + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String where, String order) + throws StorageObjectFailure { + return selectByWhereClause(where, order, 0); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param ob orderBy-Clause + * @param offset ab welchem Datensatz + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String whereClause, String orderBy, + int offset) throws StorageObjectFailure { + return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * @param wc where-Clause + * @param ob orderBy-Clause + * @param offset ab welchem Datensatz + * @param limit wieviele Datens?tze + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String wc, String ob, int offset, + int limit) throws StorageObjectFailure { + // check o_store for entitylist + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreIdentifier search_sid = + new StoreIdentifier(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST, + StoreUtil.getEntityListUniqueIdentifierFor(theTable, wc, ob, offset, + limit)); + EntityList hit = (EntityList) o_store.use(search_sid); + + if (hit != null) { + logger.debug("CACHE (hit): " + search_sid.toString()); + + return hit; + } + } + + // local + EntityList theReturnList = null; + Connection con = null; + Statement stmt = null; + ResultSet rs; + int offsetCount = 0; + int count = 0; + + // build sql-statement + + /** @todo count sql string should only be assembled if we really count + * see below at the end of method //rk */ + if ((wc != null) && (wc.length() == 0)) { + wc = null; + } + + StringBuffer countSql = + new StringBuffer("select count(*) from ").append(theTable); + StringBuffer selectSql = + new StringBuffer("select * from ").append(theTable); + + if (wc != null) { + selectSql.append(" where ").append(wc); + countSql.append(" where ").append(wc); + } + + if ((ob != null) && !(ob.length() == 0)) { + selectSql.append(" order by ").append(ob); + } + + if (theAdaptor.hasLimit()) { + if ((limit > -1) && (offset > -1)) { + selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset); + } + } + + // execute sql + try { + con = getPooledCon(); + stmt = con.createStatement(); + + // selecting... + rs = executeSql(stmt, selectSql.toString()); + + if (rs != null) { + if (!evaluatedMetaData) { + evalMetaData(rs.getMetaData()); + } + + theReturnList = new EntityList(); + + Entity theResultEntity; + + while (rs.next()) { + theResultEntity = makeEntityFromResultSet(rs); + theReturnList.add(theResultEntity); + offsetCount++; + } + + rs.close(); + } + + // making entitylist infos + if (!(theAdaptor.hasLimit())) { + count = offsetCount; + } + + if (theReturnList != null) { + // now we decide if we have to know an overall count... + count = offsetCount; + + if ((limit > -1) && (offset > -1)) { + if (offsetCount == limit) { + /** @todo counting should be deffered to entitylist + * getSize() should be used */ + rs = executeSql(stmt, countSql.toString()); + + if (rs != null) { + if (rs.next()) { + count = rs.getInt(1); + } + + rs.close(); + } + else { + logger.error("Could not count: " + countSql); + } + } + } + + theReturnList.setCount(count); + theReturnList.setOffset(offset); + theReturnList.setWhere(wc); + theReturnList.setOrder(ob); + theReturnList.setStorage(this); + theReturnList.setLimit(limit); + + if (offset >= limit) { + theReturnList.setPrevBatch(offset - limit); + } + + if ((offset + offsetCount) < count) { + theReturnList.setNextBatch(offset + limit); + } + + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreIdentifier sid = theReturnList.getStoreIdentifier(); + logger.debug("CACHE (add): " + sid.toString()); + o_store.add(sid); + } + } + } catch (SQLException sqe) { + throwSQLException(sqe, "selectByWhereClause"); + } finally { + try { + if (con != null) { + freeConnection(con, stmt); + } + } catch (Throwable t) { + } + } + + return theReturnList; + } + + /** + * Bastelt aus einer Zeile der Datenbank ein EntityObjekt. + * + * @param rs Das ResultSetObjekt. + * @return Entity Die Entity. + */ + private Entity makeEntityFromResultSet(ResultSet rs) + throws StorageObjectFailure { + /** @todo OS: get Pkey from ResultSet and consult ObjectStore */ + HashMap theResultHash = new HashMap(); + String theResult = null; + int theType; + Entity returnEntity = null; + + try { + int size = metadataFields.size(); + + for (int i = 0; i < size; i++) { + // alle durchlaufen bis nix mehr da + theType = metadataTypes[i]; + + if (theType == java.sql.Types.LONGVARBINARY) { + InputStreamReader is = + (InputStreamReader) rs.getCharacterStream(i + 1); + + if (is != null) { + char[] data = new char[32768]; + StringBuffer theResultString = new StringBuffer(); + int len; + + while ((len = is.read(data)) > 0) { + theResultString.append(data, 0, len); + } + + is.close(); + theResult = theResultString.toString(); + } else { + theResult = null; + } + } else { + theResult = getValueAsString(rs, (i + 1), theType); + } + + if (theResult != null) { + theResultHash.put(metadataFields.get(i), theResult); + } + } + + if (theEntityClass != null) { + returnEntity = (Entity) theEntityClass.newInstance(); + returnEntity.setValues(theResultHash); + returnEntity.setStorage(myselfDatabase); + + if (returnEntity instanceof StorableObject) { + logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable); + o_store.add(((StorableObject) returnEntity).getStoreIdentifier()); + } + } else { + throwStorageObjectException("Internal Error: theEntityClass not set!"); + } + } catch (IllegalAccessException e) { + throwStorageObjectException("No access! -- " + e.getMessage()); + } catch (IOException e) { + throwStorageObjectException("IOException! -- " + e.getMessage()); + } catch (InstantiationException e) { + throwStorageObjectException("No Instatiation! -- " + e.getMessage()); + } catch (SQLException sqe) { + throwSQLException(sqe, "makeEntityFromResultSet"); + + return null; + } + + return returnEntity; + } + + /** + * insert-Operator: f?gt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE + * wird automatisch mit dem aktuellen Datum gefuellt. + * + * @param theEntity + * @return der Wert des Primary-keys der eingef?gten Entity + */ + public String insert(Entity theEntity) throws StorageObjectFailure { + //cache + invalidatePopupCache(); + + // invalidating all EntityLists corresponding with theEntityClass + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = + StoreContainerType.valueOf(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + String returnId = null; + Connection con = null; + PreparedStatement pstmt = null; + + try { + List streamedInput = theEntity.streamedInput(); + StringBuffer f = new StringBuffer(); + StringBuffer v = new StringBuffer(); + String aField; + String aValue; + boolean firstField = true; + + // make sql-string + for (int i = 0; i < getFields().size(); i++) { + aField = (String) getFields().get(i); + + if (!aField.equals(thePKeyName)) { + aValue = null; + + // exceptions + if (aField.equals("webdb_create") || + aField.equals("webdb_lastchange")) { + aValue = "NOW()"; + } else { + if ((streamedInput != null) && streamedInput.contains(aField)) { + aValue = "?"; + } else { + if (theEntity.hasValueForField(aField)) { + aValue = + "'" + + JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue( + aField)) + "'"; + } + } + } + + // wenn Wert gegeben, dann einbauen + if (aValue != null) { + if (firstField == false) { + f.append(","); + v.append(","); + } + else { + firstField = false; + } + + f.append(aField); + v.append(aValue); + } + } + } + // end for + + // insert into db + StringBuffer sqlBuf = + new StringBuffer("insert into ").append(theTable).append("(").append(f) + .append(") values (").append(v).append(")"); + String sql = sqlBuf.toString(); + + //theLog.printInfo("INSERT: " + sql); + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql); + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = + (String) theEntity.getValue((String) streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + + int ret = pstmt.executeUpdate(); + + if (ret == 0) { + //insert failed + return null; + } + + pstmt = + con.prepareStatement(theAdaptor.getLastInsertSQL( + (Database) myselfDatabase)); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + returnId = rs.getString(1); + theEntity.setId(returnId); + } + catch (SQLException sqe) { + throwSQLException(sqe, "insert"); + } + finally { + try { + con.setAutoCommit(true); + } + catch (Exception e) { + } + + freeConnection(con, pstmt); + } + + /** @todo store entity in o_store */ + return returnId; + } + + /** + * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE + * wird automatisch mit dem aktuellen Datum gefuellt. + * + * @param theEntity + */ + public void update(Entity theEntity) throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + + /** @todo this is stupid: why do we prepare statement, when we + * throw it away afterwards. should be regular statement + * update/insert could better be one routine called save() + * that chooses to either insert or update depending if we + * have a primary key in the entity. i don't know if we + * still need the streamed input fields. // rk */ + /** @todo extension: check if Entity did change, otherwise we don't need + * the roundtrip to the database */ + /** invalidating corresponding entitylists in o_store*/ + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = + StoreContainerType.valueOf(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + List streamedInput = theEntity.streamedInput(); + String id = theEntity.getId(); + String aField; + StringBuffer fv = new StringBuffer(); + boolean firstField = true; + + //cache + invalidatePopupCache(); + + // build sql statement + for (int i = 0; i < getFields().size(); i++) { + aField = (String) metadataFields.get(i); + + // only normal cases + if ( !(aField.equals(thePKeyName) || + aField.equals("webdb_create") || + aField.equals("webdb_lastchange") || + ((streamedInput != null) && streamedInput.contains(aField)))) { + if (theEntity.hasValueForField(aField)) { + if (firstField == false) { + fv.append(", "); + } + else { + firstField = false; + } + + fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'"); + + // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'"); + } + } + } + + StringBuffer sql = + new StringBuffer("update ").append(theTable).append(" set ").append(fv); + + // exceptions + if (metadataFields.contains("webdb_lastchange")) { + sql.append(",webdb_lastchange=NOW()"); + } + + // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm + // format so anything extra will be ignored. -mh + if (metadataFields.contains("webdb_create") && + theEntity.hasValueForField("webdb_create")) { + // minimum of 10 (yyyy-mm-dd)... + if (theEntity.getValue("webdb_create").length() >= 10) { + String dateString = theEntity.getValue("webdb_create"); + + // if only 10, then add 00:00 so it doesn't throw a ParseException + if (dateString.length() == 10) { + dateString = dateString + " 00:00"; + } + + // TimeStamp stuff + try { + java.util.Date d = _dateFormatterIn.parse(dateString); + Timestamp tStamp = new Timestamp(d.getTime()); + sql.append(",webdb_create='" + tStamp.toString() + "'"); + } catch (ParseException e) { + throw new StorageObjectFailure(e); + } + } + } + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + sql.append(",").append(streamedInput.get(i)).append("=?"); + } + } + + sql.append(" where id=").append(id); + + //theLog.printInfo("UPDATE: " + sql); + // execute sql + try { + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql.toString()); + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = + theEntity.getValue((String) streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + + pstmt.executeUpdate(); + } catch (SQLException sqe) { + throwSQLException(sqe, "update"); + } finally { + try { + con.setAutoCommit(true); + } catch (Exception e) { + ; + } + + freeConnection(con, pstmt); + } + } + + /* + * delete-Operator + * @param id des zu loeschenden Datensatzes + * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. + */ + public boolean delete(String id) throws StorageObjectFailure { + invalidatePopupCache(); + + // ostore send notification + if (StoreUtil.implementsStorableObject(theEntityClass)) { + String uniqueId = id; + + if (theEntityClass.equals(StorableObjectEntity.class)) { + uniqueId += ("@" + theTable); + } + + logger.debug("CACHE: (del) " + id); + + StoreIdentifier search_sid = + new StoreIdentifier(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITY, uniqueId); + o_store.invalidate(search_sid); + } + + /** @todo could be prepared Statement */ + Statement stmt = null; + Connection con = null; + int res = 0; + String sql = + "delete from " + theTable + " where " + thePKeyName + "='" + id + "'"; + + //theLog.printInfo("DELETE " + sql); + try { + con = getPooledCon(); + stmt = con.createStatement(); + res = stmt.executeUpdate(sql); + } catch (SQLException sqe) { + throwSQLException(sqe, "delete"); + } finally { + freeConnection(con, stmt); + } + + return (res > 0) ? true : false; + } + + /* noch nicht implementiert. + * @return immer false + */ + public boolean delete(EntityList theEntityList) { + invalidatePopupCache(); + + return false; + } + + /** + * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse + * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll. + * @return null + */ + public SimpleList getPopupData() throws StorageObjectFailure { + return null; + } + + /** + * Holt Daten fuer Popups. + * @param name Name des Feldes. + * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. + * @return SimpleList Gibt freemarker.template.SimpleList zurueck. + */ + public SimpleList getPopupData(String name, boolean hasNullValue) + throws StorageObjectFailure { + return getPopupData(name, hasNullValue, null); + } + + /** + * Holt Daten fuer Popups. + * @param name Name des Feldes. + * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. + * @param where Schraenkt die Selektion der Datensaetze ein. + * @return SimpleList Gibt freemarker.template.SimpleList zurueck. + */ + public SimpleList getPopupData(String name, boolean hasNullValue, String where) + throws StorageObjectFailure { + return getPopupData(name, hasNullValue, where, null); + } + + /** + * Holt Daten fuer Popups. + * @param name Name des Feldes. + * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. + * @param where Schraenkt die Selektion der Datensaetze ein. + * @param order Gibt ein Feld als Sortierkriterium an. + * @return SimpleList Gibt freemarker.template.SimpleList zurueck. + */ + public SimpleList getPopupData(String name, boolean hasNullValue, + String where, String order) throws StorageObjectFailure { + // caching + if (hasPopupCache && (popupCache != null)) { + return popupCache; + } + + SimpleList simpleList = null; + Connection con = null; + Statement stmt = null; + + // build sql + StringBuffer sql = + new StringBuffer("select ").append(thePKeyName).append(",").append(name) + .append(" from ").append(theTable); + + if ((where != null) && !(where.length() == 0)) { + sql.append(" where ").append(where); + } + + sql.append(" order by "); + + if ((order != null) && !(order.length() == 0)) { + sql.append(order); + } else { + sql.append(name); + } + + // execute sql + try { + con = getPooledCon(); + } catch (Exception e) { + throw new StorageObjectFailure(e); + } + + try { + stmt = con.createStatement(); + + ResultSet rs = executeSql(stmt, sql.toString()); + + if (rs != null) { + if (!evaluatedMetaData) { + get_meta_data(); + } + + simpleList = new SimpleList(); + + // if popup has null-selector + if (hasNullValue) { + simpleList.add(POPUP_EMPTYLINE); + } + + SimpleHash popupDict; + + while (rs.next()) { + popupDict = new SimpleHash(); + popupDict.put("key", getValueAsString(rs, 1, thePKeyType)); + popupDict.put("value", rs.getString(2)); + simpleList.add(popupDict); + } + + rs.close(); + } + } + catch (Exception e) { + logger.error("getPopupData: " + e.getMessage()); + throw new StorageObjectFailure(e); + } finally { + freeConnection(con, stmt); + } + + if (hasPopupCache) { + popupCache = simpleList; + } + + return simpleList; + } + + /** + * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt, + * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen + * Tabellen Verwendung finden. + * @return SimpleHash mit den Tabellezeilen. + */ + public SimpleHash getHashData() { + /** @todo dangerous! this should have a flag to be enabled, otherwise + * very big Hashes could be returned */ + if (hashCache == null) { + try { + hashCache = + HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1)); + } + catch (StorageObjectFailure e) { + logger.debug(e.getMessage()); + } + } + + return hashCache; + } + + /* invalidates the popupCache + */ + protected void invalidatePopupCache() { + /** @todo invalidates toooo much */ + popupCache = null; + hashCache = null; + } + + /** + * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. + * @param stmt Statemnt + * @param sql Sql-String + * @return ResultSet + * @exception StorageObjectException + */ + public ResultSet executeSql(Statement stmt, String sql) + throws StorageObjectFailure, SQLException { + ResultSet rs; + long startTime = System.currentTimeMillis(); + + try { + rs = stmt.executeQuery(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + } + catch (SQLException e) { + logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw e; + } + + return rs; + } + + /** + * returns the number of rows in the table + */ + public int getSize(String where) throws SQLException, StorageObjectFailure { + long startTime = System.currentTimeMillis(); + String sql = "SELECT Count(*) FROM " + theTable; + + if ((where != null) && !(where.length() == 0)) { + sql = sql + " where " + where; + } + + Connection con = null; + Statement stmt = null; + int result = 0; + + try { + con = getPooledCon(); + stmt = con.createStatement(); + + ResultSet rs = executeSql(stmt, sql); + + while (rs.next()) { + result = rs.getInt(1); + } + } + catch (SQLException e) { + logger.error("Database.getSize: " + e.getMessage()); + } + finally { + freeConnection(con, stmt); + } + + //theLog.printInfo(theTable + " has "+ result +" rows where " + where); + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + + return result; + } + + public int executeUpdate(Statement stmt, String sql) + throws StorageObjectFailure, SQLException { + int rs; + long startTime = System.currentTimeMillis(); + + try { + rs = stmt.executeUpdate(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + } + catch (SQLException e) { + logger.debug("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw e; + } + + return rs; + } + + public int executeUpdate(String sql) + throws StorageObjectFailure, SQLException { + int result = -1; + long startTime = System.currentTimeMillis(); + Connection con = null; + PreparedStatement pstmt = null; + + try { + con = getPooledCon(); + pstmt = con.prepareStatement(sql); + result = pstmt.executeUpdate(); + } + catch (Throwable e) { + logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage()); + throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); + } + finally { + freeConnection(con, pstmt); + } + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + return result; + } + + /** + * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend + * @param md ResultSetMetaData + * @exception StorageObjectException + */ + private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure { + this.evaluatedMetaData = true; + this.metadataFields = new ArrayList(); + this.metadataLabels = new ArrayList(); + this.metadataNotNullFields = new ArrayList(); + + try { + int numFields = md.getColumnCount(); + this.metadataTypes = new int[numFields]; + + String aField; + int aType; + + for (int i = 1; i <= numFields; i++) { + aField = md.getColumnName(i); + metadataFields.add(aField); + metadataLabels.add(md.getColumnLabel(i)); + aType = md.getColumnType(i); + metadataTypes[i - 1] = aType; + + if (aField.equals(thePKeyName)) { + thePKeyType = aType; + thePKeyIndex = i; + } + + if (md.isNullable(i) == ResultSetMetaData.columnNullable) { + metadataNotNullFields.add(aField); + } + } + } + catch (SQLException e) { + throwSQLException(e, "evalMetaData"); + } + } + + /** + * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus, + * um die alle Columns und Typen einer Tabelle zu ermitteln. + */ + private void get_meta_data() throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + String sql = "select * from " + theTable + " where 0=1"; + + try { + con = getPooledCon(); + pstmt = con.prepareStatement(sql); + + logger.debug("METADATA: " + sql); + ResultSet rs = pstmt.executeQuery(); + evalMetaData(rs.getMetaData()); + rs.close(); + } + catch (SQLException e) { + throwSQLException(e, "get_meta_data"); + } + finally { + freeConnection(con, pstmt); + } + } + + public Connection getPooledCon() throws StorageObjectFailure { + Connection con = null; + + try { + con = SQLManager.getInstance().requestConnection(); + } + catch (SQLException e) { + logger.error("could not connect to the database " + e.getMessage()); + System.err.println("could not connect to the database " + e.getMessage()); + throw new StorageObjectFailure("Could not connect to the database", e); + } + + return con; + } + + public void freeConnection(Connection con, Statement stmt) + throws StorageObjectFailure { + SQLManager.closeStatement(stmt); + SQLManager.getInstance().returnConnection(con); + } + + /** + * Wertet SQLException aus und wirft dannach eine StorageObjectException + * @param sqe SQLException + * @param wo Funktonsname, in der die SQLException geworfen wurde + * @exception StorageObjectException + */ + protected void throwSQLException(SQLException sqe, String aFunction) + throws StorageObjectFailure { + String state = ""; + String message = ""; + int vendor = 0; + + if (sqe != null) { + state = sqe.getSQLState(); + message = sqe.getMessage(); + vendor = sqe.getErrorCode(); + } + + String information = + "SQL Error: " + + "state= " + state + + ", vendor= " + vendor + + ", message=" + message + + ", function= " + aFunction; + + logger.error(information); + + throw new StorageObjectFailure(information, sqe); + } + + protected void _throwStorageObjectException(Exception e, String aFunction) + throws StorageObjectFailure { + + if (e != null) { + logger.error(e.getMessage() + aFunction); + throw new StorageObjectFailure(aFunction, e); + } + } + + /** + * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach + * eine StorageObjectException + * @param message Nachricht mit dem Fehler + * @exception StorageObjectException + */ + void throwStorageObjectException(String aMessage) throws StorageObjectFailure { + logger.error(aMessage); + throw new StorageObjectFailure(aMessage, null); + } +} diff --git a/source/mir/storage/StorageObject.java b/source/mir/storage/StorageObject.java index 773aaedc..ac85d056 100755 --- a/source/mir/storage/StorageObject.java +++ b/source/mir/storage/StorageObject.java @@ -46,7 +46,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; -import java.util.ArrayList; +import java.util.List; /** @@ -130,7 +130,7 @@ public interface StorageObject { * @return ArrayList * @exception StorageObjectException */ - abstract public ArrayList getFields() throws StorageObjectFailure; + abstract public List getFields() throws StorageObjectFailure; /** * Dokumentation siehe Database.java @@ -144,7 +144,7 @@ public interface StorageObject { * @return ArrayList * @exception StorageObjectException */ - abstract public ArrayList getLabels() throws StorageObjectFailure; + abstract public List getLabels() throws StorageObjectFailure; /** * Dokumentation siehe Database.java diff --git a/source/mir/storage/store/ObjectStore.java b/source/mir/storage/store/ObjectStore.java index 10191ffe..73aea10b 100755 --- a/source/mir/storage/store/ObjectStore.java +++ b/source/mir/storage/store/ObjectStore.java @@ -1,277 +1,286 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.storage.store; - -/** - * Title: ObjectStore for StorableObjects - * Description: ObjectStore holds a Map of @see StoreContainer for all possible - * @see StoreIdentifier. - * - * @see StorageIdentifier - identitfies one object in the ObjectStore - * i.e. in its apropriate bucket. It holds a unique identifier - * of a StorableObject and a reference on the StorableObject. - * - * @see StoreContainer - "Buckets" to store different types of Objects - * in one Container. These buckets are cofigurable via - * config.properties. - * - * @see StoreContainerType - is a signature for all StoreContainer - * and StoreIdentifier. - * - * @see StorableObjects - Interface Object have to implement to - * be handled by the ObjectStore - * - * @see ServletStoreInfo - Maintenance Servlet for ObjectStore. - * Displays information about current content of the - * ObjectStore. - * - * - * Copyright: Copyright (c) 2002 - * Company: indy - * @author rk - * @version 1.0 - */ - -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.MissingResourceException; -import java.util.Properties; - -import javax.servlet.http.HttpServletRequest; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.misc.Logfile; - -public class ObjectStore { - - private final static ObjectStore INSTANCE=new ObjectStore(); - private final static HashMap containerMap=new HashMap(); // StoreContainerType/StoreContainer - private static Logfile storeLog; - private static long storeHit=0,storeMiss=0; - private Properties ostoreConf; - - private ObjectStore() { - String confName = null; - try { - confName = - MirPropertiesConfiguration.instance().getString("Home") - + "etc/objectstore.properties"; - } catch (PropertiesConfigExc e) { - e.printStackTrace(System.err); - } - Properties conf = new Properties(); - try { - conf.load( new BufferedInputStream(new FileInputStream(confName))); - } - catch ( java.io.FileNotFoundException fnfe ) { - System.err.println("could not read config file. not found: "+confName); - } - catch ( java.io.IOException ioex ) { - System.err.println("could not read config file: "+confName); - } - ostoreConf = conf; - } - public static ObjectStore getInstance() { return INSTANCE; } - - - /** - * Method: use - * Description: The ObjectStore tries to find the @see StoreIdentifier sid - * and returns the stored Object. - * - * @return StorableObject is null when no StorableObject for the - * StoreIdentifier sid is found. - */ - public StorableObject use(StoreIdentifier sid) { - if (sid!=null ) { - StorableObject storeObject=null; - StoreContainer stoc = getStoreContainerForSid( sid ); - if (stoc!=null) storeObject=stoc.use(sid); - else System.out.println("Warning: container not found for: " + sid.toString()); - if (storeObject!=null) { - storeHit++; - return storeObject; - } - } - storeMiss++; return null; - - } - - /** - * Method: add - * Description: A StoreIdentifier is added to the ObjectStore, if it - * contains a reference to a @see StorableObject. - */ - public void add(StoreIdentifier sid) { - if ( sid!=null && sid.hasReference() ) { - // find the right StoreContainer for sid - StoreContainer stoc = getStoreContainerForSid(sid); - if (stoc==null) { - // we have to make new StoreContainer - StoreContainerType stocType = sid.getStoreContainerType(); - stoc = new StoreContainer(stocType); - containerMap.put(stocType, stoc); - } - stoc.add(sid); - } - } - - /** - * Method: invalidate(StorableObject sto) - * Description: ObjectStore is notified of change of a @see StorableObject - * sto and invalidates all relevant cache entries. - */ - - public void invalidate(StoreIdentifier sid) { - // propagate invalidation to StoreContainer - if (sid!=null) { - StoreContainer stoc = getStoreContainerForSid(sid); - stoc.invalidate(sid); - } - } - - /** - * Method: invalidate(StoreContainerType) - * Description: serves to invalidate a whole StoreContainer - * - * @return - */ - public void invalidate(StoreContainerType stoc_type) { - if ( stoc_type != null ) { - /** @todo invalidates too much: - * improvement: if instanceof StoreContainerEntity && EntityList - * then invalidate only StoreIdentifier matching the right table - */ - StoreContainer stoc = getStoreContainerForStocType(stoc_type); - if ( stoc!=null ) - stoc.invalidate(); - } - - } - - // internal methods for StoreContainer managment - - /** - * Method: getStoreContainerForSid - * Description: private method to find the right @see StoreContainer for - * the @see StoreIdentifier sid. - * - * @return StoreContainer is null when no Container is found. - */ - private StoreContainer getStoreContainerForSid(StoreIdentifier sid){ - // find apropriate container for a specific sid - if (sid!=null) { - StoreContainerType stoc_type = sid.getStoreContainerType(); - return getStoreContainerForStocType(stoc_type); - } - return null; - } - - private StoreContainer getStoreContainerForStocType(StoreContainerType stoc_type) { - if ( stoc_type!=null && containerMap.containsKey(stoc_type) ) - return (StoreContainer)containerMap.get(stoc_type); - return null; - } - - private boolean has(StoreIdentifier sid) { - StoreContainer stoc = getStoreContainerForSid( sid ); - return ( stoc != null && stoc.has(sid) ) ? true:false; - } - - public String getConfProperty(String name) { - if (name!=null ) { - String returnValue=""; - try { - return ostoreConf.getProperty(name); - } - catch (MissingResourceException e) { - System.err.println("ObjectStore: " + e.toString()); - } - } - return null; - } - - /** - * Method: toString() - * Description: Displays statistical information about the ObjectStore. - * Further information is gathered from all @see StoreContainer - * - * @return String - */ - public String toString() { - return toHtml(null); - } - - public String toHtml(HttpServletRequest req) { - float hitRatio=0; - long divisor=storeHit+storeMiss; - if (divisor>0) hitRatio=(float)storeHit/(float)divisor; - hitRatio*=100; - - StringBuffer sb = new StringBuffer("Mir-ObjectStore "); - sb.append( ((req!=null) ? html_version():version()) ).append("\n"); - sb.append("ObjectStore overall hits/misses/ratio: ").append(storeHit); - sb.append("/").append(storeMiss).append("/").append(hitRatio); - sb.append("%\nCurrently ").append(containerMap.size()); - sb.append(" StoreContainer in use - listing information:\n"); - - // ask container for information - StoreContainer currentStoc; - for(Iterator it=containerMap.keySet().iterator();it.hasNext();) { - currentStoc=(StoreContainer)containerMap.get(it.next()); - sb.append(currentStoc.toHtml(req)); - } - - return sb.toString(); - } - - - /** - * Method: html_version() - * Description: returns ObjectStore version as String for HTML representation - * - * @return String - */ - private String html_version() { return ""+version()+""; } - - /** - * Method: version() - * Description: returns ObjectStore version as String - * - * @return String - */ - private String version() { return "v_sstart3__1.0"; } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.storage.store; + +/** + * Title: ObjectStore for StorableObjects + * Description: ObjectStore holds a Map of @see StoreContainer for all possible + * @see StoreIdentifier. + * + * @see StorageIdentifier - identitfies one object in the ObjectStore + * i.e. in its apropriate bucket. It holds a unique identifier + * of a StorableObject and a reference on the StorableObject. + * + * @see StoreContainer - "Buckets" to store different types of Objects + * in one Container. These buckets are cofigurable via + * config.properties. + * + * @see StoreContainerType - is a signature for all StoreContainer + * and StoreIdentifier. + * + * @see StorableObjects - Interface Object have to implement to + * be handled by the ObjectStore + * + * @see ServletStoreInfo - Maintenance Servlet for ObjectStore. + * Displays information about current content of the + * ObjectStore. + * + * + * Copyright: Copyright (c) 2002 + * Company: indy + * @author rk + * @version 1.0 + */ + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Iterator; +import java.util.MissingResourceException; +import java.util.Properties; + +import javax.servlet.http.HttpServletRequest; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.log.LoggerWrapper; + +public class ObjectStore { + + private final static ObjectStore INSTANCE = new ObjectStore(); + private final static HashMap containerMap = new HashMap(); // StoreContainerType/StoreContainer + private static long storeHit = 0, storeMiss = 0; + private Properties ostoreConf; + private LoggerWrapper logger; + + private ObjectStore() { + String confName = null; + + logger = new LoggerWrapper("Database.ObjectStore"); + Properties conf = new Properties(); + + try { + confName = + MirPropertiesConfiguration.instance().getString("Home") + + "etc/objectstore.properties"; + conf.load(new BufferedInputStream(new FileInputStream(confName))); + } + catch (java.io.FileNotFoundException fnfe) { + logger.error("could not read config file. not found: " + confName); + } + catch (Throwable t) { + logger.error("could not get config: " + t.getMessage()); + } + ostoreConf = conf; + } + + public static ObjectStore getInstance() { + return INSTANCE; + } + + /** + * Method: use + * Description: The ObjectStore tries to find the @see StoreIdentifier sid + * and returns the stored Object. + * + * @return StorableObject is null when no StorableObject for the + * StoreIdentifier sid is found. + */ + public StorableObject use(StoreIdentifier sid) { + if (sid != null) { + StorableObject storeObject = null; + StoreContainer stoc = getStoreContainerForSid(sid); + if (stoc != null) + storeObject = stoc.use(sid); + else + logger.warn("container not found for: " + sid.toString()); + if (storeObject != null) { + storeHit++; + return storeObject; + } + } + storeMiss++; + return null; + + } + + /** + * Method: add + * Description: A StoreIdentifier is added to the ObjectStore, if it + * contains a reference to a @see StorableObject. + */ + public void add(StoreIdentifier sid) { + if (sid != null && sid.hasReference()) { + // find the right StoreContainer for sid + StoreContainer stoc = getStoreContainerForSid(sid); + if (stoc == null) { + // we have to make new StoreContainer + StoreContainerType stocType = sid.getStoreContainerType(); + stoc = new StoreContainer(stocType); + containerMap.put(stocType, stoc); + } + stoc.add(sid); + } + } + + /** + * Method: invalidate(StorableObject sto) + * Description: ObjectStore is notified of change of a @see StorableObject + * sto and invalidates all relevant cache entries. + */ + + public void invalidate(StoreIdentifier sid) { + // propagate invalidation to StoreContainer + if (sid != null) { + StoreContainer stoc = getStoreContainerForSid(sid); + stoc.invalidate(sid); + } + } + + /** + * Method: invalidate(StoreContainerType) + * Description: serves to invalidate a whole StoreContainer + * + * @return + */ + public void invalidate(StoreContainerType stoc_type) { + if (stoc_type != null) { + /** @todo invalidates too much: + * improvement: if instanceof StoreContainerEntity && EntityList + * then invalidate only StoreIdentifier matching the right table + */ + StoreContainer stoc = getStoreContainerForStocType(stoc_type); + if (stoc != null) + stoc.invalidate(); + } + + } + + // internal methods for StoreContainer managment + + /** + * Method: getStoreContainerForSid + * Description: private method to find the right @see StoreContainer for + * the @see StoreIdentifier sid. + * + * @return StoreContainer is null when no Container is found. + */ + private StoreContainer getStoreContainerForSid(StoreIdentifier sid) { + // find apropriate container for a specific sid + if (sid != null) { + StoreContainerType stoc_type = sid.getStoreContainerType(); + return getStoreContainerForStocType(stoc_type); + } + return null; + } + + private StoreContainer getStoreContainerForStocType(StoreContainerType + stoc_type) { + if (stoc_type != null && containerMap.containsKey(stoc_type)) + return (StoreContainer) containerMap.get(stoc_type); + return null; + } + + private boolean has(StoreIdentifier sid) { + StoreContainer stoc = getStoreContainerForSid(sid); + return (stoc != null && stoc.has(sid)) ? true : false; + } + + public String getConfProperty(String name) { + if (name != null) { + String returnValue = ""; + try { + return ostoreConf.getProperty(name); + } + catch (MissingResourceException e) { + logger.error("getConfProperty: " + e.toString()); + } + } + return null; + } + + /** + * Method: toString() + * Description: Displays statistical information about the ObjectStore. + * Further information is gathered from all @see StoreContainer + * + * @return String + */ + public String toString() { + return toHtml(null); + } + + public String toHtml(HttpServletRequest req) { + float hitRatio = 0; + long divisor = storeHit + storeMiss; + if (divisor > 0) + hitRatio = (float) storeHit / (float) divisor; + hitRatio *= 100; + + StringBuffer sb = new StringBuffer("Mir-ObjectStore "); + sb.append( ( (req != null) ? html_version() : version())).append("\n"); + sb.append("ObjectStore overall hits/misses/ratio: ").append(storeHit); + sb.append("/").append(storeMiss).append("/").append(hitRatio); + sb.append("%\nCurrently ").append(containerMap.size()); + sb.append(" StoreContainer in use - listing information:\n"); + + // ask container for information + StoreContainer currentStoc; + for (Iterator it = containerMap.keySet().iterator(); it.hasNext(); ) { + currentStoc = (StoreContainer) containerMap.get(it.next()); + sb.append(currentStoc.toHtml(req)); + } + + return sb.toString(); + } + + /** + * Method: html_version() + * Description: returns ObjectStore version as String for HTML representation + * + * @return String + */ + private String html_version() { + return "" + version() + ""; + } + + /** + * Method: version() + * Description: returns ObjectStore version as String + * + * @return String + */ + private String version() { + return "v_sstart3__1.0"; + } + } \ No newline at end of file diff --git a/source/mir/util/SQLQueryBuilder.java b/source/mir/util/SQLQueryBuilder.java new file mode 100755 index 00000000..f1d0d6bd --- /dev/null +++ b/source/mir/util/SQLQueryBuilder.java @@ -0,0 +1,57 @@ +package mir.util; + +import java.util.*; + +public class SQLQueryBuilder { + private StringBuffer whereClause; + private StringBuffer orderByClause; + + public SQLQueryBuilder(){ + whereClause = new StringBuffer(); + orderByClause = new StringBuffer(); + } + + public void appendDescendingOrder(String anOrder) { + if (orderByClause.length()==0) { + orderByClause.append(anOrder).append(" desc"); + } + else { + orderByClause.append(",").append(anOrder).append(" desc"); + } + } + + public void appendAscendingOrder(String anOrder) { + if (orderByClause.length()==0) { + orderByClause.append(anOrder).append(" asc"); + } + else { + orderByClause=orderByClause.append(",").append(anOrder).append(" asc"); + } + } + + public void appendAndCondition(String aQualifier) { + if (whereClause.length()==0) { + whereClause.append(aQualifier); + } + else { + whereClause.append("(").append(whereClause).append(") and (").append(aQualifier).append(")"); + } + } + + public void appendOrCondition(String aQualifier) { + if (whereClause.length()==0) { + whereClause.append(aQualifier); + } + else { + whereClause.append("(").append(whereClause).append(") or (").append(aQualifier).append(")"); + } + } + + public String getWhereClause() { + return whereClause.toString(); + } + + public String getOrderByClause() { + return orderByClause.toString(); + } +} diff --git a/source/mir/util/XMLReader.java b/source/mir/util/XMLReader.java index 6b53f8e1..8ce6f852 100755 --- a/source/mir/util/XMLReader.java +++ b/source/mir/util/XMLReader.java @@ -219,10 +219,17 @@ public class XMLReader { } } - public void characters(char[] aBuffer, int aStart, int anEnd) throws SAXParseException { - String text = new String(aBuffer, aStart, anEnd).trim(); - if ( text.length() > 0) { - throw new SAXParseException("Text not allowed", null, new XMLReaderExc("Text not allowed")); + public void characters(char[] aBuffer, int aStart, int anEnd) throws SAXException { + try { + String text = new String(aBuffer, aStart, anEnd); + + manager.currentHandler().characters(text); + } + catch (XMLReaderExc e) { + throw new SAXParseException(e.getMessage(), null, e); + } + catch (Exception e) { + throw new SAXException(e); } } } @@ -256,6 +263,8 @@ public class XMLReader { public abstract void endElement(SectionHandler aHandler) throws XMLReaderExc; + public void characters(String aCharacters) throws XMLReaderExc; + public void finishSection() throws XMLReaderExc; } @@ -269,6 +278,12 @@ public class XMLReader { public void finishSection() throws XMLReaderExc { } + + public void characters(String aCharacters) throws XMLReaderExc { + if ( aCharacters.trim().length() > 0) { + throw new XMLReaderExc("Text not allowed"); + } + } } public static class XMLReaderExc extends Exc { diff --git a/source/mircoders/entity/EntityBreaking.java b/source/mircoders/entity/EntityBreaking.java deleted file mode 100755 index cce0b573..00000000 --- a/source/mircoders/entity/EntityBreaking.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.entity; - -/** - * Title: EntityBreaking - * Description: Maps table "breaking" to Java Object - * Copyright: Copyright (c) 2001 - * Company: Indymedia.de - * @author /rk - * @version 1.0 - */ - - -import java.util.Set; - -import mir.entity.Entity; -import mir.storage.StorageObject; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreIdentifier; - - -public class EntityBreaking extends Entity implements StorableObject -{ - public EntityBreaking() { super(); } - public EntityBreaking(StorageObject theStorage) { this(); setStorage(theStorage); } - - - /** - * Method: getStoreIdentifier - * Description: returns unique StoreIdentifer under which the Entity - * is Stored. Based upon primary key and tablename. - * - * @return StoreIdentifier - */ - public StoreIdentifier getStoreIdentifier() { - String id = getId(); - if ( id!=null && theStorageObject!= null ) - return new StoreIdentifier(this, id+"@"+theStorageObject.getTableName()); - return null; - } - - /** - * Method: getNotifyOnReleaseSet() - * Description: returns empty Set, GenericContainer does not implement - * dependencies. - * - * @return null - */ - public Set getNotifyOnReleaseSet() { return null; } - -} \ No newline at end of file diff --git a/source/mircoders/entity/EntityUploadedMedia.java b/source/mircoders/entity/EntityUploadedMedia.java index 26666127..f6895fe8 100755 --- a/source/mircoders/entity/EntityUploadedMedia.java +++ b/source/mircoders/entity/EntityUploadedMedia.java @@ -52,7 +52,7 @@ import freemarker.template.TemplateModelException; * Diese Klasse enth?lt die Daten eines MetaObjekts * * @author mh, mir-coders group - * @version $Id: EntityUploadedMedia.java,v 1.17 2003/01/25 17:50:34 idfx Exp $ + * @version $Id: EntityUploadedMedia.java,v 1.18 2003/02/20 16:05:33 zapata Exp $ */ @@ -100,8 +100,6 @@ public class EntityUploadedMedia extends Entity { } catch (StorageObjectFailure e) { throwStorageObjectFailure(e, "get MediaType failed -- "); - } catch (StorageObjectExc e) { - throwStorageObjectFailure(e, "get MediaType failed -- "); } return ent; } diff --git a/source/mircoders/global/MirGlobal.java b/source/mircoders/global/MirGlobal.java index f66719d5..8bd47117 100755 --- a/source/mircoders/global/MirGlobal.java +++ b/source/mircoders/global/MirGlobal.java @@ -74,10 +74,10 @@ public class MirGlobal { } public static MirPropertiesConfiguration config() { - try { + try { return MirPropertiesConfiguration.instance(); - } catch (PropertiesConfigExc e) { - e.printStackTrace(); + } + catch (PropertiesConfigExc e) { throw new RuntimeException(e.getMessage()); } } @@ -101,7 +101,7 @@ public class MirGlobal { } catch (Throwable t) { result = aDefault; } - + if (result==null) result = aDefault; diff --git a/source/mircoders/localizer/MirAdminInterfaceLocalizer.java b/source/mircoders/localizer/MirAdminInterfaceLocalizer.java index dd8f195b..3cff9956 100755 --- a/source/mircoders/localizer/MirAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/MirAdminInterfaceLocalizer.java @@ -32,10 +32,28 @@ package mircoders.localizer; import java.util.List; +import java.util.Map; import mir.entity.adapter.EntityAdapter; +/** + * + *

Title: Interface to allow for localized changed to the workings of the admin system

+ * @author Zapata + * @version 1.0 + */ + public interface MirAdminInterfaceLocalizer { + /** + * Every time an article gets made inside the admin system, this function is called. It is + * possible to set different initial values for the article here. + * + * @param anArticle The map that can be changed. For example, to set a default author, do + *

+ * anArticle.put("creator", "editorial team"); + */ + public void initializeArticle(Map anArticle); + public List simpleCommentOperations(); public MirSimpleEntityOperation simpleCommentOperationForName(String aName); diff --git a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java index 0336b73a..06c32001 100755 --- a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java @@ -41,6 +41,7 @@ import java.util.Vector; import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.storage.StorageObjectFailure; +import mir.misc.StringUtil; import mir.util.StringRoutines; import mircoders.entity.EntityComment; import mircoders.entity.EntityContent; @@ -71,6 +72,11 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0")); } + public void initializeArticle(Map anArticle) { + anArticle.put("is_published", "0"); + anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); + }; + public List simpleCommentOperations() { return simpleCommentOperations; }; @@ -181,11 +187,11 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz if (logOperation) { StringBuffer comment = new StringBuffer(); - try { + try { comment.append(StringRoutines.interpretAsString(anEntity.getValue("comment"))); - } - catch (Throwable t) { - } + } + catch (Throwable t) { + } if (comment.length()>0 && comment.charAt(comment.length()-1)!='\n') { comment.append('\n'); } diff --git a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java index 92a5a0a6..fcdda5a8 100755 --- a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java @@ -44,6 +44,7 @@ import mir.entity.adapter.EntityAdapterModel; import mir.media.MediaHelper; import mir.media.MirMedia; import mir.util.RewindableIterator; +import mir.log.LoggerWrapper; import mircoders.entity.EntityUploadedMedia; import mircoders.global.MirGlobal; import mircoders.localizer.MirAdminInterfaceLocalizer; @@ -71,11 +72,14 @@ import mircoders.storage.DatabaseVideo; public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { private EntityAdapterModel model; + protected LoggerWrapper logger; public MirBasicDataModelLocalizer() { } public EntityAdapterModel adapterModel() throws MirLocalizerFailure { + logger = new LoggerWrapper("Localizer.Basic"); + if (model==null) model = buildModel(); @@ -106,6 +110,9 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data")); + anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField()); + anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField()); + anEntityAdapterDefinition.addCalculatedField("operations", new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations())); } @@ -251,6 +258,35 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { } } + protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + logger.debug("ContentToParentField.getValue"); + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_content"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "to_content="+anEntityAdapter.get("id"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField { public Object getValue(EntityAdapter anEntityAdapter) { try { diff --git a/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java b/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java index 6a012e89..5beb8b2a 100755 --- a/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java @@ -35,18 +35,21 @@ import mir.generator.FreemarkerGenerator; import mir.generator.Generator; import mir.generator.GeneratorLibraryRepository; import mir.generator.WriterEngine; -import mir.misc.Logfile; +import mir.log.LoggerWrapper; + import mircoders.global.MirGlobal; import mircoders.localizer.MirGeneratorLocalizer; import mircoders.localizer.MirLocalizerExc; import mircoders.localizer.MirLocalizerFailure; public class MirBasicGeneratorLocalizer implements MirGeneratorLocalizer { - protected static Logfile logger = Logfile.getInstance( MirGlobal.getConfigProperty("Home") + "/" + MirGlobal.getConfigProperty("Mir.Localizer.Logfile")); private GeneratorLibraryRepository repository; + protected LoggerWrapper logger; public MirBasicGeneratorLocalizer () { repository = new GeneratorLibraryRepository(); + logger = new LoggerWrapper("Localizer.Basic.Generator"); + buildRepository(repository); } diff --git a/source/mircoders/localizer/basic/MirBasicLocalizer.java b/source/mircoders/localizer/basic/MirBasicLocalizer.java index 83f7ec45..3dfb79a3 100755 --- a/source/mircoders/localizer/basic/MirBasicLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicLocalizer.java @@ -42,7 +42,6 @@ import mircoders.localizer.MirProducerAssistantLocalizer; import mircoders.localizer.MirProducerLocalizer; public class MirBasicLocalizer implements MirLocalizer { -// protected static Logfile logger = Logfile.getInstance( MirGlobal.getConfigProperty("Home") + "/" + MirGlobal.getConfigProperty("Mir.Localizer.Logfile")); public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc { return new MirBasicProducerLocalizer(); diff --git a/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java b/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java index 35b2deb4..5f0655ec 100755 --- a/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java @@ -36,7 +36,7 @@ import java.util.Locale; import javax.servlet.http.HttpServletRequest; -import mir.misc.Logfile; +import mir.log.LoggerWrapper; import mircoders.entity.EntityComment; import mircoders.entity.EntityContent; import mircoders.global.MirGlobal; @@ -46,10 +46,13 @@ import mircoders.localizer.MirOpenPostingLocalizer; public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer { private List afterContentProducerTasks; private List afterCommentProducerTasks; + protected LoggerWrapper logger; + - protected static Logfile logger = Logfile.getInstance( MirGlobal.getConfigProperty("Home") + "/" + MirGlobal.getConfigProperty("Mir.Localizer.Logfile")); public MirBasicOpenPostingLocalizer() { + logger = new LoggerWrapper("Localizer.Basic.OpenPosting"); + try { String contentProducers = MirGlobal.getConfigProperty("Mir.Localizer.OpenPosting.ContentProducers"); String commentProducers = MirGlobal.getConfigProperty("Mir.Localizer.OpenPosting.CommentProducers"); @@ -58,7 +61,7 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer { afterCommentProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(commentProducers); } catch (Throwable t) { - logger.printError("Setting up MirBasicOpenPostingLocalizer failed: " + t.getMessage()); + logger.error("Setting up MirBasicOpenPostingLocalizer failed: " + t.getMessage()); } } diff --git a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java index c227e92c..414eb023 100755 --- a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java @@ -41,7 +41,7 @@ import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; import mir.entity.EntityList; import mir.entity.adapter.EntityAdapter; import mir.entity.adapter.EntityIteratorAdapter; -import mir.misc.Logfile; +import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.util.DateToMapAdapter; import mir.util.GeneratorHTMLFunctions; @@ -56,7 +56,7 @@ import mircoders.storage.DatabaseLanguage; import mircoders.storage.DatabaseTopics; public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer { - protected static Logfile logger = Logfile.getInstance( MirGlobal.getConfigProperty("Home") + "/" + MirGlobal.getConfigProperty("Mir.Localizer.Logfile")); + protected LoggerWrapper logger; public void initializeGenerationValueSet(Map aValueSet) { Iterator i; @@ -64,6 +64,8 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL Map configMap = new HashMap(); Map utilityMap = new HashMap(); + logger = new LoggerWrapper("Localizer.Basic.ProducerAssistant"); + // obsolete: configMap.put("producerDocRoot", MirGlobal.getConfigProperty("Producer.DocRoot")); configMap.put("storageRoot", MirGlobal.getConfigProperty("Producer.StorageRoot")); @@ -100,7 +102,6 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL aValueSet.put("utility", utilityMap); - EntityList topicList=null; EntityList entityList=null; EntityList parentList=null; @@ -115,7 +116,7 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL } catch (Throwable t) { - logger.printError("initializeGenerationValueSet: Exception "+t.getMessage()); + logger.error("initializeGenerationValueSet: Exception "+t.getMessage()); } aValueSet.put("topics", topicList); @@ -139,7 +140,7 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL } } catch (Throwable t) { - logger.printError("initializeGenerationValueSet: Exception while collecting article types "+t.getMessage()); + logger.error("initializeGenerationValueSet: Exception while collecting article types "+t.getMessage()); } aValueSet.put("articletype", articleTypeMap); @@ -154,7 +155,7 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL } } catch (Throwable t) { - logger.printError("initializeGenerationValueSet: Exception while collecting comment statuses"+t.getMessage()); + logger.error("initializeGenerationValueSet: Exception while collecting comment statuses"+t.getMessage()); } aValueSet.put("commentstatus", commentStatusMap); diff --git a/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java b/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java index 96480bbf..0531d063 100755 --- a/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java @@ -41,7 +41,7 @@ import java.util.Vector; import mir.entity.adapter.EntityAdapterModel; import mir.generator.Generator; import mir.generator.WriterEngine; -import mir.misc.Logfile; +import mir.log.LoggerWrapper; import mir.producer.CompositeProducerNode; import mir.producer.ProducerFactory; import mir.producer.reader.DefaultProducerNodeBuilders; @@ -71,10 +71,12 @@ public class MirBasicProducerLocalizer implements MirProducerLocalizer { protected Generator.GeneratorLibrary generatorLibrary; protected WriterEngine writerEngine; - protected static Logfile logger = Logfile.getInstance( MirGlobal.getConfigProperty("Home") + "/" + MirGlobal.getConfigProperty("Mir.Localizer.Logfile")); + protected LoggerWrapper logger; public MirBasicProducerLocalizer() { try { + logger = new LoggerWrapper("Localizer.Basic.Producer"); + String allNewProducers = MirGlobal.getConfigProperty("Mir.Localizer.Producer.AllNewProducers"); allNewProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(allNewProducers); @@ -85,7 +87,7 @@ public class MirBasicProducerLocalizer implements MirProducerLocalizer { nameToFactory = new HashMap(); } catch (Throwable t) { - logger.printError("MirBasicProducerLocalizer(): Exception "+t.getMessage()); + logger.error("MirBasicProducerLocalizer(): Exception "+t.getMessage()); model = new EntityAdapterModel(); } } @@ -99,7 +101,7 @@ public class MirBasicProducerLocalizer implements MirProducerLocalizer { producerFactories = newProducers; fileMonitor = newFileMonitor; - logger.printInfo("MirBasicProducerLocalizer.factories(): successfully setup factories"); + logger.info("MirBasicProducerLocalizer.factories(): successfully setup factories"); nameToFactory.clear(); Iterator i = producerFactories.iterator(); @@ -109,7 +111,7 @@ public class MirBasicProducerLocalizer implements MirProducerLocalizer { } } catch (Throwable t) { - logger.printError("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage()); + logger.error("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index fbe224d7..4b955e54 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -1,494 +1,590 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.io.IOException; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.entity.EntityList; -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.module.ModuleException; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleException; -import mir.storage.StorageObjectFailure; -import mir.util.CachingRewindableIterator; -import mir.util.HTMLRoutines; -import mir.util.JDBCStringRoutines; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleContent; -import mircoders.module.ModuleImages; -import mircoders.module.ModuleSchwerpunkt; -import mircoders.module.ModuleTopics; -import mircoders.search.IndexUtil; -import mircoders.storage.DatabaseArticleType; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToTopics; -import mircoders.storage.DatabaseFeature; -import mircoders.storage.DatabaseImages; -import mircoders.storage.DatabaseLanguage; -import mircoders.storage.DatabaseTopics; - -import org.apache.lucene.index.IndexReader; - -import freemarker.template.SimpleHash; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModelRoot; - -/* - * ServletModuleContent - - * deliver html for the article admin form. - * - * @version $Id: ServletModuleContent.java,v 1.32 2003/01/25 17:50:36 idfx Exp $ - * @author rk, mir-coders - * - */ - -public class ServletModuleContent extends ServletModule -{ - static ModuleTopics themenModule; - static ModuleSchwerpunkt schwerpunktModule; - static ModuleImages imageModule; - - static String templateOpString; - -// Singelton / Kontruktor - - private static ServletModuleContent instance = new ServletModuleContent(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleContent() { - super(); - logger = new LoggerWrapper("ServletModule.Content"); - try { - - templateListString = configuration.getString("ServletModule.Content.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); - - mainModule = new ModuleContent(DatabaseContent.getInstance()); - themenModule = new ModuleTopics(DatabaseTopics.getInstance()); - schwerpunktModule = new ModuleSchwerpunkt(DatabaseFeature.getInstance()); - imageModule = new ModuleImages(DatabaseImages.getInstance()); - } - catch (StorageObjectFailure e) { - logger.error("servletmodulecontent konnte nicht initialisiert werden"); - } - } - -// Methoden - - public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - EntityUsers user = _getUser(req); - String offsetParam = req.getParameter("offset"); - String whereParam = req.getParameter("where"); - String orderParam = req.getParameter("order"); - - int offset =0; - - if (offsetParam != null && !offsetParam.equals("")) - offset = Integer.parseInt(offsetParam); - - if (req.getParameter("next") != null) - offset=Integer.parseInt(req.getParameter("nextoffset")); - else - if (req.getParameter("prev") != null) - offset = Integer.parseInt(req.getParameter("prevoffset")); - - returnArticleList(req, res, whereParam, orderParam, offset); - } - - public void listop(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - EntityUsers user = _getUser(req); - String offsetParam = req.getParameter("offset"); - int offset =0; - - String whereParam = req.getParameter("where"); - - if (whereParam==null) whereParam = "to_article_type='0'"; - -// hier offsetcode bearbeiteb - if (offsetParam != null && !offsetParam.equals("")) - offset = Integer.parseInt(offsetParam); - - if (req.getParameter("next") != null) - offset=Integer.parseInt(req.getParameter("nextoffset")); - else - if (req.getParameter("prev") != null) - offset = Integer.parseInt(req.getParameter("prevoffset")); - - String orderParam = req.getParameter("order"); - - returnArticleList(req, res, whereParam, orderParam, offset); - } - - - public void search(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleException { - try { - EntityUsers user = _getUser(req); - EntityList theList; - String fieldParam = req.getParameter("field"); - String fieldValueParam = req.getParameter("fieldvalue"); - String orderParam = req.getParameter("order"); - - theList = ((ModuleContent)mainModule).getContentByField(fieldParam, fieldValueParam, orderParam, 0, user); - returnArticleList(req, res, "lower("+ fieldParam + ") like lower('%" + JDBCStringRoutines.escapeStringLiteral(fieldValueParam) + "%')", orderParam, 0); - } catch (ModuleException e) { - throw new ServletModuleException(e.toString()); - } - } - - public void add(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleException { - _showObject(null, req, res); - } - - - public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { -//theLog.printDebugInfo(":: content :: trying to insert"); - try { - EntityUsers user = _getUser(req); - HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance()); - - String now = StringUtil.date2webdbDate(new GregorianCalendar()); - withValues.put("date", now); - withValues.put("publish_path", StringUtil.webdbDate2path(now)); - withValues.put("to_publisher", user.getId()); - withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String id = mainModule.add(withValues); - DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic")); - - _showObject(id, req, res); - } - catch (StorageObjectFailure e) { - throw new ServletModuleException(e.toString()); - } - catch (ModuleException e) { - throw new ServletModuleException(e.toString()); - } - } - - public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - EntityUsers user = _getUser(req); - - String idParam = req.getParameter("id"); - if (idParam == null) throw new ServletModuleException("Invalid call: id missing"); - - String confirmParam = req.getParameter("confirm"); - String cancelParam = req.getParameter("cancel"); - - logger.info("where = " + req.getParameter("where")); - - if (confirmParam == null && cancelParam == null) { - - SimpleHash mergeData = new SimpleHash(); - mergeData.put("module", "Content"); - mergeData.put("infoString", "Content: " + idParam); - mergeData.put("id", idParam); - mergeData.put("where", req.getParameter("where")); - mergeData.put("order", req.getParameter("order")); - mergeData.put("offset", req.getParameter("offset")); - deliver(req, res, mergeData, templateConfirmString); - } - else { - if (confirmParam!= null && !confirmParam.equals("")) { - try { - mainModule.deleteById(idParam); - - /** @todo the following two should be implied in - * DatabaseContent */ - - //delete rows in the content_x_topic-table - DatabaseContentToTopics.getInstance().deleteByContentId(idParam); - //delete rows in the comment-table - DatabaseComment.getInstance().deleteByContentId(idParam); - //delete from lucene index, if any - String index = configuration.getString("IndexPath"); - if (IndexReader.indexExists(index)){ - IndexUtil.unindexID(idParam,index); - } - - } catch (ModuleException e) { - throw new ServletModuleException(e.toString()); - } catch (StorageObjectFailure e) { - throw new ServletModuleException(e.toString()); - } catch (IOException e) { - throw new ServletModuleException(e.toString()); - } - list(req,res); - } - else { - // Datensatz anzeigen - _showObject(idParam, req, res); - } - } - } - - public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - String idParam = req.getParameter("id"); - if (idParam == null) throw new ServletModuleException("Invalid call: id not supplied "); - _showObject(idParam, req, res); - } - -// methods for attaching media file - public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - String mediaIdParam = req.getParameter("mid"); - String idParam = req.getParameter("cid"); - if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(idParam); - entContent.attach(mediaIdParam); - } - catch(ModuleException e) { - logger.error("smod content :: attach :: could not get entityContent"); - } - catch(StorageObjectFailure e) { - logger.error("smod content :: attach :: could not get entityContent"); - } - - _showObject(idParam, req, res); - } - - public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - String cidParam = req.getParameter("cid"); - String midParam = req.getParameter("mid"); - if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing"); - if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(cidParam); - entContent.dettach(cidParam,midParam); - } - catch(ModuleException e) { - logger.error("smod content :: dettach :: could not get entityContent"); - } - catch(StorageObjectFailure e) { - logger.error("smod content :: dettach :: could not get entityContent"); - } - - _showObject(cidParam, req, res); - } - - public void newswire(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException - { - String idParam = req.getParameter("id"); - if (idParam == null) throw new ServletModuleException("smod content :: newswire :: id missing"); - try { - EntityContent entContent = (EntityContent)mainModule.getById(idParam); - entContent.newswire(); - } - catch(ModuleException e) { - logger.error("smod content :: newswire :: could not get entityContent"); - } - catch(StorageObjectFailure e) { - logger.error("smod content :: dettach :: could not get entityContent"); - } - - list(req, res); - } - - - public void update(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleException - { - try { - - EntityUsers user = _getUser(req); - if (user==null) logger.debug("user null!"); - String idParam = req.getParameter("id"); - if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing"); - - HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance()); - String[] topic_id = req.getParameterValues("to_topic"); - String content_id = req.getParameter("id"); - - if(user != null) withValues.put("user_id", user.getId()); - withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String id = mainModule.set(withValues); - DatabaseContentToTopics.getInstance().setTopics(req.getParameter("id"),topic_id); - - String whereParam = req.getParameter("where"); - String orderParam = req.getParameter("order"); - - if ((whereParam!=null && !whereParam.equals("")) || (orderParam!=null && !orderParam.equals(""))){ - list(req,res); - } - else - _showObject(idParam, req, res); - } - catch (StorageObjectFailure e) { - throw new ServletModuleException(e.toString()); - } - catch (ModuleException e) { - throw new ServletModuleException(e.toString()); - } - } - -/* - * HelperMethod shows the basic article editing form. - * - * if the "id" parameter is null, it means show an empty form to add a new - * article. -*/ - private void _showObject(String id, HttpServletRequest req, HttpServletResponse res) - throws ServletModuleException { - - SimpleHash extraInfo = new SimpleHash(); - try { - TemplateModelRoot entContent; - - if (id != null) { - entContent = (TemplateModelRoot)mainModule.getById(id); - } - else { - SimpleHash withValues = new SimpleHash(); - withValues.put("new", "1"); - withValues.put("is_published", "0"); - String now = StringUtil.date2webdbDate(new GregorianCalendar()); - withValues.put("date", new SimpleScalar(now)); - EntityUsers user = _getUser(req); - withValues.put("login_user", user); - entContent = withValues; - } - - extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList()); - extraInfo.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData()); - extraInfo.put("languagePopupData", DatabaseLanguage.getInstance().getPopupData()); - - // code to be able to return to the list: - String offsetParam, whereParam, orderParam; - if ((offsetParam = req.getParameter("offset"))!=null) extraInfo.put("offset", offsetParam); - if ((whereParam = req.getParameter("where"))!=null) extraInfo.put("where", whereParam); - if ((orderParam = req.getParameter("order"))!=null) extraInfo.put("order", orderParam); - - extraInfo.put("login_user", _getUser(req)); - deliver(req, res, entContent, extraInfo, templateObjektString); - } - catch (Exception e) { - throw new ServletModuleException(e.toString()); - } - } - - public void returnArticleList(HttpServletRequest aRequest, HttpServletResponse aResponse, - String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleException { - // ML: experiment in using the producer's generation system instead of the - // old one... - - EntityAdapterModel model; - int nrArticlesPerPage = 20; - int count; - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - model = MirGlobal.localizer().dataModel().adapterModel(); - - Object contentList = - new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, - MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset) - ); - - responseData.put("nexturl", null); - responseData.put("prevurl", null); - - count=mainModule.getSize(aWhereClause); - - if (count>=anOffset+nrArticlesPerPage) { - responseData.put("nexturl" , - "module=Content&do=list&where=" + HTMLRoutines.encodeURL(aWhereClause) + - "&order=" + HTMLRoutines.encodeURL(anOrderByClause) + - "&offset=" + (anOffset + nrArticlesPerPage)); - } - if (anOffset>0) { - responseData.put("prevurl" , - "module=Content&do=list&where=" + HTMLRoutines.encodeURL(aWhereClause) + - "&order=" + HTMLRoutines.encodeURL(anOrderByClause) + - "&offset=" + Math.max(anOffset - nrArticlesPerPage, 0)); - } - - responseData.put("articles", contentList); - - responseData.put("thisurl" , - "module=Content&do=list&where=" + HTMLRoutines.encodeURL(aWhereClause) + - "&order=" + HTMLRoutines.encodeURL(anOrderByClause) + - "&offset=" + anOffset); - - responseData.put("from" , Integer.toString(anOffset+1)); - responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count))); - responseData.put("offset" , Integer.toString(anOffset)); - responseData.put("order", anOrderByClause); - responseData.put("where" , aWhereClause); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "contentlist.template"); - } - catch (Throwable e) { - throw new ServletModuleException(e.toString()); - } - } - - private EntityUsers _getUser(HttpServletRequest req) - { - HttpSession session=req.getSession(false); - return (EntityUsers)session.getAttribute("login.uid"); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.io.PrintWriter; +import java.io.IOException; +import java.util.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.entity.EntityList; +import mir.entity.adapter.EntityAdapter; +import mir.entity.adapter.EntityAdapterModel; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.module.ModuleException; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleException; +import mir.storage.StorageObjectFailure; +import mir.util.CachingRewindableIterator; +import mir.util.HTMLRoutines; +import mir.util.JDBCStringRoutines; +import mir.util.HTTPRequestParser; +import mir.util.URLBuilder; +import mir.util.SQLQueryBuilder; +import mir.log.*; + +import mircoders.entity.EntityContent; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleContent; +import mircoders.module.ModuleImages; +import mircoders.module.ModuleSchwerpunkt; +import mircoders.module.ModuleTopics; +import mircoders.search.IndexUtil; +import mircoders.storage.DatabaseArticleType; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseContentToTopics; +import mircoders.storage.DatabaseFeature; +import mircoders.storage.DatabaseImages; +import mircoders.storage.DatabaseLanguage; +import mircoders.storage.DatabaseTopics; + +import org.apache.lucene.index.IndexReader; + +import freemarker.template.SimpleHash; +import freemarker.template.SimpleScalar; +import freemarker.template.TemplateModelRoot; + +/* + * ServletModuleContent - + * deliver html for the article admin form. + * + * @version $Id: ServletModuleContent.java,v 1.33 2003/02/20 16:05:34 zapata Exp $ + * @author rk, mir-coders + * + */ + +public class ServletModuleContent extends ServletModule +{ + private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");; + private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate"); + + private static ServletModuleContent instance = new ServletModuleContent(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleContent() { + super(); + logger = new LoggerWrapper("ServletModule.Content"); + try { + + templateListString = configuration.getString("ServletModule.Content.ListTemplate"); + templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); + templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); + + mainModule = new ModuleContent(DatabaseContent.getInstance()); + } + catch (StorageObjectFailure e) { + logger.error("servletmodulecontent konnte nicht initialisiert werden"); + } + } + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String where = requestParser.getParameter("where"); + String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); + int offset = requestParser.getIntegerWithDefault("offset", 0); + String selectArticleUrl = requestParser.getParameter("selectarticleurl"); + + returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl); + } + + public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); + String searchField = requestParser.getParameterWithDefault("searchfield", ""); + String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim(); + String searchOrder = requestParser.getParameterWithDefault("searchorder", ""); + String searchispublished = requestParser.getParameterWithDefault("searchispublished", ""); + String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", ""); + String selectArticleUrl = requestParser.getParameter("selectarticleurl"); + + if (searchValue.length()>0) { + if (searchField.equals("contents")) + queryBuilder.appendAndCondition( + "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+ + " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"); + else + queryBuilder.appendAndCondition( + "lower("+ searchField + ") like " + + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'"); + } + + if (searchispublished.length()>0) { + if (searchispublished.equals("0")) + queryBuilder.appendAndCondition("is_published='f'"); + else + queryBuilder.appendAndCondition("is_published='t'"); + } + + if (searchArticleType.length()>0) { + queryBuilder.appendAndCondition("to_article_type="+searchArticleType); + } + + if (searchOrder.length()>0) { + if (searchOrder.equals("datedesc")) + queryBuilder.appendAscendingOrder("webdb_create"); + else if (searchOrder.equals("dateasc")) + queryBuilder.appendDescendingOrder("webdb_create"); + else if (searchOrder.equals("title")) + queryBuilder.appendDescendingOrder("title"); + else if (searchOrder.equals("creator")) + queryBuilder.appendDescendingOrder("creator"); + } + + returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); + } + catch (Throwable e) { + throw new ServletModuleException(e.toString()); + } + } + + public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException { + _showObject(null, req, res); + } + + + public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException + { +//theLog.printDebugInfo(":: content :: trying to insert"); + try { + EntityUsers user = _getUser(req); + HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance()); + + String now = StringUtil.date2webdbDate(new GregorianCalendar()); + withValues.put("date", now); + withValues.put("publish_path", StringUtil.webdbDate2path(now)); + withValues.put("to_publisher", user.getId()); + withValues.put("is_produced", "0"); + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String id = mainModule.add(withValues); + DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic")); + + _showObject(id, req, res); + } + catch (StorageObjectFailure e) { + throw new ServletModuleException(e.toString()); + } + catch (ModuleException e) { + throw new ServletModuleException(e.toString()); + } + } + + public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException + { + EntityUsers user = _getUser(req); + + String idParam = req.getParameter("id"); + if (idParam == null) throw new ServletModuleException("Invalid call: id missing"); + + String confirmParam = req.getParameter("confirm"); + String cancelParam = req.getParameter("cancel"); + + logger.info("where = " + req.getParameter("where")); + + if (confirmParam == null && cancelParam == null) { + + SimpleHash mergeData = new SimpleHash(); + mergeData.put("module", "Content"); + mergeData.put("infoString", "Content: " + idParam); + mergeData.put("id", idParam); + mergeData.put("where", req.getParameter("where")); + mergeData.put("order", req.getParameter("order")); + mergeData.put("offset", req.getParameter("offset")); + deliver(req, res, mergeData, templateConfirmString); + } + else { + if (confirmParam!= null && !confirmParam.equals("")) { + try { + mainModule.deleteById(idParam); + + /** @todo the following two should be implied in + * DatabaseContent */ + + //delete rows in the content_x_topic-table + DatabaseContentToTopics.getInstance().deleteByContentId(idParam); + //delete rows in the comment-table + DatabaseComment.getInstance().deleteByContentId(idParam); + //delete from lucene index, if any + String index = configuration.getString("IndexPath"); + if (IndexReader.indexExists(index)){ + IndexUtil.unindexID(idParam,index); + } + + } + catch (ModuleException e) { + throw new ServletModuleException(e.toString()); + } + catch (StorageObjectFailure e) { + throw new ServletModuleException(e.toString()); + } + catch (IOException e) { + throw new ServletModuleException(e.toString()); + } + list(req,res); + } + else { + // Datensatz anzeigen + _showObject(idParam, req, res); + } + } + } + + public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException + { + String idParam = req.getParameter("id"); + if (idParam == null) + throw new ServletModuleException("Invalid call: id not supplied "); + _showObject(idParam, req, res); + } + +// methods for attaching media file + public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException + { + String mediaIdParam = req.getParameter("mid"); + String idParam = req.getParameter("cid"); + if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(idParam); + entContent.attach(mediaIdParam); + } + catch(ModuleException e) { + logger.error("smod content :: attach :: could not get entityContent"); + } + catch(StorageObjectFailure e) { + logger.error("smod content :: attach :: could not get entityContent"); + } + + _showObject(idParam, req, res); + } + + public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException + { + String cidParam = req.getParameter("cid"); + String midParam = req.getParameter("mid"); + if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing"); + if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(cidParam); + entContent.dettach(cidParam,midParam); + } + catch(ModuleException e) { + logger.error("smod content :: dettach :: could not get entityContent"); + } + catch(StorageObjectFailure e) { + logger.error("smod content :: dettach :: could not get entityContent"); + } + + _showObject(cidParam, req, res); + } + + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleException + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String returnUrl = requestParser.getParameter("returnurl"); + + String idParam = aRequest.getParameter("id"); + if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing"); + + HashMap withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); + String[] topic_id = aRequest.getParameterValues("to_topic"); + String content_id = aRequest.getParameter("id"); + + withValues.put("is_produced", "0"); + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String id = mainModule.set(withValues); + DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id); + + String whereParam = aRequest.getParameter("where"); + String orderParam = aRequest.getParameter("order"); + + if (returnUrl!=null){ + redirect(aResponse, returnUrl); + } + else + _showObject(idParam, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleException(e.toString()); + } + } + +/* + * HelperMethod shows the basic article editing form. + * + * if the "id" parameter is null, it means show an empty form to add a new + * article. +*/ + private void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleException { + + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); + EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); + Map article; + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "edit"); + urlBuilder.setValue("id", id); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + if (id!=null) { + responseData.put("new", Boolean.FALSE); + article = model.makeEntityAdapter("content", mainModule.getById(id)); + } + else { + List fields = DatabaseContent.getInstance().getFields(); + responseData.put("new", Boolean.TRUE); + article = new HashMap(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + article.put(i.next(), null); + } + + article.put("to_topics", null); + + MirGlobal.localizer().adminInterface().initializeArticle(article); + } + responseData.put("article", article); + + Object languages = + new CachingRewindableIterator( + new EntityIteratorAdapter( "", "id", 30, + MirGlobal.localizer().dataModel().adapterModel(), "language")); + Object topics = + new CachingRewindableIterator( + new EntityIteratorAdapter("", "id", 30, + MirGlobal.localizer().dataModel().adapterModel(), "topic")); + Object articleTypes = + new CachingRewindableIterator( + new EntityIteratorAdapter( "", "id", 30, + MirGlobal.localizer().dataModel().adapterModel(), "articleType")); + + responseData.put("articleTypes", articleTypes); + responseData.put("languages", languages); + responseData.put("topics", topics); + responseData.put("returnurl", requestParser.getParameter("returnurl")); + responseData.put("thisurl", urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); + } + catch (Exception e) { + throw new ServletModuleException(e.toString()); + } + } + + public void returnArticleList( + HttpServletRequest aRequest, + HttpServletResponse aResponse, + String aWhereClause, + String anOrderByClause, + int anOffset, + String aSelectArticleUrl) throws ServletModuleException { + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + EntityAdapterModel model; + int nrArticlesPerPage = 20; + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); + model = MirGlobal.localizer().dataModel().adapterModel(); + + Object articleList = + new CachingRewindableIterator( + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, + MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset) + ); + + responseData.put("nexturl", null); + responseData.put("prevurl", null); + + count=mainModule.getSize(aWhereClause); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "list"); + urlBuilder.setValue("where", aWhereClause); + urlBuilder.setValue("order", anOrderByClause); + + + urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); + urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue")); + urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); + urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder")); + urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype")); + urlBuilder.setValue("selectarticleurl", aSelectArticleUrl); + + responseData.put("searchfield", requestParser.getParameter("searchfield")); + responseData.put("searchvalue", requestParser.getParameter("searchvalue")); + responseData.put("searchispublished", requestParser.getParameter("searchispublished")); + responseData.put("searchorder", requestParser.getParameter("searchorder")); + responseData.put("searcharticletype", requestParser.getParameter("searcharticletype")); + responseData.put("selectarticleurl", aSelectArticleUrl); + + urlBuilder.setValue("offset", anOffset); + responseData.put("offset" , new Integer(anOffset).toString()); + responseData.put("thisurl" , urlBuilder.getQuery()); + + if (count>=anOffset+nrArticlesPerPage) { + urlBuilder.setValue("offset", anOffset + nrArticlesPerPage); + responseData.put("nexturl" , urlBuilder.getQuery()); + } + + if (anOffset>0) { + urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0)); + responseData.put("prevurl" , urlBuilder.getQuery()); + } + + responseData.put("articles", articleList); + + responseData.put("from" , Integer.toString(anOffset+1)); + responseData.put("count", Integer.toString(count)); + responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count))); + responseData.put("offset" , Integer.toString(anOffset)); + responseData.put("order", anOrderByClause); + responseData.put("where" , aWhereClause); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); + } + catch (Throwable e) { + throw new ServletModuleException(e.toString()); + } + } + + public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "setparent"); + urlBuilder.setValue("childid", requestParser.getParameter("id")); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery()); + } + catch (Throwable e) { + throw new ServletModuleException(e.getMessage()); + } + } + + public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("article_id"); + + if (articleId == null) + throw new ServletModuleException("ServletModuleContent.listchildren: article_id not set!"); + + returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null); + } + catch (Throwable e) { + throw new ServletModuleException(e.getMessage()); + } + } + + public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = aRequest.getParameter("childid"); + String parentId = aRequest.getParameter("id"); + String returnUrl = aRequest.getParameter("returnurl"); + + try { + EntityContent article = (EntityContent) mainModule.getById(articleId); + article.setValueForProperty("to_content", parentId); + article.setProduced(false); + article.update(); + } + catch(Throwable e) { + logger.error("ServletModuleContent.setparent: " + e.getMessage()); + throw new ServletModuleException("ServletModuleContent.setparent: " + e.getMessage()); + } + + redirect(aResponse, returnUrl); + } + + public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("id"); + String returnUrl = requestParser.getParameter("returnurl"); + + try { + EntityContent article = (EntityContent) mainModule.getById(articleId); + article.setValueForProperty("to_content", ""); + article.setProduced(false); + article.update(); + } + catch(Throwable e) { + e.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE)); + logger.error("ServletModuleContent.clearparent: " + e.getMessage()); + + throw new ServletModuleException("ServletModuleContent.clearparent: " + e.getMessage()); + } + + redirect(aResponse, returnUrl); + } + + private EntityUsers _getUser(HttpServletRequest req) + { + HttpSession session=req.getSession(false); + + return (EntityUsers)session.getAttribute("login.uid"); + } +} diff --git a/source/mircoders/storage/DatabaseArticleType.java b/source/mircoders/storage/DatabaseArticleType.java index 832df27f..d3d29eb0 100755 --- a/source/mircoders/storage/DatabaseArticleType.java +++ b/source/mircoders/storage/DatabaseArticleType.java @@ -40,6 +40,7 @@ package mircoders.storage; * @version 1.0 */ +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; @@ -65,6 +66,7 @@ public class DatabaseArticleType extends Database implements StorageObject{ private DatabaseArticleType() throws StorageObjectFailure { super(); + logger = new LoggerWrapper("Database.ArticleType"); this.hasTimestamp = false; this.theTable = "article_type"; } diff --git a/source/mircoders/storage/DatabaseAudio.java b/source/mircoders/storage/DatabaseAudio.java index a09126a4..6d698b0a 100755 --- a/source/mircoders/storage/DatabaseAudio.java +++ b/source/mircoders/storage/DatabaseAudio.java @@ -1,107 +1,94 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseAudio extends Database implements StorageObject{ - - private static DatabaseAudio instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseAudio getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseAudio(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseAudio() throws StorageObjectFailure - { - super(); - this.hasTimestamp = true; - this.theTable="audio"; - this.theCoreTable="media"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityAudio"); - } - catch (Exception e) { throw new StorageObjectFailure(e); } - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title",true); - } - - public void update(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - - super.update(theEntity); - } - - - public String insert(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; + +import mir.log.LoggerWrapper; +import mir.entity.Entity; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +public class DatabaseAudio extends Database implements StorageObject{ + + private static DatabaseAudio instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseAudio getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseAudio(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseAudio() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Audio"); + + hasTimestamp = true; + theTable = "audio"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityAudio.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + +} diff --git a/source/mircoders/storage/DatabaseBreaking.java b/source/mircoders/storage/DatabaseBreaking.java index 83184ba7..f926fd32 100755 --- a/source/mircoders/storage/DatabaseBreaking.java +++ b/source/mircoders/storage/DatabaseBreaking.java @@ -31,6 +31,7 @@ package mircoders.storage; +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; @@ -60,7 +61,7 @@ public class DatabaseBreaking extends Database implements StorageObject{ private DatabaseBreaking() throws StorageObjectFailure { super(); - //this.cache = new DatabaseCache(4); + logger = new LoggerWrapper("Database.Breaking"); this.theTable="breaking"; } diff --git a/source/mircoders/storage/DatabaseComment.java b/source/mircoders/storage/DatabaseComment.java index 54fa0681..ee371f15 100755 --- a/source/mircoders/storage/DatabaseComment.java +++ b/source/mircoders/storage/DatabaseComment.java @@ -1,104 +1,109 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * This class implements the access to the comment-table for the - * media table. - * - * - */ - -public class DatabaseComment extends Database implements StorageObject{ - - private static DatabaseComment instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseComment getInstance() - throws StorageObjectFailure { - if (instance == null) { - instance = new DatabaseComment(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseComment() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - ////this.cache = new HashMap(); - this.theTable="comment"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityComment"); - } - catch (Exception e) { throw new StorageObjectFailure(e); } - } - - public SimpleList getPopupData() - throws StorageObjectFailure { return getPopupData("title",true); } - - public boolean deleteByContentId(String id) - throws StorageObjectFailure { - Statement stmt=null; - Connection con=null; - String sql; - int res = 0; - - /** @todo comments and topics should be deleted */ - sql = "delete from "+ theTable + " where to_media="+id; - //theLog.printInfo("DELETE "+ sql); - - try { - con=getPooledCon(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); - } catch (SQLException sqe) { - new StorageObjectFailure(sqe); - return false; - } finally { - freeConnection(con,stmt); - } - return true; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * This class implements the access to the comment-table for the + * media table. + * + * + */ + +public class DatabaseComment extends Database implements StorageObject{ + + private static DatabaseComment instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseComment getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseComment(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseComment() throws StorageObjectFailure { + super(); + hasTimestamp = false; + theTable = "comment"; + logger = new LoggerWrapper("Database.Comment"); + + try { + this.theEntityClass = Class.forName("mircoders.entity.EntityComment"); + } + catch (Exception e) { + throw new StorageObjectFailure(e); + } + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public boolean deleteByContentId(String id) throws StorageObjectFailure { + Statement stmt = null; + Connection con = null; + String sql; + int res = 0; + + /** @todo comments and topics should be deleted */ + sql = "delete from " + theTable + " where to_media=" + id; + logger.info("DELETE "+ sql); + + try { + con = getPooledCon(); + stmt = con.createStatement(); + res = stmt.executeUpdate(sql); + } + catch (SQLException sqe) { + new StorageObjectFailure(sqe); + return false; + } + finally { + freeConnection(con, stmt); + } + return true; + } +} diff --git a/source/mircoders/storage/DatabaseCommentStatus.java b/source/mircoders/storage/DatabaseCommentStatus.java index 3fee965f..83ae0cc8 100755 --- a/source/mircoders/storage/DatabaseCommentStatus.java +++ b/source/mircoders/storage/DatabaseCommentStatus.java @@ -40,6 +40,7 @@ package mircoders.storage; * @version 1.0 */ +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; @@ -65,8 +66,9 @@ public class DatabaseCommentStatus extends Database implements StorageObject{ private DatabaseCommentStatus() throws StorageObjectFailure { super(); - this.hasTimestamp = false; - this.theTable = "comment_status"; + hasTimestamp = false; + theTable = "comment_status"; + logger = new LoggerWrapper("Database.CommentStatus"); } public SimpleList getPopupData() throws StorageObjectFailure { diff --git a/source/mircoders/storage/DatabaseContent.java b/source/mircoders/storage/DatabaseContent.java index e0fc844d..fc5116aa 100755 --- a/source/mircoders/storage/DatabaseContent.java +++ b/source/mircoders/storage/DatabaseContent.java @@ -34,6 +34,7 @@ package mircoders.storage; import java.sql.Connection; import java.sql.Statement; +import mir.log.LoggerWrapper; import mir.entity.EntityList; import mir.entity.EntityRelation; import mir.storage.Database; @@ -68,17 +69,18 @@ public class DatabaseContent extends Database implements StorageObject { return instance; } - private DatabaseContent() - throws StorageObjectFailure { + private DatabaseContent() throws StorageObjectFailure { super(); - this.theTable="content"; - this.theCoreTable="media"; - - relationComments = new EntityRelation("id", "to_media", DatabaseComment.getInstance(), EntityRelation.TO_MANY); - relationFeature = new EntityRelation("id", "to_feature", DatabaseFeature.getInstance(), EntityRelation.TO_ONE); - try { this.theEntityClass = Class.forName("mircoders.entity.EntityContent"); } - catch (Exception e) { throw new StorageObjectFailure(e); } + theTable="content"; + theCoreTable="media"; + logger = new LoggerWrapper("Database.Content"); + + relationComments = + new EntityRelation("id", "to_media", DatabaseComment.getInstance(), EntityRelation.TO_MANY); + relationFeature = + new EntityRelation("id", "to_feature", DatabaseFeature.getInstance(), EntityRelation.TO_ONE); + theEntityClass = mircoders.entity.EntityContent.class; } // methods @@ -91,13 +93,13 @@ public class DatabaseContent extends Database implements StorageObject { { Connection con=null;Statement stmt=null; String sql = "update content set is_produced='0' where " + where; - theLog.printDebugInfo("set unproduced: "+where); + logger.debug("set unproduced: "+where); try { con = getPooledCon(); // should be a preparedStatement because is faster stmt = con.createStatement(); executeUpdate(stmt,sql); - theLog.printDebugInfo("set unproduced: "+where); + logger.debug("set unproduced: "+where); } catch (Exception e) {_throwStorageObjectException(e, "-- set unproduced failed");} finally { freeConnection(con,stmt);} diff --git a/source/mircoders/storage/DatabaseContentToMedia.java b/source/mircoders/storage/DatabaseContentToMedia.java index 1445f155..bcb8cedf 100755 --- a/source/mircoders/storage/DatabaseContentToMedia.java +++ b/source/mircoders/storage/DatabaseContentToMedia.java @@ -1,521 +1,566 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - -import mir.entity.EntityList; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUploadedMedia; - -/** - * implements abstract DB connection to the content_x_media SQL table - * - * @author RK, mir-coders group - * @version $Id: DatabaseContentToMedia.java,v 1.12 2003/01/25 17:50:36 idfx Exp $ - * - */ - -public class DatabaseContentToMedia extends Database implements StorageObject{ - - private static DatabaseContentToMedia instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseContentToMedia getInstance() - throws StorageObjectFailure { - if (instance == null) { - instance = new DatabaseContentToMedia(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseContentToMedia() - throws StorageObjectFailure { - - super(); - this.hasTimestamp = false; - this.theTable="content_x_media"; - try { this.theEntityClass = Class.forName("mir.entity.GenericEntity"); } - catch (Exception e) { throw new StorageObjectFailure(e); } - } - - /** - * get all the media-files belonging to a content entity - * - */ - public EntityList getMedia(EntityContent content) - throws StorageObjectFailure { - EntityList returnList=null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect,"id",-1); - } catch (Exception e) { - theLog.printDebugInfo("-- get media failed " + e.toString()); - throw new StorageObjectFailure("-- get media failed ", e); - } - } - return returnList; - } - - public boolean hasMedia(EntityContent content) - throws StorageObjectFailure, StorageObjectExc { - String wc = "content_id="+content.getId(); - if( content != null) { - try { - if(selectByWhereClause(wc,-1).size() == 0) - return false; - else - return true; - } catch (Exception e) { - theLog.printError("-- hasMedia failed " + e.toString()); - throw new StorageObjectFailure("-- hasMedia failed ",e); - } - } else { - theLog.printError("-- hasMedia failed: content is NULL"); - throw new StorageObjectExc("-- hasMedia failed: content is NULL"); - } - } - - - - - /** - * get all the audio belonging to a content entity - * - */ - public EntityList getAudio(EntityContent content) - throws StorageObjectFailure { - EntityList returnList=null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseAudio.getInstance().selectByWhereClause(subselect,"id",-1); - } catch (Exception e) { - theLog.printDebugInfo("-- get audio failed " + e.toString()); - throw new StorageObjectFailure("-- get audio failed ",e); - } - } - return returnList; - } - - /** - * get all the video belonging to a content entity - * - */ - public EntityList getVideo(EntityContent content) - throws StorageObjectFailure { - EntityList returnList=null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseVideo.getInstance().selectByWhereClause(subselect,"id",-1); - } catch (Exception e) { - theLog.printDebugInfo("-- get video failed " + e.toString()); - throw new StorageObjectFailure("-- get video failed ",e); - } - } - return returnList; - } - - /** - * get all the images belonging to a content entity - * - */ - public EntityList getImages(EntityContent content) - throws StorageObjectFailure { - EntityList returnList=null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseImages.getInstance().selectByWhereClause(subselect,"id",-1); - } catch (Exception e) { - theLog.printDebugInfo("-- get images failed " + e.toString()); - throw new StorageObjectFailure("-- get images failed ",e); - } - } - return returnList; - } - - - /** - * get all the uploaded/other Media belonging to a content entity - * - */ - public EntityList getOther(EntityContent content) - throws StorageObjectFailure - { - /** @todo this should only fetch published media / rk */ - - EntityList returnList=null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id+")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseOther.getInstance().selectByWhereClause(subselect, - "id"); - } catch (Exception e) { - e.printStackTrace(); - theLog.printDebugInfo("-- get Other failed " + e.toString()); - throw new StorageObjectFailure("-- get Other failed ",e); - } - } - return returnList; - } - - /** - * get all the uploaded/other Media belonging to a content entity - * - */ - public EntityList getUploadedMedia(EntityContent content) - throws StorageObjectFailure - { - /** @todo this should only fetch published media / rk */ - - EntityList returnList=null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id+")"; - - try { - returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause(subselect, - "id"); - } catch (Exception e) { - e.printStackTrace(); - theLog.printDebugInfo("-- get uploadedMedia failed " + e.toString()); - throw new StorageObjectFailure("-- get uploadedMedia failed ", e); - } - } - return returnList; - } - - - public void setMedia(String contentId, String[] mediaId) - throws StorageObjectFailure { - if (contentId == null){ - return; - } - if (mediaId==null || mediaId[0]==null) { - return; - } - //first delete all row with content_id=contentId - String sql = "delete from "+ theTable +" where content_id=" + contentId; - - Connection con=null;Statement stmt=null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,sql); - } catch (Exception e) { - theLog.printDebugInfo("-- set media failed -- delete"); - throw new StorageObjectFailure("-- set media failed -- delete",e); - } finally { - freeConnection(con,stmt); - } - - //now insert - //first delete all row with content_id=contentId - for (int i=0;iimplements abstract DB connection to the content_x_media SQL table + * + * @author RK, mir-coders group + * @version $Id: DatabaseContentToMedia.java,v 1.13 2003/02/20 16:05:35 zapata Exp $ + * + */ + +public class DatabaseContentToMedia extends Database implements StorageObject{ + + private static DatabaseContentToMedia instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseContentToMedia getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseContentToMedia(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseContentToMedia() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.ContentToMedia"); + + hasTimestamp = false; + theTable = "content_x_media"; + + theEntityClass = mir.entity.GenericEntity.class; + } + + /** + * get all the media-files belonging to a content entity + * + */ + public EntityList getMedia(EntityContent content) throws StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Throwable e) { + logger.debug("-- get media failed " + e.toString()); + throw new StorageObjectFailure("-- get media failed ", e); + } + } + return returnList; + } + + public boolean hasMedia(EntityContent content) throws StorageObjectFailure, + StorageObjectExc { + if (content != null) { + try { + if (selectByWhereClause("content_id=" + content.getId(), -1).size() == + 0) + return false; + else + return true; + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.hasMedia: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.hasMedia: " + + e.toString(), e); + } + } + else { + logger.error("DatabaseContentToMedia.hasMedia: content == null"); + throw new StorageObjectExc( + "DatabaseContentToMedia.hasMedia: content == null"); + } + } + + /** + * get all the audio belonging to a content entity + * + */ + public EntityList getAudio(EntityContent content) throws StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseAudio.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getAudio: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getAudio: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the video belonging to a content entity + * + */ + public EntityList getVideo(EntityContent content) throws StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseVideo.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getVideo: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getVideo: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the images belonging to a content entity + * + */ + public EntityList getImages(EntityContent content) throws + StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseImages.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getImages: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getImages: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the uploaded/other Media belonging to a content entity + * + */ + public EntityList getOther(EntityContent content) throws StorageObjectFailure { + /** @todo this should only fetch published media / rk */ + + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseOther.getInstance().selectByWhereClause(subselect, + "id"); + } + catch (Exception e) { + e.printStackTrace(); + logger.error("DatabaseContentToMedia.getOther: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getOther: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the uploaded/other Media belonging to a content entity + * + */ + public EntityList getUploadedMedia(EntityContent content) throws + StorageObjectFailure { + /** @todo this should only fetch published media / rk */ + + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause( + subselect, + "id"); + } + catch (Exception e) { + e.printStackTrace(); + logger.error("DatabaseContentToMedia.getUploadedMedia: " + e.toString()); + throw new StorageObjectFailure( + "DatabaseContentToMedia.getUploadedMedia: " + e.toString(), e); + } + } + return returnList; + } + + public void setMedia(String contentId, String[] mediaId) throws + StorageObjectFailure { + if (contentId == null) { + return; + } + if (mediaId == null || mediaId[0] == null) { + return; + } + //first delete all row with content_id=contentId + String sql = "delete from " + theTable + " where content_id=" + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt, sql); + } + catch (Exception e) { + logger.error("-- set media failed -- delete"); + throw new StorageObjectFailure("-- set media failed -- delete", e); + } + finally { + freeConnection(con, stmt); + } + + //now insert + //first delete all row with content_id=contentId + for (int i = 0; i < mediaId.length; i++) { + sql = "insert into " + theTable + " (content_id,media_id) values (" + + contentId + "," + mediaId[i] + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- set topics failed -- insert"); + throw new StorageObjectFailure("-- set topics failed -- insert ", e); + } + finally { + freeConnection(con, stmt); + } + } + } + + public void addMedia(String contentId, String mediaId) throws + StorageObjectFailure { + if (contentId == null && mediaId == null) { + return; + } + + Connection con = null; + Statement stmt = null; + //now insert + + String sql = "insert into " + theTable + " (content_id,media_id) values (" + + contentId + "," + mediaId + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- add media failed -- insert"); + throw new StorageObjectFailure("-- add media failed -- insert ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void setMedia(String contentId, String mediaId) throws + StorageObjectFailure { + if (contentId == null && mediaId == null) { + return; + } + //first delete all row with content_id=contentId + String sql = "delete from " + theTable + " where content_id=" + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- set media failed -- delete"); + throw new StorageObjectFailure("-- set media failed -- delete ", e); + } + finally { + freeConnection(con, stmt); + } + + //now insert + //first delete all row with content_id=contentId + + sql = "insert into " + theTable + " (content_id,media_id) values (" + + contentId + "," + mediaId + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- set media failed -- insert"); + throw new StorageObjectFailure("-- set media failed -- insert ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void deleteByContentId(String contentId) throws StorageObjectFailure { + if (contentId == null) { + //theLog.printDebugInfo("-- delete topics failed -- no content id"); + return; + } + //delete all row with content_id=contentId + String sql = "delete from " + theTable + " where content_id=" + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- delete by contentId failed "); + throw new StorageObjectFailure( + "-- delete by content id failed -- delete ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void deleteByMediaId(String mediaId) throws StorageObjectFailure { + if (mediaId == null) { + //theLog.printDebugInfo("-- delete topics failed -- no topic id"); + return; + } + //delete all row with content_id=contentId + String sql = "delete from " + theTable + " where media_id=" + mediaId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + logger.debug("-- delete media success "); + } + catch (Exception e) { + logger.error("-- delete media failed "); + throw new StorageObjectFailure("-- delete by media id failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void delete(String contentId, String mediaId) throws + StorageObjectFailure { + if (mediaId == null || contentId == null) { + logger.debug("-- delete media failed -- missing parameter"); + return; + } + //delete all row with content_id=contentId and media_id=mediaId + String sql = "delete from " + theTable + " where media_id=" + mediaId + + " and content_id= " + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + logger.debug("-- delete content_x_media success "); + } + catch (Exception e) { + logger.error("-- delete content_x_media failed "); + throw new StorageObjectFailure("-- delete content_x_media failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public EntityList getContent(EntityUploadedMedia media) throws + StorageObjectFailure { + EntityList returnList = null; + if (media != null) { + String id = media.getId(); + String select = "select content_id from " + theTable + " where media_id=" + + id; + + // execute select statement + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt, select); + if (rs != null) { + String mediaSelect = "id IN ("; + boolean first = true; + while (rs.next()) { + if (first == false) + mediaSelect += ","; + mediaSelect += rs.getString(1); + first = false; + } + mediaSelect += ")"; + if (first == false) + returnList = DatabaseContent.getInstance().selectByWhereClause( + mediaSelect, -1); + } + } + catch (Exception e) { + logger.error("-- get content failed"); + throw new StorageObjectFailure("-- get content failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + } + return returnList; + } + + /** + * Returns a EntityList with all content-objects having a relation to a media + */ + + public EntityList getContent() throws StorageObjectFailure { + EntityList returnList = null; + + String select = "select distinct content_id from " + theTable; + // execute select statement + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt, select); + if (rs != null) { + String mediaSelect = "id IN ("; + boolean first = true; + while (rs.next()) { + if (first == false) + mediaSelect += ","; + mediaSelect += rs.getString(1); + first = false; + } + mediaSelect += ")"; + if (first == false) + returnList = DatabaseContent.getInstance().selectByWhereClause( + mediaSelect, "webdb_lastchange desc"); + } + } + catch (Exception e) { + logger.error("-- get content failed"); + throw new StorageObjectFailure("-- get content failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + + return returnList; + } + +} diff --git a/source/mircoders/storage/DatabaseContentToTopics.java b/source/mircoders/storage/DatabaseContentToTopics.java index 53c3c199..9d3b0c41 100755 --- a/source/mircoders/storage/DatabaseContentToTopics.java +++ b/source/mircoders/storage/DatabaseContentToTopics.java @@ -38,6 +38,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; +import mir.log.LoggerWrapper; import mir.entity.EntityList; import mir.storage.Database; import mir.storage.StorageObject; @@ -67,12 +68,13 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ return instance; } - private DatabaseContentToTopics() - throws StorageObjectFailure { - + private DatabaseContentToTopics() throws StorageObjectFailure { super(); - this.hasTimestamp = false; - this.theTable="content_x_topic"; + + logger = new LoggerWrapper("Database.ContentToTopics"); + + hasTimestamp = false; + theTable="content_x_topic"; try { this.theEntityClass = Class.forName("mir.entity.GenericEntity"); } catch (Exception e) { throw new StorageObjectFailure(e); } @@ -92,8 +94,9 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ try { returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1); - } catch (Exception e) { - theLog.printDebugInfo("-- get topics failed " + e.toString()); + } + catch (Exception e) { + logger.error("-- get topics failed " + e.toString()); } } return returnList; @@ -106,6 +109,7 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ public ArrayList getTopicsOfContent(String contentId) throws StorageObjectFailure { ArrayList returnList = new ArrayList(); + if (contentId != null) { String sql = "select topic_id from " + theTable + " where content_id=" + contentId; Connection con=null;Statement stmt=null; @@ -119,10 +123,11 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ returnList.add(new Integer(rs.getInt("topic_id"))); } } - } catch (Exception e) { - theLog.printError(e.toString()); - theLog.printError("-- get topicsofcontent failed"); - } finally { + } + catch (Exception e) { + logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage()); + } + finally { freeConnection(con,stmt); } } @@ -160,7 +165,7 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ } if(set==false){ toSet.add(topicId[i]); - theLog.printDebugInfo("to set: "+ topicId[i]); + logger.debug("to set: "+ topicId[i]); } } //now we check if we have to delete topics @@ -177,14 +182,14 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ } if(delete==true){ toDelete.add(topic.toString()); - theLog.printDebugInfo("to delete: "+ topic.toString()); + logger.debug("to delete: "+ topic.toString()); } } } else { //all the topics has to be set, so we copy all to the array - for (int i = 0; i < topicId.length; i++){ - toSet.add(topicId[i]); - } + for (int i = 0; i < topicId.length; i++){ + toSet.add(topicId[i]); + } } //first delete all row with content_id=contentId @@ -207,7 +212,7 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ stmt = con.createStatement(); int rs = executeUpdate(stmt,sql); } catch (Exception e) { - theLog.printDebugInfo("-- deleting topics failed"); + logger.error("-- deleting topics failed"); } finally { freeConnection(con,stmt); } @@ -222,8 +227,9 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt,sql); - } catch (Exception e) { - theLog.printDebugInfo("-- set topics failed -- insert laenge topicId" + topicId.length); + } + catch (Exception e) { + logger.error("-- set topics failed -- insert laenge topicId" + topicId.length); } finally { freeConnection(con,stmt); } @@ -267,9 +273,11 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ // should be a preparedStatement because is faster stmt = con.createStatement(); ResultSet rs = executeSql(stmt,sql); - } catch (Exception e) { - theLog.printDebugInfo("-- delete topics failed "); - } finally { + } + catch (Exception e) { + logger.error("-- delete topics failed "); + } + finally { freeConnection(con,stmt); } } @@ -302,7 +310,9 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1); } } - catch (Exception e) {theLog.printDebugInfo("-- get contetn failed");} + catch (Exception e) { + logger.error("-- get contetn failed"); + } finally { freeConnection(con,stmt);} } return returnList; diff --git a/source/mircoders/storage/DatabaseFeature.java b/source/mircoders/storage/DatabaseFeature.java index 57cc348b..03341276 100755 --- a/source/mircoders/storage/DatabaseFeature.java +++ b/source/mircoders/storage/DatabaseFeature.java @@ -1,80 +1,76 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseFeature extends Database implements StorageObject{ - - private static DatabaseFeature instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseFeature getInstance() - throws StorageObjectFailure { - if (instance == null) { - instance = new DatabaseFeature(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseFeature() throws StorageObjectFailure - { - super(); - //this.cache = new DatabaseCache(10); - this.hasTimestamp = false; - this.theTable="feature"; - - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityFeature"); - } - catch (Exception e) { - throw new StorageObjectFailure(e); - } - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title",true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import freemarker.template.SimpleList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseFeature extends Database implements StorageObject{ + + private static DatabaseFeature instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseFeature getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseFeature(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseFeature() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Feature"); + + hasTimestamp = false; + theTable = "feature"; + + theEntityClass = mircoders.entity.EntityFeature.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImageColor.java b/source/mircoders/storage/DatabaseImageColor.java index fb8fbb2a..4dce6468 100755 --- a/source/mircoders/storage/DatabaseImageColor.java +++ b/source/mircoders/storage/DatabaseImageColor.java @@ -1,74 +1,72 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageColor extends Database implements StorageObject{ - - private static DatabaseImageColor instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageColor getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseImageColor(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageColor() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - this.theTable="img_color"; - } - - public SimpleList getPopupData() - throws StorageObjectFailure { return getPopupData("name",true); } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import freemarker.template.SimpleList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageColor extends Database implements StorageObject{ + + private static DatabaseImageColor instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageColor getInstance() { + if (instance == null) { + instance = new DatabaseImageColor(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageColor() { + super(); + logger = new LoggerWrapper("Database.ImageColor"); + hasTimestamp = false; + theTable = "img_color"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } +} diff --git a/source/mircoders/storage/DatabaseImageFormat.java b/source/mircoders/storage/DatabaseImageFormat.java index 349390d9..67a3e7d3 100755 --- a/source/mircoders/storage/DatabaseImageFormat.java +++ b/source/mircoders/storage/DatabaseImageFormat.java @@ -1,74 +1,73 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageFormat extends Database implements StorageObject{ - - private static DatabaseImageFormat instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageFormat getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseImageFormat(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageFormat() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - this.theTable="img_format"; - } - - public SimpleList getPopupData() - throws StorageObjectFailure { return getPopupData("name",true); } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import freemarker.template.SimpleList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageFormat extends Database implements StorageObject{ + + private static DatabaseImageFormat instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageFormat getInstance() { + if (instance == null) { + instance = new DatabaseImageFormat(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageFormat() { + super(); + logger = new LoggerWrapper("Database.ImageFormat"); + hasTimestamp = false; + theTable = "img_format"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImageLayout.java b/source/mircoders/storage/DatabaseImageLayout.java index 0f2bfc92..10a2b70f 100755 --- a/source/mircoders/storage/DatabaseImageLayout.java +++ b/source/mircoders/storage/DatabaseImageLayout.java @@ -1,74 +1,74 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageLayout extends Database implements StorageObject{ - - private static DatabaseImageLayout instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageLayout getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseImageLayout(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageLayout() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - this.theTable="img_layout"; - } - - public SimpleList getPopupData() - throws StorageObjectFailure { return getPopupData("name",true); } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import freemarker.template.SimpleList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageLayout extends Database implements StorageObject{ + + private static DatabaseImageLayout instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageLayout getInstance() { + if (instance == null) { + instance = new DatabaseImageLayout(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageLayout() { + super(); + + logger = new LoggerWrapper("Database.ImageLayout"); + hasTimestamp = false; + theTable = "img_layout"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImageType.java b/source/mircoders/storage/DatabaseImageType.java index 473d7373..6f4dd7fc 100755 --- a/source/mircoders/storage/DatabaseImageType.java +++ b/source/mircoders/storage/DatabaseImageType.java @@ -1,74 +1,73 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageType extends Database implements StorageObject{ - - private static DatabaseImageType instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageType getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseImageType(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageType() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - this.theTable="img_type"; - } - - public SimpleList getPopupData() - throws StorageObjectFailure { return getPopupData("name",true); } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import freemarker.template.SimpleList; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageType extends Database implements StorageObject{ + private static DatabaseImageType instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageType getInstance() { + if (instance == null) { + instance = new DatabaseImageType(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageType() { + super(); + logger = new LoggerWrapper("Database.ImageType"); + + hasTimestamp = false; + theTable = "img_type"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImages.java b/source/mircoders/storage/DatabaseImages.java index 03592964..9a30c4fb 100755 --- a/source/mircoders/storage/DatabaseImages.java +++ b/source/mircoders/storage/DatabaseImages.java @@ -1,107 +1,105 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImages extends Database implements StorageObject{ - - private static DatabaseImages instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImages getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseImages(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImages() throws StorageObjectFailure - { - super(); - this.hasTimestamp = true; - this.theTable="images"; - this.theCoreTable="media"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityImages"); - } - catch (Exception e) { throw new StorageObjectFailure(e); } - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title",true); - } - - public void update(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - - super.update(theEntity); - } - - - public String insert(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; + +import freemarker.template.SimpleList; + +import mir.log.LoggerWrapper; +import mir.entity.Entity; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImages extends Database implements StorageObject{ + + private static DatabaseImages instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImages getInstance() { + if (instance == null) { + instance = new DatabaseImages(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImages() { + super(); + + logger = new LoggerWrapper("Database.Images"); + + hasTimestamp = true; + theTable = "images"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityImages.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + return super.insert(theEntity); + } + + // initialisierungen aus den statischen Tabellen + +} diff --git a/source/mircoders/storage/DatabaseLanguage.java b/source/mircoders/storage/DatabaseLanguage.java index e3d32018..a0ed059d 100755 --- a/source/mircoders/storage/DatabaseLanguage.java +++ b/source/mircoders/storage/DatabaseLanguage.java @@ -40,10 +40,12 @@ package mircoders.storage; * @version 1.0 */ +import freemarker.template.SimpleList; + +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; public class DatabaseLanguage extends Database implements StorageObject{ @@ -65,6 +67,8 @@ public class DatabaseLanguage extends Database implements StorageObject{ private DatabaseLanguage() throws StorageObjectFailure { super(); + logger = new LoggerWrapper("Database.Language"); + this.hasTimestamp = false; this.theTable = "language"; } diff --git a/source/mircoders/storage/DatabaseLinksImcs.java b/source/mircoders/storage/DatabaseLinksImcs.java index b69a0cff..306b2485 100755 --- a/source/mircoders/storage/DatabaseLinksImcs.java +++ b/source/mircoders/storage/DatabaseLinksImcs.java @@ -35,9 +35,10 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; +import java.util.List; import java.util.HashMap; +import mir.log.LoggerWrapper; import mir.entity.Entity; import mir.storage.Database; import mir.storage.StorageObject; @@ -50,41 +51,34 @@ import mir.util.JDBCStringRoutines; * * */ -public class DatabaseLinksImcs extends Database - implements StorageObject { +public class DatabaseLinksImcs extends Database implements StorageObject { + private static DatabaseLinksImcs instance; - /** - * put your documentation comment here - * @return - * @exception StorageObjectException - */ - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseLinksImcs getInstance() throws - StorageObjectFailure { + public static DatabaseLinksImcs getInstance() { if (instance == null) { - instance = new DatabaseLinksImcs(); - instance.myselfDatabase = instance; + synchronized (DatabaseLinksImcs.class) { + if (instance == null) { + DatabaseLinksImcs newInstance; + + newInstance = new DatabaseLinksImcs(); + newInstance.myselfDatabase = newInstance; + instance = newInstance; + } + } } + return instance; } - /** - * put your documentation comment here - */ - private DatabaseLinksImcs() throws StorageObjectFailure { + private DatabaseLinksImcs() { super(); - ////this.cache = new HashMap(); - this.hasTimestamp = false; - this.theTable = "links_imcs"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityLinksImcs"); - } - catch (Exception e) { - throw new StorageObjectFailure(e); - } + + logger = new LoggerWrapper("ServletModule.Database.LinksImcs"); + hasTimestamp = false; + theTable = "links_imcs"; + + theEntityClass = mircoders.entity.EntityLinksImcs.class; } /** @todo toooo much copy/paste in this class //rk */ @@ -97,7 +91,7 @@ public class DatabaseLinksImcs extends Database invalidatePopupCache(); try { HashMap theEntityValues = theEntity.getValues(); - ArrayList streamedInput = theEntity.streamedInput(); + List streamedInput = theEntity.streamedInput(); StringBuffer f = new StringBuffer(); StringBuffer v = new StringBuffer(); String aField, aValue; @@ -141,10 +135,12 @@ public class DatabaseLinksImcs extends Database } } // end for // insert into db - StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable). - append("(").append(f).append(") values (").append(v).append(")"); + StringBuffer sqlBuf = + new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")"); String sql = sqlBuf.toString(); - theLog.printInfo("INSERT: " + sql); + + logger.info("INSERT: " + sql); + con = getPooledCon(); con.setAutoCommit(false); pstmt = con.prepareStatement(sql); @@ -180,7 +176,7 @@ public class DatabaseLinksImcs extends Database public void update(Entity theEntity) throws StorageObjectFailure { Connection con = null; PreparedStatement pstmt = null; - ArrayList streamedInput = theEntity.streamedInput(); + List streamedInput = theEntity.streamedInput(); HashMap theEntityValues = theEntity.getValues(); String id = theEntity.getId(); String aField; @@ -223,7 +219,7 @@ public class DatabaseLinksImcs extends Database } } sql.append(" where id=").append(id); - theLog.printInfo("UPDATE: " + sql); + logger.info("UPDATE: " + sql); // execute sql try { con = getPooledCon(); diff --git a/source/mircoders/storage/DatabaseMedia.java b/source/mircoders/storage/DatabaseMedia.java index c0ab7a53..97b25f91 100755 --- a/source/mircoders/storage/DatabaseMedia.java +++ b/source/mircoders/storage/DatabaseMedia.java @@ -31,6 +31,7 @@ package mircoders.storage; +import mir.log.LoggerWrapper; import mir.entity.Entity; import mir.entity.EntityRelation; import mir.storage.Database; @@ -52,8 +53,7 @@ public class DatabaseMedia extends Database implements StorageObject{ // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseMedia getInstance() - throws StorageObjectFailure { + public synchronized static DatabaseMedia getInstance() { if (instance == null) { instance = new DatabaseMedia(); instance.myselfDatabase = instance; @@ -61,20 +61,16 @@ public class DatabaseMedia extends Database implements StorageObject{ return instance; } - private DatabaseMedia() throws StorageObjectFailure - { + private DatabaseMedia() { super(); - //this.cache = new DatabaseCache(100); - this.hasTimestamp = false; - this.theTable="media"; - relationMediaType = new EntityRelation("to_media_type", "id", - DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityMedia"); - } - catch (Exception e) { - throw new StorageObjectFailure(e); - } + + logger = new LoggerWrapper("Database.Media"); + + hasTimestamp = false; + theTable="media"; + relationMediaType = + new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); + theEntityClass = mircoders.entity.EntityMedia.class; } // methods @@ -84,17 +80,14 @@ public class DatabaseMedia extends Database implements StorageObject{ * returns the comments that belong to the article (via entityrelation) * where db-flag is_published is true */ - public Entity getMediaType(Entity ent) - throws StorageObjectFailure, StorageObjectExc { - Entity type=null; + public Entity getMediaType(Entity ent) throws StorageObjectFailure, StorageObjectExc { try { - type = relationMediaType.getOne(ent); + return relationMediaType.getOne(ent); } - catch (StorageObjectFailure e) { - theLog.printError("DatabaseMedia :: failed to get media_type"); - throw new StorageObjectFailure("DatabaseMedia :",e); + catch (Throwable e) { + logger.error("failed to get media_type: " + e.getMessage()); + throw new StorageObjectFailure("DatabaseMedia.getMediaType :" + e.getMessage(),e); } - return type; } } diff --git a/source/mircoders/storage/DatabaseMediaType.java b/source/mircoders/storage/DatabaseMediaType.java index 6291d46c..c1101bd2 100755 --- a/source/mircoders/storage/DatabaseMediaType.java +++ b/source/mircoders/storage/DatabaseMediaType.java @@ -31,6 +31,7 @@ package mircoders.storage; +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; @@ -49,8 +50,7 @@ public class DatabaseMediaType extends Database implements StorageObject{ // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseMediaType getInstance() - throws StorageObjectFailure { + public synchronized static DatabaseMediaType getInstance() { if (instance == null) { instance = new DatabaseMediaType(); instance.myselfDatabase = instance; @@ -61,13 +61,12 @@ public class DatabaseMediaType extends Database implements StorageObject{ private DatabaseMediaType() throws StorageObjectFailure { super(); - this.hasTimestamp = false; - //this.cache = new DatabaseCache(20); - this.theTable="media_type"; - try { - this.theEntityClass = Class.forName("mir.entity.GenericEntity"); - } - catch (Exception e) { throw new StorageObjectFailure(e); } + + logger = new LoggerWrapper("Database.MediaType"); + + hasTimestamp = false; + theTable="media_type"; + theEntityClass = mir.entity.GenericEntity.class; } } diff --git a/source/mircoders/storage/DatabaseMediafolder.java b/source/mircoders/storage/DatabaseMediafolder.java index fd8eda5e..103ee16f 100755 --- a/source/mircoders/storage/DatabaseMediafolder.java +++ b/source/mircoders/storage/DatabaseMediafolder.java @@ -40,6 +40,7 @@ package mircoders.storage; * @version */ +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; @@ -54,8 +55,7 @@ public class DatabaseMediafolder extends Database implements StorageObject{ // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseMediafolder getInstance() - throws StorageObjectFailure { + public synchronized static DatabaseMediafolder getInstance() { if (instance == null) { instance = new DatabaseMediafolder(); instance.myselfDatabase = instance; @@ -63,12 +63,13 @@ public class DatabaseMediafolder extends Database implements StorageObject{ return instance; } - private DatabaseMediafolder() throws StorageObjectFailure - { + private DatabaseMediafolder() { super(); - this.hasTimestamp = false; - //this.cache = new DatabaseCache(20); - this.theTable="media_folder"; + + logger = new LoggerWrapper("Database.Mediafolder"); + + hasTimestamp = false; + theTable="media_folder"; } public SimpleList getPopupData() throws StorageObjectFailure { diff --git a/source/mircoders/storage/DatabaseMessages.java b/source/mircoders/storage/DatabaseMessages.java index 7c8eb50e..8461ac73 100755 --- a/source/mircoders/storage/DatabaseMessages.java +++ b/source/mircoders/storage/DatabaseMessages.java @@ -31,6 +31,7 @@ package mircoders.storage; +import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; @@ -53,8 +54,7 @@ public class DatabaseMessages extends Database implements StorageObject{ // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseMessages getInstance() - throws StorageObjectFailure { + public synchronized static DatabaseMessages getInstance() { if (instance == null) { instance = new DatabaseMessages(); instance.myselfDatabase = instance; @@ -62,10 +62,12 @@ public class DatabaseMessages extends Database implements StorageObject{ return instance; } - private DatabaseMessages() throws StorageObjectFailure + private DatabaseMessages() { super(); - //this.cache = new DatabaseCache(10); + + logger = new LoggerWrapper("Database.Messages"); + this.theTable="messages"; } diff --git a/source/mircoders/storage/DatabaseOther.java b/source/mircoders/storage/DatabaseOther.java index 50f7842b..15061d61 100755 --- a/source/mircoders/storage/DatabaseOther.java +++ b/source/mircoders/storage/DatabaseOther.java @@ -1,107 +1,101 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseOther extends Database implements StorageObject{ - - private static DatabaseOther instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseOther getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseOther(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseOther() throws StorageObjectFailure - { - super(); - this.hasTimestamp = true; - this.theTable="other_media"; - this.theCoreTable="media"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityOther"); - } - catch (Exception e) { throw new StorageObjectFailure(e); } - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title",true); - } - - public void update(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - - super.update(theEntity); - } - - - public String insert(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + + +import java.util.GregorianCalendar; + +import mir.log.LoggerWrapper; +import mir.entity.Entity; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseOther extends Database implements StorageObject{ + private static DatabaseOther instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseOther getInstance() { + if (instance == null) { + instance = new DatabaseOther(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseOther() { + super(); + + logger = new LoggerWrapper("Database.OtherMedia"); + + hasTimestamp = true; + theTable = "other_media"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityOther.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + + // initialisierungen aus den statischen Tabellen + +} diff --git a/source/mircoders/storage/DatabaseRights.java b/source/mircoders/storage/DatabaseRights.java index 826788cd..3c87f892 100755 --- a/source/mircoders/storage/DatabaseRights.java +++ b/source/mircoders/storage/DatabaseRights.java @@ -1,74 +1,74 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseRights extends Database implements StorageObject{ - - private static DatabaseRights instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseRights getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseRights(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseRights() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - this.theTable="rights"; - } - - public SimpleList getPopupData() throws StorageObjectFailure - { return getPopupData("name",true); } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseRights extends Database implements StorageObject{ + private static DatabaseRights instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseRights getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseRights(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseRights() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Rights"); + + hasTimestamp = false; + theTable = "rights"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseTopics.java b/source/mircoders/storage/DatabaseTopics.java index 4cf6f976..2445eb3a 100755 --- a/source/mircoders/storage/DatabaseTopics.java +++ b/source/mircoders/storage/DatabaseTopics.java @@ -1,82 +1,75 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseTopics extends Database implements StorageObject{ - - private static DatabaseTopics instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseTopics getInstance() - throws StorageObjectFailure { - if (instance == null) { - instance = new DatabaseTopics(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseTopics() throws StorageObjectFailure - { - super(); - //this.cache = new DatabaseCache(20); - this.hasTimestamp = false; - this.theTable="topic"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityTopics"); - } - catch (Exception e) { - throw new StorageObjectFailure(e); - } - - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title",true); - } - - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseTopics extends Database implements StorageObject{ + + private static DatabaseTopics instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseTopics getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseTopics(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseTopics() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Topics"); + + hasTimestamp = false; + theTable = "topic"; + theEntityClass = mircoders.entity.EntityTopics.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } +} diff --git a/source/mircoders/storage/DatabaseUploadedMedia.java b/source/mircoders/storage/DatabaseUploadedMedia.java index 7792ef16..1fd6eee5 100755 --- a/source/mircoders/storage/DatabaseUploadedMedia.java +++ b/source/mircoders/storage/DatabaseUploadedMedia.java @@ -31,6 +31,7 @@ package mircoders.storage; +import mir.log.LoggerWrapper; import mir.entity.Entity; import mir.entity.EntityRelation; import mir.storage.Database; @@ -65,6 +66,9 @@ public class DatabaseUploadedMedia extends Database implements StorageObject { throws StorageObjectFailure { super(); + + logger = new LoggerWrapper("Database.UploadedMedia"); + this.theTable="uploaded_media"; this.theCoreTable="media"; relationMediaType = new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); @@ -79,15 +83,15 @@ public class DatabaseUploadedMedia extends Database implements StorageObject { * returns the media_type that belongs to the media item (via entityrelation) * where db-flag is_published is true */ - public Entity getMediaType(Entity ent) - throws StorageObjectFailure, StorageObjectExc { + public Entity getMediaType(Entity ent) throws StorageObjectFailure { Entity type=null; try { type = relationMediaType.getOne(ent); } - catch (StorageObjectFailure e) { - theLog.printError("DatabaseUploadedMedia :: failed to get media_type"); - throw new StorageObjectFailure("DatabaseUploadedMedia :: failed to get media_type", e); + catch (Throwable t) { + logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage()); + + throw new StorageObjectFailure("DatabaseUploadedMedia :: failed to get media_type", t); } return type; } diff --git a/source/mircoders/storage/DatabaseUsers.java b/source/mircoders/storage/DatabaseUsers.java index 9ba17128..1373abb2 100755 --- a/source/mircoders/storage/DatabaseUsers.java +++ b/source/mircoders/storage/DatabaseUsers.java @@ -1,77 +1,75 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseUsers extends Database implements StorageObject{ - - private static DatabaseUsers instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseUsers getInstance() - throws StorageObjectFailure { - if (instance == null) { - instance = new DatabaseUsers(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseUsers() throws StorageObjectFailure - { - super(); - this.hasTimestamp = false; - this.theTable="webdb_users"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityUsers"); - } - catch (Exception e) { - throw new StorageObjectFailure(e); - } - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("login",true); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseUsers extends Database implements StorageObject{ + + private static DatabaseUsers instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseUsers getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseUsers(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseUsers() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Users"); + + hasTimestamp = false; + theTable = "webdb_users"; + theEntityClass = mircoders.entity.EntityUsers.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("login", true); + } +} diff --git a/source/mircoders/storage/DatabaseVideo.java b/source/mircoders/storage/DatabaseVideo.java index 533ba8d1..d251c600 100755 --- a/source/mircoders/storage/DatabaseVideo.java +++ b/source/mircoders/storage/DatabaseVideo.java @@ -1,105 +1,100 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseVideo extends Database implements StorageObject{ - - private static DatabaseVideo instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseVideo getInstance() - throws StorageObjectFailure - { - if (instance == null) { - instance = new DatabaseVideo(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseVideo() throws StorageObjectFailure - { - super(); - this.hasTimestamp = true; - this.theTable="video"; - this.theCoreTable="media"; - try { - this.theEntityClass = Class.forName("mircoders.entity.EntityVideo"); - } - catch (Exception e) { throw new StorageObjectFailure(e); } - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title",true); - } - - public void update(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - - super.update(theEntity); - } - - - public String insert(Entity theEntity) throws StorageObjectFailure - { - String date = theEntity.getValue("date"); - if (date==null){ - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date",date); - } - return super.insert(theEntity); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; + +import mir.log.LoggerWrapper; +import mir.entity.Entity; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseVideo extends Database implements StorageObject{ + + private static DatabaseVideo instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseVideo getInstance() { + if (instance == null) { + instance = new DatabaseVideo(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseVideo() { + super(); + + logger = new LoggerWrapper("Database.Video"); + + hasTimestamp = true; + theTable = "video"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityVideo.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + +} -- 2.11.0