-/*
- * 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.<p>
- */
-
-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?
- }
-
-
- //////////////////////////////////////////////////////////////////////////////////
-
-
-}
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+/**\r
+ * Base class the entities are derived from. Provides base functionality of\r
+ * an entity. Entities are used to represent rows of a database table.<p>\r
+ */\r
+\r
+package mir.entity;\r
+\r
+import java.util.List;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.Set;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.misc.Logfile;\r
+import mir.misc.StringUtil;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectExc;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleScalar;\r
+import freemarker.template.TemplateHashModel;\r
+import freemarker.template.TemplateModel;\r
+import freemarker.template.TemplateModelException;\r
+import freemarker.template.TemplateModelRoot;\r
+\r
+/**\r
+ * Base Class of Entities\r
+ * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant\r
+ *\r
+ * @version $Id: Entity.java,v 1.14 2003/02/20 16:05:32 zapata Exp $\r
+ * @author rk\r
+ *\r
+ */\r
+\r
+public class Entity implements TemplateHashModel, TemplateModelRoot\r
+{\r
+ protected static MirPropertiesConfiguration configuration;\r
+ protected static Logfile theLog;\r
+\r
+ private boolean changed;\r
+ protected HashMap theValuesHash; // tablekey / value\r
+ protected StorageObject theStorageObject;\r
+ protected List streamedInput = null;\r
+\r
+ static {\r
+ try {\r
+ configuration = MirPropertiesConfiguration.instance();\r
+ }\r
+ catch (PropertiesConfigExc e) {\r
+ e.printStackTrace();\r
+ }\r
+ theLog = Logfile.getInstance(configuration.getStringWithHome(\r
+ "Entity.Logfile"));\r
+ }\r
+\r
+ public Entity() {\r
+ this.changed = false;\r
+ }\r
+\r
+ /**\r
+ * Constructor\r
+ * @param StorageObject The StorageObject of the Entity.\r
+ */\r
+ public Entity(StorageObject StorageObject) {\r
+ this();\r
+ setStorage(StorageObject);\r
+ }\r
+\r
+ /*\r
+ * Sets the StorageObject of the Entity.\r
+ */\r
+ public void setStorage(StorageObject storage) {\r
+ this.theStorageObject = storage;\r
+ }\r
+\r
+ /**\r
+ * Sets the values of the Entity.\r
+ * @param theStringValues HashMap containing the new values of the Entity\r
+ */\r
+\r
+ public void setValues(HashMap theStringValues) {\r
+ /** @todo should be synchronized */\r
+ if (theStringValues != null) {\r
+ theValuesHash = new HashMap();\r
+ String aKey;\r
+ Set set = theStringValues.keySet();\r
+ Iterator it = set.iterator();\r
+ int size = set.size();\r
+ for (int i = 0; i < size; i++) {\r
+ aKey = (String) it.next();\r
+ theValuesHash.put(aKey, (String) theStringValues.get(aKey));\r
+ }\r
+ }\r
+ else\r
+ theLog.printWarning("Entity.setValues called with null HashMap");\r
+ }\r
+\r
+ /**\r
+ * Returns whether the content of the Entity has changed.\r
+ * @return true wenn ja, sonst false\r
+ */\r
+ public boolean changed() {\r
+ return changed;\r
+ }\r
+\r
+ /**\r
+ * Returns the primary key of the Entity.\r
+ * @return String Id\r
+ */\r
+ public String getId() {\r
+ return (String) getValue(theStorageObject.getIdName());\r
+ }\r
+\r
+ /**\r
+ * Defines the primary key of the Entity\r
+ * @param id\r
+ */\r
+ public void setId(String id) {\r
+ theValuesHash.put(theStorageObject.getIdName(), id);\r
+ }\r
+\r
+ /**\r
+ * Returns the value of a field by field name.\r
+ * @param field The name of the field\r
+ * @return value of the field\r
+ */\r
+ public String getValue(String field) {\r
+ String returnValue = null;\r
+ if (field != null) {\r
+ if (field.equals("webdb_create_formatted")) {\r
+ if (hasValueForField("webdb_create"))\r
+ returnValue = StringUtil.dateToReadableDate(getValue("webdb_create"));\r
+ }\r
+ else if (field.equals("webdb_lastchange_formatted")) {\r
+ if (hasValueForField("webdb_lastchange"))\r
+ returnValue = StringUtil.dateToReadableDate(getValue(\r
+ "webdb_lastchange"));\r
+ }\r
+ else\r
+ returnValue = (String) theValuesHash.get(field);\r
+ }\r
+ return returnValue;\r
+ }\r
+\r
+ public boolean hasValueForField(String field) {\r
+ if (theValuesHash != null)\r
+ return theValuesHash.containsKey(field);\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * Insers Entity into the database via StorageObject\r
+ * @return Primary Key of the Entity\r
+ * @exception StorageObjectException\r
+ */\r
+ public String insert() throws StorageObjectExc {\r
+ theLog.printDebugInfo("Entity: trying to insert ...");\r
+ if (theStorageObject != null) {\r
+ return theStorageObject.insert( (Entity)this);\r
+ }\r
+ else\r
+ throw new StorageObjectExc("Kein StorageObject gesetzt!");\r
+ }\r
+\r
+ /**\r
+ * Saves changes of this Entity to the database\r
+ * @exception StorageObjectException\r
+ */\r
+ public void update() throws StorageObjectFailure {\r
+ theStorageObject.update( (Entity)this);\r
+ }\r
+\r
+ /**\r
+ * Sets the value for a field. Issues a log message if the field name\r
+ * supplied was not found in the Entity.\r
+ * @param theProp The field name whose value has to be set\r
+ * @param theValue The new value of the field\r
+ * @exception StorageObjectException\r
+ */\r
+ public void setValueForProperty(String theProp, String theValue) throws\r
+ StorageObjectFailure {\r
+ this.changed = true;\r
+ if (isField(theProp))\r
+ theValuesHash.put(theProp, theValue);\r
+ else {\r
+ theLog.printWarning("Property not found: " + theProp + theValue);\r
+ }\r
+\r
+ }\r
+\r
+ /**\r
+ * Returns the field names of the Entity as ArrayListe.\r
+ * @return ArrayList with field names\r
+ * @exception StorageObjectException is throuwn if database access was impossible\r
+ */\r
+ public List getFields() throws StorageObjectFailure {\r
+ return theStorageObject.getFields();\r
+ }\r
+\r
+ /**\r
+ * Returns an int[] with the types of the fields\r
+ * @return int[] that contains the types of the fields\r
+ * @exception StorageObjectException\r
+ */\r
+ public int[] getTypes() throws StorageObjectFailure {\r
+ return theStorageObject.getTypes();\r
+ }\r
+\r
+ /**\r
+ * Returns an ArrayList with field names\r
+ * @return List with field names\r
+ * @exception StorageObjectException\r
+ */\r
+ public List getLabels() throws StorageObjectFailure {\r
+ return theStorageObject.getLabels();\r
+ }\r
+\r
+ /**\r
+ * Returns a Hashmap with all values of the Entity.\r
+ * @return HashMap with field name as key and the corresponding values\r
+ *\r
+ * @deprecated This method is deprecated and will be deleted in the next release.\r
+ * Entity interfaces freemarker.template.TemplateHashModel now and can\r
+ * be used in the same way as SimpleHash.\r
+ */\r
+ public HashMap getValues() {\r
+ theLog.printWarning(\r
+ "## using deprecated Entity.getValues() - a waste of resources");\r
+ return theValuesHash;\r
+ }\r
+\r
+ /**\r
+ * Returns an ArrayList with all database fields that can\r
+ * be evaluated as streamedInput.\r
+ * Could be automated by the types (blob, etc.)\r
+ * Until now to be created manually in the inheriting class\r
+ *\r
+ * Liefert einen ArrayList mit allen Datenbankfeldern, die\r
+ * als streamedInput ausgelesen werden muessen.\r
+ * Waere automatisierbar ueber die types (blob, etc.)\r
+ * Bisher manuell anzulegen in der erbenden Klasse\r
+ */\r
+\r
+ public List streamedInput() {\r
+ return streamedInput;\r
+ }\r
+\r
+ /** Returns whether fieldName is a valid field name of this Entity.\r
+ * @param fieldName\r
+ * @return true in case fieldName is a field name, else false.\r
+ * @exception StorageObjectException\r
+ */\r
+ public boolean isField(String fieldName) throws StorageObjectFailure {\r
+ return theStorageObject.getFields().contains(fieldName);\r
+ }\r
+\r
+ protected void throwStorageObjectFailure(Exception e, String wo) throws\r
+ StorageObjectFailure {\r
+ theLog.printError(e.toString() + " Funktion: " + wo);\r
+ e.printStackTrace(System.out);\r
+ throw new StorageObjectFailure("Storage Object Exception in entity", e);\r
+ }\r
+\r
+ // Now implements freemarkers TemplateHashModel\r
+ // two methods have to be overridden:\r
+ // 1. public boolean isEmpty() throws TemplateModelException\r
+ // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException\r
+\r
+ public boolean isEmpty() throws TemplateModelException {\r
+ return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false;\r
+ }\r
+\r
+ public TemplateModel get(java.lang.String key) throws TemplateModelException {\r
+ return new SimpleScalar(getValue(key));\r
+ }\r
+\r
+ public void put(java.lang.String key, TemplateModel model) {\r
+ // putting should only take place via setValue and is limited to the\r
+ // database fields associated with the entity. no additional freemarker\r
+ // stuff will be available via Entity.\r
+ theLog.printWarning(\r
+ "### put is called on entity! - the values will be lost!");\r
+ }\r
+\r
+ public void remove(java.lang.String key) {\r
+ // do we need this?\r
+ }\r
+\r
+ //////////////////////////////////////////////////////////////////////////////////\r
+}\r
+\r
+++ /dev/null
-/*
- * 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;\r
-\r
-public class QueryBuilder {\r
-\r
- private String whereClause;\r
- private String orderByClause;\r
-\r
- public QueryBuilder(){\r
- whereClause = new String();\r
- orderByClause = new String();\r
- }\r
-\r
- public void appendDescendingOrder(String anOrder) {\r
- if (orderByClause.length()==0) {\r
- orderByClause=anOrder+" desc";\r
- }\r
- else {\r
- orderByClause=orderByClause+","+anOrder+" desc";\r
- }\r
- }\r
-\r
- public void appendAscendingOrder(String anOrder) {\r
- if (orderByClause.length()==0) {\r
- orderByClause=anOrder+" asc";\r
- }\r
- else {\r
- orderByClause=orderByClause+","+anOrder+" asc";\r
- }\r
- }\r
-\r
- public void appendAndCondition(String aQualifier) {\r
- if (whereClause.length()==0) {\r
- whereClause = aQualifier;\r
- }\r
- else {\r
- whereClause="("+whereClause+") and ("+aQualifier+")";\r
- }\r
- }\r
-\r
- public void appendOrCondition(String aQualifier) {\r
- if (whereClause.length()==0) {\r
- whereClause = aQualifier;\r
- }\r
- else {\r
- whereClause="("+whereClause+") or ("+aQualifier+")";\r
- }\r
- }\r
-\r
- public String getWhereClause() {\r
- return whereClause;\r
- }\r
-\r
- public String getOrderByClause() {\r
- return orderByClause;\r
- }\r
-}
\ No newline at end of file
-/*
- * 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())
- {
- result = (TemplateModel) valuesCache.get(anIndex);
-
- return result;
- }
- else
- throw new TemplateModelException( "Iterator out of bounds" );
- }
-
- public boolean hasNext() {
- return position<valuesCache.size() || iterator.hasNext();
- }
-
- public boolean isRewound() {
- return position==0;
- }
-
- public TemplateModel next() throws TemplateModelException {
- TemplateModel result;
-
- if (hasNext()) {
- result = get(position);
- position++;
- }
- else
- throw new TemplateModelException( "Iterator out of bounds" );
-
- return result;
- }
-
- public void rewind() {
- position=0;
- }
- }
-
- private static class ListAdapter implements TemplateListModel {
- List list;
- List valuesCache;
- int position;
-
- private ListAdapter(List aList) {
- list = aList;
- valuesCache = new Vector();
- position=0;
- }
-
- public boolean isEmpty() {
- return list.isEmpty();
- }
-
- public TemplateModel get(int i) throws TemplateModelException {
-
- if (i>=valuesCache.size() && i<list.size()) {
- for(int j=valuesCache.size(); j<=i; j++) {
- valuesCache.add(makeAdapter(list.get(j)));
- }
- }
-
- if (i<valuesCache.size())
- return (TemplateModel) valuesCache.get(i);
- else
- throw new TemplateModelException( "Iterator out of bounds" );
- }
-
- public boolean hasNext() {
- return position<list.size();
- }
-
- public boolean isRewound() {
- return position==0;
- }
-
- public TemplateModel next() throws TemplateModelException {
- TemplateModel result;
-
- if (hasNext()) {
- result = get(position);
- position++;
- }
- else {
- throw new TemplateModelException( "Iterator out of bounds" );
- }
-
- return result;
- }
-
- public void rewind() {
- position = 0;
- }
- }
-
- private static class FunctionAdapter implements TemplateMethodModel {
- Generator.GeneratorFunction function;
-
- public FunctionAdapter(Generator.GeneratorFunction aFunction) {
- function = aFunction;
- }
-
- public TemplateModel exec(List anArguments) throws TemplateModelException {
- try {
- return makeAdapter(function.perform(anArguments));
- }
- catch (Throwable t) {
- throw new TemplateModelException(t.getMessage());
- }
- }
-
- public boolean isEmpty() {
- return false;
- }
-
- }
-
- public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {
- private FileTemplateCache templateCache;
-
- public FreemarkerGeneratorLibrary(String aTemplateRoot) {
- templateCache = new FileTemplateCache( aTemplateRoot+"/" );
- templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);
- }
-
- public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
- Template template = (Template) templateCache.getItem(anIdentifier, "template");
-
- if (template==null) {
- throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier);
- }
-
- return new FreemarkerGenerator(template);
- }
- }
-
- public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory {
- private String basePath;
-
- public FreemarkerGeneratorLibraryFactory(String aBasePath) {
- basePath = aBasePath;
- }
-
- public GeneratorLibrary makeLibrary(String anInitializationString) {
- return new FreemarkerGeneratorLibrary(basePath+anInitializationString);
- };
- }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.generator;\r
+\r
+import java.io.PrintWriter;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import org.apache.struts.util.MessageResources;\r
+\r
+import freemarker.template.FileTemplateCache;\r
+import freemarker.template.SimpleScalar;\r
+import freemarker.template.Template;\r
+import freemarker.template.TemplateHashModel;\r
+import freemarker.template.TemplateListModel;\r
+import freemarker.template.TemplateMethodModel;\r
+import freemarker.template.TemplateModel;\r
+import freemarker.template.TemplateModelException;\r
+import freemarker.template.TemplateModelRoot;\r
+import freemarker.template.TemplateScalarModel;\r
+\r
+import mir.misc.MessageMethodModel;\r
+import mir.util.RewindableIterator;\r
+\r
+public class FreemarkerGenerator implements Generator {\r
+ private Template template;\r
+\r
+ public FreemarkerGenerator(Template aTemplate) {\r
+ template = aTemplate;\r
+ }\r
+\r
+ public void generate(Object anOutputWriter, Map aValues, PrintWriter aLogger) throws GeneratorExc, GeneratorFailure {\r
+ if (!(anOutputWriter instanceof PrintWriter))\r
+ throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter");\r
+\r
+ try {\r
+ template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter);\r
+ }\r
+ catch (Throwable t) {\r
+ t.printStackTrace();\r
+ aLogger.println("Exception occurred: "+t.getMessage());\r
+ t.printStackTrace(aLogger);\r
+ throw new GeneratorFailure( t );\r
+ }\r
+ }\r
+\r
+ private static TemplateScalarModel makeStringAdapter(String aString) {\r
+ return new SimpleScalar(aString);\r
+ }\r
+\r
+ private static TemplateHashModel makeMapAdapter(Map aMap) {\r
+ return new MapAdapter(aMap);\r
+ }\r
+\r
+ private static TemplateListModel makeIteratorAdapter(Iterator anIterator) {\r
+ return new IteratorAdapter(anIterator);\r
+ }\r
+\r
+ private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) {\r
+ return new FunctionAdapter(aFunction);\r
+ }\r
+\r
+ public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {\r
+ if (anObject == null)\r
+ return null;\r
+\r
+ if (anObject instanceof TemplateModel)\r
+ return (TemplateModel) anObject;\r
+ else if (anObject instanceof Generator.GeneratorFunction)\r
+ return makeFunctionAdapter((Generator.GeneratorFunction) anObject);\r
+ else if (anObject instanceof MessageResources)\r
+ return new MessageMethodModel((MessageResources) anObject);\r
+ else if (anObject instanceof Integer)\r
+ return makeStringAdapter(((Integer) anObject).toString());\r
+ else if (anObject instanceof Boolean) {\r
+ if (((Boolean) anObject).booleanValue())\r
+ return makeStringAdapter("1");\r
+ else\r
+ return makeStringAdapter("0");\r
+ }\r
+ else if (anObject instanceof String)\r
+ return makeStringAdapter((String) anObject);\r
+ else if (anObject instanceof Map)\r
+ return makeMapAdapter((Map) anObject);\r
+ else if (anObject instanceof Iterator)\r
+ return makeIteratorAdapter((Iterator) anObject);\r
+ else if (anObject instanceof List)\r
+ return makeIteratorAdapter(((List) anObject).iterator());\r
+ else\r
+ throw new TemplateModelException("Unadaptable class: " + anObject.getClass().getName());\r
+ }\r
+\r
+ private static class MapAdapter implements TemplateModelRoot {\r
+ Map map;\r
+ Map valuesCache;\r
+\r
+ private MapAdapter(Map aMap) {\r
+ map = aMap;\r
+ valuesCache = new HashMap();\r
+ }\r
+\r
+ public void put(String aKey, TemplateModel aModel) {\r
+ valuesCache.put(aKey, aModel);\r
+ }\r
+\r
+ public void remove(String aKey) {\r
+ // ML: kinda tricky...\r
+ }\r
+\r
+ public boolean isEmpty() {\r
+ return map.isEmpty();\r
+ }\r
+\r
+ public TemplateModel get(String aKey) throws TemplateModelException {\r
+ try {\r
+ if (!valuesCache.containsKey(aKey)) {\r
+ Object value = map.get(aKey);\r
+\r
+ if (value == null && !map.containsKey(aKey)) {\r
+ throw new TemplateModelException("MapAdapter: no key "+aKey+" available");\r
+ }\r
+\r
+ valuesCache.put(aKey, makeAdapter(value));\r
+ }\r
+\r
+ return (TemplateModel) valuesCache.get(aKey);\r
+ }\r
+ catch (TemplateModelException e) {\r
+ throw e;\r
+ }\r
+ catch (Throwable t) {\r
+ throw new TemplateModelException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+ private static class IteratorAdapter implements TemplateListModel {\r
+ Iterator iterator;\r
+ List valuesCache;\r
+ int position;\r
+\r
+ private IteratorAdapter(Iterator anIterator) {\r
+ iterator = anIterator;\r
+\r
+ valuesCache = new Vector();\r
+ position=0;\r
+\r
+\r
+ if (iterator instanceof RewindableIterator) {\r
+ ((RewindableIterator) iterator).rewind();\r
+ }\r
+ }\r
+\r
+ public boolean isEmpty() {\r
+ return valuesCache.isEmpty() && !iterator.hasNext();\r
+ }\r
+\r
+ private void getUntil(int anIndex) throws TemplateModelException {\r
+ while (valuesCache.size()<=anIndex && iterator.hasNext())\r
+ {\r
+ valuesCache.add(makeAdapter(iterator.next()));\r
+ }\r
+ };\r
+\r
+ public TemplateModel get(int anIndex) throws TemplateModelException {\r
+ TemplateModel result;\r
+\r
+ getUntil(anIndex);\r
+\r
+ if (anIndex<valuesCache.size())\r
+ {\r
+ result = (TemplateModel) valuesCache.get(anIndex);\r
+\r
+ return result;\r
+ }\r
+ else\r
+ throw new TemplateModelException( "Iterator out of bounds" );\r
+ }\r
+\r
+ public boolean hasNext() {\r
+ return position<valuesCache.size() || iterator.hasNext();\r
+ }\r
+\r
+ public boolean isRewound() {\r
+ return position==0;\r
+ }\r
+\r
+ public TemplateModel next() throws TemplateModelException {\r
+ TemplateModel result;\r
+\r
+ if (hasNext()) {\r
+ result = get(position);\r
+ position++;\r
+ }\r
+ else\r
+ throw new TemplateModelException( "Iterator out of bounds" );\r
+\r
+ return result;\r
+ }\r
+\r
+ public void rewind() {\r
+ position=0;\r
+ }\r
+ }\r
+\r
+ private static class ListAdapter implements TemplateListModel {\r
+ List list;\r
+ List valuesCache;\r
+ int position;\r
+\r
+ private ListAdapter(List aList) {\r
+ list = aList;\r
+ valuesCache = new Vector();\r
+ position=0;\r
+ }\r
+\r
+ public boolean isEmpty() {\r
+ return list.isEmpty();\r
+ }\r
+\r
+ public TemplateModel get(int i) throws TemplateModelException {\r
+\r
+ if (i>=valuesCache.size() && i<list.size()) {\r
+ for(int j=valuesCache.size(); j<=i; j++) {\r
+ valuesCache.add(makeAdapter(list.get(j)));\r
+ }\r
+ }\r
+\r
+ if (i<valuesCache.size())\r
+ return (TemplateModel) valuesCache.get(i);\r
+ else\r
+ throw new TemplateModelException( "Iterator out of bounds" );\r
+ }\r
+\r
+ public boolean hasNext() {\r
+ return position<list.size();\r
+ }\r
+\r
+ public boolean isRewound() {\r
+ return position==0;\r
+ }\r
+\r
+ public TemplateModel next() throws TemplateModelException {\r
+ TemplateModel result;\r
+\r
+ if (hasNext()) {\r
+ result = get(position);\r
+ position++;\r
+ }\r
+ else {\r
+ throw new TemplateModelException( "Iterator out of bounds" );\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ public void rewind() {\r
+ position = 0;\r
+ }\r
+ }\r
+\r
+ private static class FunctionAdapter implements TemplateMethodModel {\r
+ Generator.GeneratorFunction function;\r
+\r
+ public FunctionAdapter(Generator.GeneratorFunction aFunction) {\r
+ function = aFunction;\r
+ }\r
+\r
+ public TemplateModel exec(List anArguments) throws TemplateModelException {\r
+ try {\r
+ return makeAdapter(function.perform(anArguments));\r
+ }\r
+ catch (Throwable t) {\r
+ throw new TemplateModelException(t.getMessage());\r
+ }\r
+ }\r
+\r
+ public boolean isEmpty() {\r
+ return false;\r
+ }\r
+\r
+ }\r
+\r
+ public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {\r
+ private FileTemplateCache templateCache;\r
+\r
+ public FreemarkerGeneratorLibrary(String aTemplateRoot) {\r
+ templateCache = new FileTemplateCache( aTemplateRoot+"/" );\r
+ templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);\r
+ }\r
+\r
+ public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {\r
+ Template template = (Template) templateCache.getItem(anIdentifier, "template");\r
+\r
+ if (template==null) {\r
+ throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier);\r
+ }\r
+\r
+ return new FreemarkerGenerator(template);\r
+ }\r
+ }\r
+\r
+ public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory {\r
+ private String basePath;\r
+\r
+ public FreemarkerGeneratorLibraryFactory(String aBasePath) {\r
+ basePath = aBasePath;\r
+ }\r
+\r
+ public GeneratorLibrary makeLibrary(String anInitializationString) {\r
+ return new FreemarkerGeneratorLibrary(basePath+anInitializationString);\r
+ };\r
+ }\r
+}\r
package mir.log;
+import java.io.*;
+
public class LoggerWrapper {
private Object object;
public final static int DEBUG_MESSAGE = 1;
warn("LoggerWrapper.message: Unknown message type ("+aType+") for message '" + aMessage + "'");
}
}
+
+ public PrintWriter asPrintWriter(int aMessageType) {
+ return new PrintWriter(new LoggerToWriterAdapter(this, aMessageType));
+ }
}
}\r
\r
\r
- public class RootSectionHandler implements XMLReader.SectionHandler {\r
+ public class RootSectionHandler extends XMLReader.AbstractSectionHandler {\r
private List producers;\r
\r
public RootSectionHandler(List aProducers) {\r
private final static String[] NODE_DEFINITION_REQUIRED_ATTRIBUTES = { NODE_DEFINITION_NAME_ATTRIBUTE };\r
private final static String[] NODE_DEFINITION_OPTIONAL_ATTRIBUTES = { };\r
\r
- public class ProducersSectionHandler implements XMLReader.SectionHandler {\r
+ public class ProducersSectionHandler extends XMLReader.AbstractSectionHandler {\r
private List producers;\r
private Set producerNames;\r
private String name;\r
}\r
}\r
\r
- public class ProducerSectionHandler implements XMLReader.SectionHandler {\r
+ public class ProducerSectionHandler extends XMLReader.AbstractSectionHandler {\r
private ProducerFactory producerFactory;\r
private String factoryName;\r
\r
private final static String[] PRODUCER_VERB_REQUIRED_ATTRIBUTES = { PRODUCER_VERB_NAME_ATTRIBUTE };\r
private final static String[] PRODUCER_VERB_OPTIONAL_ATTRIBUTES = { PRODUCER_VERB_DEFAULT_ATTRIBUTE, PRODUCER_VERB_DESCRIPTION_ATTRIBUTE };\r
\r
- public class ProducerVerbsSectionHandler implements XMLReader.SectionHandler {\r
+ public class ProducerVerbsSectionHandler extends XMLReader.AbstractSectionHandler {\r
private Map verbNodes;\r
private List verbs;\r
private String defaultVerb;\r
}\r
}\r
\r
- public class EmptySectionHandler implements XMLReader.SectionHandler {\r
+ public class EmptySectionHandler extends XMLReader.AbstractSectionHandler {\r
public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc {\r
throw new XMLReader.XMLReaderExc("No tags are allowed here");\r
}\r
}\r
}\r
\r
- public class MultiProducerNodeSectionHandler implements XMLReader.SectionHandler {\r
+ public class MultiProducerNodeSectionHandler extends XMLReader.AbstractSectionHandler {\r
private Map nodeParameters;\r
private Set validNodeParameters;\r
private String currentNodeParameter;\r
}\r
}\r
\r
- public class ProducerNodeSectionHandler implements XMLReader.SectionHandler {\r
+ public class ProducerNodeSectionHandler extends XMLReader.AbstractSectionHandler {\r
private CompositeProducerNode producerNode;\r
private ProducerNodeBuilder currentBuilder;\r
private String scriptedNodeName;\r
}\r
}\r
\r
- public class NodeDefinitionSectionHandler implements XMLReader.SectionHandler {\r
+ public class NodeDefinitionSectionHandler extends XMLReader.AbstractSectionHandler {\r
private ScriptedProducerNodeDefinition nodeDefinition;\r
private ProducerNode body;\r
private Map stringParameters;\r
private final static String[] NODE_DEFINITION_PARAMETER_OPTIONAL_ATTRIBUTES = { NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE };\r
private final static String[] NODE_DEFINITION_NODE_PARAMETER_OPTIONAL_ATTRIBUTES = { };\r
\r
- public class NodeDefinitionParametersSectionHandler implements XMLReader.SectionHandler {\r
+ public class NodeDefinitionParametersSectionHandler extends XMLReader.AbstractSectionHandler {\r
private Map nodeParameters;\r
private Map stringParameters;\r
private Map integerParameters;\r
* Copyright: Copyright (c) 2001, 2002
* Company: Mir-coders group
* @author idfx, the Mir-coders group
- * @version $Id: AbstractServlet.java,v 1.21 2003/01/28 23:37:08 idfx Exp $
+ * @version $Id: AbstractServlet.java,v 1.22 2003/02/20 16:05:33 zapata Exp $
*/
public abstract class AbstractServlet extends HttpServlet {
protected static String lang;
- //protected static Logfile theLog;
- protected LoggerWrapper logger;
- protected MirPropertiesConfiguration configuration;
-
+ protected LoggerWrapper logger;
+ protected MirPropertiesConfiguration configuration;
+
/**
* Constructor for AbstractServlet.
*/
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
- MirPropertiesConfiguration.setContext(config.getServletContext());
+ MirPropertiesConfiguration.setContext(config.getServletContext());
try {
configuration = MirPropertiesConfiguration.instance();
} catch (PropertiesConfigExc e) {
throw new ServletException(e);
}
-
+
String dbUser=configuration.getString("Database.Username");
String dbPassword=configuration.getString("Database.Password");
String dbHost=configuration.getString("Database.Host");
String dbAdapName=configuration.getString("Database.Adaptor");
-
+ String dbName=configuration.getString("Database.Name");
+
DatabaseAdaptor adaptor;
try {
adaptor = (DatabaseAdaptor)Class.forName(dbAdapName).newInstance();
throw new ServletException("Could not load DB adapator: "+
e.toString());
}
-
- String min,max,log,reset,dbname,dblogfile;
-
- min=configuration.getString("Database.poolMin");
- System.out.println(min);
- max=configuration.getString("Database.poolMax");
- System.out.println(max);
- dbname=configuration.getString("Database.Name");
- System.out.println(dbname);
- log=configuration.getStringWithHome("Database.PoolLog");
- System.out.println(log);
- reset=configuration.getString("Database.poolResetTime");
- System.out.println(reset);
- dblogfile=configuration.getStringWithHome("Database.Logfile");
- System.out.println(dblogfile);
-
+
String dbDriver;
String dbUrl;
try{
}
JDBCPoolMetaData meta = new JDBCPoolMetaData();
- meta.setDbname(dbname);
+ meta.setDbname(dbName);
meta.setDriver(dbDriver);
meta.setURL(dbUrl);
meta.setUserName(dbUser);
meta.setCacheEnabled(false);
meta.setCacheSize(15);
meta.setDebugging(false);
- meta.setLogFile(dblogfile+".pool");
+// meta.setLogFile(dblogfile+".pool");
SQLManager manager = SQLManager.getInstance();
JDBCPool pool = null;
\r
import java.io.IOException;\r
import java.io.PrintWriter;\r
-import java.util.ArrayList;\r
+import java.util.List;\r
import java.util.HashMap;\r
import java.util.Locale;\r
\r
\r
try {\r
HTTPRequestParser parser;\r
- ArrayList theFieldList;\r
- System.out.println("using charset: " + req.getParameter("charset"));\r
- System.out.println("using method: " + req.getParameter("do"));\r
+ List theFieldList;\r
+\r
+ logger.debug("using charset: " + req.getParameter("charset"));\r
+ logger.debug("using method: " + req.getParameter("do"));\r
if (req.getParameter("charset") != null) {\r
parser = new HTTPRequestParser(req, req.getParameter("charset"));\r
- System.out.println("using charset: " + req.getParameter("charset"));\r
- System.out.println("original charset: " + req.getCharacterEncoding());\r
+ logger.debug("using charset: " + req.getParameter("charset"));\r
+ logger.debug("original charset: " + req.getCharacterEncoding());\r
}\r
else {\r
parser = new HTTPRequestParser(req);\r
}\r
\r
-\r
theFieldList = theStorage.getFields();\r
\r
HashMap withValues = new HashMap();\r
-/*
- * 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</b>
- *
- *
- * @version 28.6.199
- * @author RK
- */
-
-public final class ServletModuleException extends Exception
-{
- public ServletModuleException(String msg) {
- super(msg);
- }
-}
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.servlet;\r
+\r
+\r
+/*\r
+ * ServletModuleException -\r
+ * wird vom ServletModule geschmissen</b>\r
+ *\r
+ *\r
+ * @version 28.6.199\r
+ * @author RK\r
+ */\r
+\r
+public final class ServletModuleException extends Exception\r
+{\r
+ public ServletModuleException(String msg) {\r
+ super(msg);\r
+ }\r
+}\r
+\r
-/*
- * 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 <code>Database.Logfile</code>,
- * <code>Database.Username</code>,<code>Database.Password</code>,
- * <code>Database.Host</code> und <code>Database.Adaptor</code>
- * 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 <code>PKEY</code>
- * @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 = "<unsupported value>";
- 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 <i>sql</i> 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);
- }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.io.IOException;\r
+import java.io.InputStreamReader;\r
+\r
+import java.sql.Connection;\r
+import java.sql.PreparedStatement;\r
+import java.sql.ResultSet;\r
+import java.sql.ResultSetMetaData;\r
+import java.sql.SQLException;\r
+import java.sql.Statement;\r
+import java.sql.Timestamp;\r
+\r
+import java.text.ParseException;\r
+import java.text.SimpleDateFormat;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Calendar;\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+\r
+import com.codestudio.util.SQLManager;\r
+\r
+import freemarker.template.SimpleHash;\r
+import freemarker.template.SimpleList;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityList;\r
+import mir.entity.StorableObjectEntity;\r
+\r
+import mir.log.LoggerWrapper;\r
+\r
+import mir.misc.HTMLTemplateProcessor;\r
+import mir.misc.StringUtil;\r
+\r
+import mir.storage.store.ObjectStore;\r
+import mir.storage.store.StorableObject;\r
+import mir.storage.store.StoreContainerType;\r
+import mir.storage.store.StoreIdentifier;\r
+import mir.storage.store.StoreUtil;\r
+\r
+import mir.util.JDBCStringRoutines;\r
+\r
+\r
+/**\r
+ * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.\r
+ * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.\r
+ * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.\r
+ * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten\r
+ * Treiber, Host, User und Passwort, ueber den der Zugriff auf die\r
+ * Datenbank erfolgt.\r
+ *\r
+ * @version $Id: Database.java,v 1.33 2003/02/20 16:05:33 zapata Exp $\r
+ * @author rk\r
+ *\r
+ */\r
+public class Database implements StorageObject {\r
+ private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;\r
+ private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;\r
+\r
+\r
+ private static SimpleHash POPUP_EMPTYLINE = new SimpleHash();\r
+ protected static final ObjectStore o_store = ObjectStore.getInstance();\r
+ private static final int _millisPerHour = 60 * 60 * 1000;\r
+ private static final int _millisPerMinute = 60 * 1000;\r
+\r
+ static {\r
+ // always same object saves a little space\r
+ POPUP_EMPTYLINE.put("key", "");\r
+ POPUP_EMPTYLINE.put("value", "--");\r
+ }\r
+\r
+ protected LoggerWrapper logger;\r
+ protected MirPropertiesConfiguration configuration;\r
+ protected String theTable;\r
+ protected String theCoreTable = null;\r
+ protected String thePKeyName = "id";\r
+ protected int thePKeyType;\r
+ protected int thePKeyIndex;\r
+ protected boolean evaluatedMetaData = false;\r
+ protected ArrayList metadataFields;\r
+ protected ArrayList metadataLabels;\r
+ protected ArrayList metadataNotNullFields;\r
+ protected int[] metadataTypes;\r
+ protected Class theEntityClass;\r
+ protected StorageObject myselfDatabase;\r
+ protected SimpleList popupCache = null;\r
+ protected boolean hasPopupCache = false;\r
+ protected SimpleHash hashCache = null;\r
+ protected boolean hasTimestamp = true;\r
+ private String database_driver;\r
+ private String database_url;\r
+ private int defaultLimit;\r
+ protected DatabaseAdaptor theAdaptor;\r
+ private SimpleDateFormat _dateFormatterOut =\r
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
+ private SimpleDateFormat _dateFormatterIn =\r
+ new SimpleDateFormat("yyyy-MM-dd HH:mm");\r
+ private Calendar _cal = new GregorianCalendar();\r
+\r
+ /**\r
+ * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.\r
+ * Aus diesem file werden <code>Database.Logfile</code>,\r
+ * <code>Database.Username</code>,<code>Database.Password</code>,\r
+ * <code>Database.Host</code> und <code>Database.Adaptor</code>\r
+ * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank\r
+ * erzeugt.\r
+ *\r
+ * @param String confFilename Dateiname der Konfigurationsdatei\r
+ */\r
+ public Database() throws StorageObjectFailure {\r
+ try {\r
+ configuration = MirPropertiesConfiguration.instance();\r
+ }\r
+ catch (PropertiesConfigExc e) {\r
+ throw new StorageObjectFailure(e);\r
+ }\r
+ logger = new LoggerWrapper("Database");\r
+\r
+ String theAdaptorName = configuration.getString("Database.Adaptor");\r
+ defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));\r
+\r
+ try {\r
+ theEntityClass = GENERIC_ENTITY_CLASS;\r
+ theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance();\r
+ }\r
+ catch (Throwable e) {\r
+ logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());\r
+ throw new StorageObjectFailure("Error in Database() constructor.", e);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt\r
+ * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,\r
+ * wird eine mir.entity.GenericEntity erzeugt.\r
+ *\r
+ * @return Class-Objekt der Entity\r
+ */\r
+ public java.lang.Class getEntityClass() {\r
+ return theEntityClass;\r
+ }\r
+\r
+ /**\r
+ * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also\r
+ * wieviel Datens?tze per Default selektiert werden.\r
+ *\r
+ * @return Standard-Anzahl der Datens?tze\r
+ */\r
+ public int getLimit() {\r
+ return defaultLimit;\r
+ }\r
+\r
+ /**\r
+ * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von\r
+ * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>\r
+ * @return Name des Primary-Keys\r
+ */\r
+ public String getIdName() {\r
+ return thePKeyName;\r
+ }\r
+\r
+ /**\r
+ * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.\r
+ *\r
+ * @return Name der Tabelle\r
+ */\r
+ public String getTableName() {\r
+ return theTable;\r
+ }\r
+\r
+ /*\r
+ * Dient dazu vererbte Tabellen bei objectrelationalen DBMS\r
+ * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet\r
+ * wird.\r
+ * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst\r
+ * the Table\r
+ */\r
+ public String getCoreTable() {\r
+ if (theCoreTable != null) {\r
+ return theCoreTable;\r
+ } else {\r
+ return theTable;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)\r
+ * @return int-Array mit den Typen der Felder\r
+ * @exception StorageObjectException\r
+ */\r
+ public int[] getTypes() throws StorageObjectFailure {\r
+ if (metadataTypes == null) {\r
+ get_meta_data();\r
+ }\r
+\r
+ return metadataTypes;\r
+ }\r
+\r
+ /**\r
+ * Liefert eine Liste der Labels der Tabellenfelder\r
+ * @return ArrayListe mit Labeln\r
+ * @exception StorageObjectException\r
+ */\r
+ public List getLabels() throws StorageObjectFailure {\r
+ if (metadataLabels == null) {\r
+ get_meta_data();\r
+ }\r
+\r
+ return metadataLabels;\r
+ }\r
+\r
+ /**\r
+ * Liefert eine Liste der Felder der Tabelle\r
+ * @return ArrayList mit Feldern\r
+ * @exception StorageObjectException\r
+ */\r
+ public List getFields() throws StorageObjectFailure {\r
+ if (metadataFields == null) {\r
+ get_meta_data();\r
+ }\r
+\r
+ return metadataFields;\r
+ }\r
+\r
+ /*\r
+ * Gets value out of ResultSet according to type and converts to String\r
+ * @param inValue Wert aus ResultSet.\r
+ * @param aType Datenbanktyp.\r
+ * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich\r
+ * dann /unsupported value/\r
+ */\r
+ private String getValueAsString(ResultSet rs, int valueIndex, int aType)\r
+ throws StorageObjectFailure {\r
+ String outValue = null;\r
+\r
+ if (rs != null) {\r
+ try {\r
+ switch (aType) {\r
+ case java.sql.Types.BIT:\r
+ outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";\r
+\r
+ break;\r
+\r
+ case java.sql.Types.INTEGER:\r
+ case java.sql.Types.SMALLINT:\r
+ case java.sql.Types.TINYINT:\r
+ case java.sql.Types.BIGINT:\r
+\r
+ int out = rs.getInt(valueIndex);\r
+\r
+ if (!rs.wasNull()) {\r
+ outValue = new Integer(out).toString();\r
+ }\r
+\r
+ break;\r
+\r
+ case java.sql.Types.NUMERIC:\r
+\r
+ /** @todo Numeric can be float or double depending upon\r
+ * metadata.getScale() / especially with oracle */\r
+ long outl = rs.getLong(valueIndex);\r
+\r
+ if (!rs.wasNull()) {\r
+ outValue = new Long(outl).toString();\r
+ }\r
+\r
+ break;\r
+\r
+ case java.sql.Types.REAL:\r
+\r
+ float tempf = rs.getFloat(valueIndex);\r
+\r
+ if (!rs.wasNull()) {\r
+ tempf *= 10;\r
+ tempf += 0.5;\r
+\r
+ int tempf_int = (int) tempf;\r
+ tempf = (float) tempf_int;\r
+ tempf /= 10;\r
+ outValue = "" + tempf;\r
+ outValue = outValue.replace('.', ',');\r
+ }\r
+\r
+ break;\r
+\r
+ case java.sql.Types.DOUBLE:\r
+\r
+ double tempd = rs.getDouble(valueIndex);\r
+\r
+ if (!rs.wasNull()) {\r
+ tempd *= 10;\r
+ tempd += 0.5;\r
+\r
+ int tempd_int = (int) tempd;\r
+ tempd = (double) tempd_int;\r
+ tempd /= 10;\r
+ outValue = "" + tempd;\r
+ outValue = outValue.replace('.', ',');\r
+ }\r
+\r
+ break;\r
+\r
+ case java.sql.Types.CHAR:\r
+ case java.sql.Types.VARCHAR:\r
+ case java.sql.Types.LONGVARCHAR:\r
+ outValue = rs.getString(valueIndex);\r
+\r
+ break;\r
+\r
+ case java.sql.Types.LONGVARBINARY:\r
+ outValue = rs.getString(valueIndex);\r
+\r
+ break;\r
+\r
+ case java.sql.Types.TIMESTAMP:\r
+\r
+ // it's important to use Timestamp here as getting it\r
+ // as a string is undefined and is only there for debugging\r
+ // according to the API. we can make it a string through formatting.\r
+ // -mh\r
+ Timestamp timestamp = (rs.getTimestamp(valueIndex));\r
+\r
+ if (!rs.wasNull()) {\r
+ java.util.Date date = new java.util.Date(timestamp.getTime());\r
+ outValue = _dateFormatterOut.format(date);\r
+ _cal.setTime(date);\r
+\r
+ int offset =\r
+ _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET);\r
+ String tzOffset =\r
+ StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2);\r
+ outValue = outValue + "+" + tzOffset;\r
+ }\r
+\r
+ break;\r
+\r
+ default:\r
+ outValue = "<unsupported value>";\r
+ logger.warn( "Unsupported Datatype: at " + valueIndex + " (" + aType + ")");\r
+ }\r
+ } catch (SQLException e) {\r
+ throw new StorageObjectFailure("Could not get Value out of Resultset -- ",\r
+ e);\r
+ }\r
+ }\r
+\r
+ return outValue;\r
+ }\r
+\r
+ /*\r
+ * select-Operator um einen Datensatz zu bekommen.\r
+ * @param id Primaerschluessel des Datensatzes.\r
+ * @return liefert EntityObject des gefundenen Datensatzes oder null.\r
+ */\r
+ public Entity selectById(String id) throws StorageObjectExc {\r
+ if ((id == null) || id.equals("")) {\r
+ throw new StorageObjectExc("Database.selectById: Missing id");\r
+ }\r
+\r
+ // ask object store for object\r
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+ String uniqueId = id;\r
+\r
+ if (theEntityClass.equals(StorableObjectEntity.class)) {\r
+ uniqueId += ("@" + theTable);\r
+ }\r
+\r
+ StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);\r
+ logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());\r
+\r
+ Entity hit = (Entity) o_store.use(search_sid);\r
+\r
+ if (hit != null) {\r
+ return hit;\r
+ }\r
+ }\r
+\r
+ Statement stmt = null;\r
+ Connection con = getPooledCon();\r
+ Entity returnEntity = null;\r
+\r
+ try {\r
+ ResultSet rs;\r
+\r
+ /** @todo better prepared statement */\r
+ String selectSql =\r
+ "select * from " + theTable + " where " + thePKeyName + "=" + id;\r
+ stmt = con.createStatement();\r
+ rs = executeSql(stmt, selectSql);\r
+\r
+ if (rs != null) {\r
+ if (evaluatedMetaData == false) {\r
+ evalMetaData(rs.getMetaData());\r
+ }\r
+\r
+ if (rs.next()) {\r
+ returnEntity = makeEntityFromResultSet(rs);\r
+ }\r
+ else {\r
+ logger.debug("No data for id: " + id + " in table " + theTable);\r
+ }\r
+\r
+ rs.close();\r
+ }\r
+ else {\r
+ logger.debug("No Data for Id " + id + " in Table " + theTable);\r
+ }\r
+ }\r
+ catch (SQLException sqe) {\r
+ throwSQLException(sqe, "selectById");\r
+ return null;\r
+ }\r
+ catch (NumberFormatException e) {\r
+ logger.error("ID is no number: " + id);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ return returnEntity;\r
+ }\r
+\r
+ /**\r
+ * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.\r
+ * @param key Datenbankfeld der Bedingung.\r
+ * @param value Wert die der key anehmen muss.\r
+ * @return EntityList mit den gematchten Entities\r
+ */\r
+ public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {\r
+ return selectByFieldValue(aField, aValue, 0);\r
+ }\r
+\r
+ /**\r
+ * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.\r
+ * @param key Datenbankfeld der Bedingung.\r
+ * @param value Wert die der key anehmen muss.\r
+ * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.\r
+ * @return EntityList mit den gematchten Entities\r
+ */\r
+ public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {\r
+ return selectByWhereClause(aField + "=" + aValue, offset);\r
+ }\r
+\r
+ /**\r
+ * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+ * Also offset wird der erste Datensatz genommen.\r
+ *\r
+ * @param wc where-Clause\r
+ * @return EntityList mit den gematchten Entities\r
+ * @exception StorageObjectException\r
+ */\r
+ public EntityList selectByWhereClause(String where)\r
+ throws StorageObjectFailure {\r
+ return selectByWhereClause(where, 0);\r
+ }\r
+\r
+ /**\r
+ * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+ * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
+ *\r
+ * @param wc where-Clause\r
+ * @param offset ab welchem Datensatz.\r
+ * @return EntityList mit den gematchten Entities\r
+ * @exception StorageObjectException\r
+ */\r
+ public EntityList selectByWhereClause(String whereClause, int offset)\r
+ throws StorageObjectFailure {\r
+ return selectByWhereClause(whereClause, null, offset);\r
+ }\r
+\r
+ /**\r
+ * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+ * Also offset wird der erste Datensatz genommen.\r
+ * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
+ *\r
+ * @param wc where-Clause\r
+ * @param ob orderBy-Clause\r
+ * @return EntityList mit den gematchten Entities\r
+ * @exception StorageObjectException\r
+ */\r
+ public EntityList selectByWhereClause(String where, String order)\r
+ throws StorageObjectFailure {\r
+ return selectByWhereClause(where, order, 0);\r
+ }\r
+\r
+ /**\r
+ * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+ * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
+ *\r
+ * @param wc where-Clause\r
+ * @param ob orderBy-Clause\r
+ * @param offset ab welchem Datensatz\r
+ * @return EntityList mit den gematchten Entities\r
+ * @exception StorageObjectException\r
+ */\r
+ public EntityList selectByWhereClause(String whereClause, String orderBy,\r
+ int offset) throws StorageObjectFailure {\r
+ return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);\r
+ }\r
+\r
+ /**\r
+ * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+ * @param wc where-Clause\r
+ * @param ob orderBy-Clause\r
+ * @param offset ab welchem Datensatz\r
+ * @param limit wieviele Datens?tze\r
+ * @return EntityList mit den gematchten Entities\r
+ * @exception StorageObjectException\r
+ */\r
+ public EntityList selectByWhereClause(String wc, String ob, int offset,\r
+ int limit) throws StorageObjectFailure {\r
+ // check o_store for entitylist\r
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+ StoreIdentifier search_sid =\r
+ new StoreIdentifier(theEntityClass,\r
+ StoreContainerType.STOC_TYPE_ENTITYLIST,\r
+ StoreUtil.getEntityListUniqueIdentifierFor(theTable, wc, ob, offset,\r
+ limit));\r
+ EntityList hit = (EntityList) o_store.use(search_sid);\r
+\r
+ if (hit != null) {\r
+ logger.debug("CACHE (hit): " + search_sid.toString());\r
+\r
+ return hit;\r
+ }\r
+ }\r
+\r
+ // local\r
+ EntityList theReturnList = null;\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ ResultSet rs;\r
+ int offsetCount = 0;\r
+ int count = 0;\r
+\r
+ // build sql-statement\r
+\r
+ /** @todo count sql string should only be assembled if we really count\r
+ * see below at the end of method //rk */\r
+ if ((wc != null) && (wc.length() == 0)) {\r
+ wc = null;\r
+ }\r
+\r
+ StringBuffer countSql =\r
+ new StringBuffer("select count(*) from ").append(theTable);\r
+ StringBuffer selectSql =\r
+ new StringBuffer("select * from ").append(theTable);\r
+\r
+ if (wc != null) {\r
+ selectSql.append(" where ").append(wc);\r
+ countSql.append(" where ").append(wc);\r
+ }\r
+\r
+ if ((ob != null) && !(ob.length() == 0)) {\r
+ selectSql.append(" order by ").append(ob);\r
+ }\r
+\r
+ if (theAdaptor.hasLimit()) {\r
+ if ((limit > -1) && (offset > -1)) {\r
+ selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);\r
+ }\r
+ }\r
+\r
+ // execute sql\r
+ try {\r
+ con = getPooledCon();\r
+ stmt = con.createStatement();\r
+\r
+ // selecting...\r
+ rs = executeSql(stmt, selectSql.toString());\r
+\r
+ if (rs != null) {\r
+ if (!evaluatedMetaData) {\r
+ evalMetaData(rs.getMetaData());\r
+ }\r
+\r
+ theReturnList = new EntityList();\r
+\r
+ Entity theResultEntity;\r
+\r
+ while (rs.next()) {\r
+ theResultEntity = makeEntityFromResultSet(rs);\r
+ theReturnList.add(theResultEntity);\r
+ offsetCount++;\r
+ }\r
+\r
+ rs.close();\r
+ }\r
+\r
+ // making entitylist infos\r
+ if (!(theAdaptor.hasLimit())) {\r
+ count = offsetCount;\r
+ }\r
+\r
+ if (theReturnList != null) {\r
+ // now we decide if we have to know an overall count...\r
+ count = offsetCount;\r
+\r
+ if ((limit > -1) && (offset > -1)) {\r
+ if (offsetCount == limit) {\r
+ /** @todo counting should be deffered to entitylist\r
+ * getSize() should be used */\r
+ rs = executeSql(stmt, countSql.toString());\r
+\r
+ if (rs != null) {\r
+ if (rs.next()) {\r
+ count = rs.getInt(1);\r
+ }\r
+\r
+ rs.close();\r
+ }\r
+ else {\r
+ logger.error("Could not count: " + countSql);\r
+ }\r
+ }\r
+ }\r
+\r
+ theReturnList.setCount(count);\r
+ theReturnList.setOffset(offset);\r
+ theReturnList.setWhere(wc);\r
+ theReturnList.setOrder(ob);\r
+ theReturnList.setStorage(this);\r
+ theReturnList.setLimit(limit);\r
+\r
+ if (offset >= limit) {\r
+ theReturnList.setPrevBatch(offset - limit);\r
+ }\r
+\r
+ if ((offset + offsetCount) < count) {\r
+ theReturnList.setNextBatch(offset + limit);\r
+ }\r
+\r
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+ StoreIdentifier sid = theReturnList.getStoreIdentifier();\r
+ logger.debug("CACHE (add): " + sid.toString());\r
+ o_store.add(sid);\r
+ }\r
+ }\r
+ } catch (SQLException sqe) {\r
+ throwSQLException(sqe, "selectByWhereClause");\r
+ } finally {\r
+ try {\r
+ if (con != null) {\r
+ freeConnection(con, stmt);\r
+ }\r
+ } catch (Throwable t) {\r
+ }\r
+ }\r
+\r
+ return theReturnList;\r
+ }\r
+\r
+ /**\r
+ * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.\r
+ *\r
+ * @param rs Das ResultSetObjekt.\r
+ * @return Entity Die Entity.\r
+ */\r
+ private Entity makeEntityFromResultSet(ResultSet rs)\r
+ throws StorageObjectFailure {\r
+ /** @todo OS: get Pkey from ResultSet and consult ObjectStore */\r
+ HashMap theResultHash = new HashMap();\r
+ String theResult = null;\r
+ int theType;\r
+ Entity returnEntity = null;\r
+\r
+ try {\r
+ int size = metadataFields.size();\r
+\r
+ for (int i = 0; i < size; i++) {\r
+ // alle durchlaufen bis nix mehr da\r
+ theType = metadataTypes[i];\r
+\r
+ if (theType == java.sql.Types.LONGVARBINARY) {\r
+ InputStreamReader is =\r
+ (InputStreamReader) rs.getCharacterStream(i + 1);\r
+\r
+ if (is != null) {\r
+ char[] data = new char[32768];\r
+ StringBuffer theResultString = new StringBuffer();\r
+ int len;\r
+\r
+ while ((len = is.read(data)) > 0) {\r
+ theResultString.append(data, 0, len);\r
+ }\r
+\r
+ is.close();\r
+ theResult = theResultString.toString();\r
+ } else {\r
+ theResult = null;\r
+ }\r
+ } else {\r
+ theResult = getValueAsString(rs, (i + 1), theType);\r
+ }\r
+\r
+ if (theResult != null) {\r
+ theResultHash.put(metadataFields.get(i), theResult);\r
+ }\r
+ }\r
+\r
+ if (theEntityClass != null) {\r
+ returnEntity = (Entity) theEntityClass.newInstance();\r
+ returnEntity.setValues(theResultHash);\r
+ returnEntity.setStorage(myselfDatabase);\r
+\r
+ if (returnEntity instanceof StorableObject) {\r
+ logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);\r
+ o_store.add(((StorableObject) returnEntity).getStoreIdentifier());\r
+ }\r
+ } else {\r
+ throwStorageObjectException("Internal Error: theEntityClass not set!");\r
+ }\r
+ } catch (IllegalAccessException e) {\r
+ throwStorageObjectException("No access! -- " + e.getMessage());\r
+ } catch (IOException e) {\r
+ throwStorageObjectException("IOException! -- " + e.getMessage());\r
+ } catch (InstantiationException e) {\r
+ throwStorageObjectException("No Instatiation! -- " + e.getMessage());\r
+ } catch (SQLException sqe) {\r
+ throwSQLException(sqe, "makeEntityFromResultSet");\r
+\r
+ return null;\r
+ }\r
+\r
+ return returnEntity;\r
+ }\r
+\r
+ /**\r
+ * insert-Operator: f?gt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE\r
+ * wird automatisch mit dem aktuellen Datum gefuellt.\r
+ *\r
+ * @param theEntity\r
+ * @return der Wert des Primary-keys der eingef?gten Entity\r
+ */\r
+ public String insert(Entity theEntity) throws StorageObjectFailure {\r
+ //cache\r
+ invalidatePopupCache();\r
+\r
+ // invalidating all EntityLists corresponding with theEntityClass\r
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+ StoreContainerType stoc_type =\r
+ StoreContainerType.valueOf(theEntityClass,\r
+ StoreContainerType.STOC_TYPE_ENTITYLIST);\r
+ o_store.invalidate(stoc_type);\r
+ }\r
+\r
+ String returnId = null;\r
+ Connection con = null;\r
+ PreparedStatement pstmt = null;\r
+\r
+ try {\r
+ List streamedInput = theEntity.streamedInput();\r
+ StringBuffer f = new StringBuffer();\r
+ StringBuffer v = new StringBuffer();\r
+ String aField;\r
+ String aValue;\r
+ boolean firstField = true;\r
+\r
+ // make sql-string\r
+ for (int i = 0; i < getFields().size(); i++) {\r
+ aField = (String) getFields().get(i);\r
+\r
+ if (!aField.equals(thePKeyName)) {\r
+ aValue = null;\r
+\r
+ // exceptions\r
+ if (aField.equals("webdb_create") ||\r
+ aField.equals("webdb_lastchange")) {\r
+ aValue = "NOW()";\r
+ } else {\r
+ if ((streamedInput != null) && streamedInput.contains(aField)) {\r
+ aValue = "?";\r
+ } else {\r
+ if (theEntity.hasValueForField(aField)) {\r
+ aValue =\r
+ "'" +\r
+ JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(\r
+ aField)) + "'";\r
+ }\r
+ }\r
+ }\r
+\r
+ // wenn Wert gegeben, dann einbauen\r
+ if (aValue != null) {\r
+ if (firstField == false) {\r
+ f.append(",");\r
+ v.append(",");\r
+ }\r
+ else {\r
+ firstField = false;\r
+ }\r
+\r
+ f.append(aField);\r
+ v.append(aValue);\r
+ }\r
+ }\r
+ }\r
+ // end for\r
+\r
+ // insert into db\r
+ StringBuffer sqlBuf =\r
+ new StringBuffer("insert into ").append(theTable).append("(").append(f)\r
+ .append(") values (").append(v).append(")");\r
+ String sql = sqlBuf.toString();\r
+\r
+ //theLog.printInfo("INSERT: " + sql);\r
+ con = getPooledCon();\r
+ con.setAutoCommit(false);\r
+ pstmt = con.prepareStatement(sql);\r
+\r
+ if (streamedInput != null) {\r
+ for (int i = 0; i < streamedInput.size(); i++) {\r
+ String inputString =\r
+ (String) theEntity.getValue((String) streamedInput.get(i));\r
+ pstmt.setBytes(i + 1, inputString.getBytes());\r
+ }\r
+ }\r
+\r
+ int ret = pstmt.executeUpdate();\r
+\r
+ if (ret == 0) {\r
+ //insert failed\r
+ return null;\r
+ }\r
+\r
+ pstmt =\r
+ con.prepareStatement(theAdaptor.getLastInsertSQL(\r
+ (Database) myselfDatabase));\r
+\r
+ ResultSet rs = pstmt.executeQuery();\r
+ rs.next();\r
+ returnId = rs.getString(1);\r
+ theEntity.setId(returnId);\r
+ }\r
+ catch (SQLException sqe) {\r
+ throwSQLException(sqe, "insert");\r
+ }\r
+ finally {\r
+ try {\r
+ con.setAutoCommit(true);\r
+ }\r
+ catch (Exception e) {\r
+ }\r
+\r
+ freeConnection(con, pstmt);\r
+ }\r
+\r
+ /** @todo store entity in o_store */\r
+ return returnId;\r
+ }\r
+\r
+ /**\r
+ * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE\r
+ * wird automatisch mit dem aktuellen Datum gefuellt.\r
+ *\r
+ * @param theEntity\r
+ */\r
+ public void update(Entity theEntity) throws StorageObjectFailure {\r
+ Connection con = null;\r
+ PreparedStatement pstmt = null;\r
+\r
+ /** @todo this is stupid: why do we prepare statement, when we\r
+ * throw it away afterwards. should be regular statement\r
+ * update/insert could better be one routine called save()\r
+ * that chooses to either insert or update depending if we\r
+ * have a primary key in the entity. i don't know if we\r
+ * still need the streamed input fields. // rk */\r
+ /** @todo extension: check if Entity did change, otherwise we don't need\r
+ * the roundtrip to the database */\r
+ /** invalidating corresponding entitylists in o_store*/\r
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+ StoreContainerType stoc_type =\r
+ StoreContainerType.valueOf(theEntityClass,\r
+ StoreContainerType.STOC_TYPE_ENTITYLIST);\r
+ o_store.invalidate(stoc_type);\r
+ }\r
+\r
+ List streamedInput = theEntity.streamedInput();\r
+ String id = theEntity.getId();\r
+ String aField;\r
+ StringBuffer fv = new StringBuffer();\r
+ boolean firstField = true;\r
+\r
+ //cache\r
+ invalidatePopupCache();\r
+\r
+ // build sql statement\r
+ for (int i = 0; i < getFields().size(); i++) {\r
+ aField = (String) metadataFields.get(i);\r
+\r
+ // only normal cases\r
+ if ( !(aField.equals(thePKeyName) ||\r
+ aField.equals("webdb_create") ||\r
+ aField.equals("webdb_lastchange") ||\r
+ ((streamedInput != null) && streamedInput.contains(aField)))) {\r
+ if (theEntity.hasValueForField(aField)) {\r
+ if (firstField == false) {\r
+ fv.append(", ");\r
+ }\r
+ else {\r
+ firstField = false;\r
+ }\r
+\r
+ fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");\r
+\r
+ // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");\r
+ }\r
+ }\r
+ }\r
+\r
+ StringBuffer sql =\r
+ new StringBuffer("update ").append(theTable).append(" set ").append(fv);\r
+\r
+ // exceptions\r
+ if (metadataFields.contains("webdb_lastchange")) {\r
+ sql.append(",webdb_lastchange=NOW()");\r
+ }\r
+\r
+ // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm\r
+ // format so anything extra will be ignored. -mh\r
+ if (metadataFields.contains("webdb_create") &&\r
+ theEntity.hasValueForField("webdb_create")) {\r
+ // minimum of 10 (yyyy-mm-dd)...\r
+ if (theEntity.getValue("webdb_create").length() >= 10) {\r
+ String dateString = theEntity.getValue("webdb_create");\r
+\r
+ // if only 10, then add 00:00 so it doesn't throw a ParseException\r
+ if (dateString.length() == 10) {\r
+ dateString = dateString + " 00:00";\r
+ }\r
+\r
+ // TimeStamp stuff\r
+ try {\r
+ java.util.Date d = _dateFormatterIn.parse(dateString);\r
+ Timestamp tStamp = new Timestamp(d.getTime());\r
+ sql.append(",webdb_create='" + tStamp.toString() + "'");\r
+ } catch (ParseException e) {\r
+ throw new StorageObjectFailure(e);\r
+ }\r
+ }\r
+ }\r
+\r
+ if (streamedInput != null) {\r
+ for (int i = 0; i < streamedInput.size(); i++) {\r
+ sql.append(",").append(streamedInput.get(i)).append("=?");\r
+ }\r
+ }\r
+\r
+ sql.append(" where id=").append(id);\r
+\r
+ //theLog.printInfo("UPDATE: " + sql);\r
+ // execute sql\r
+ try {\r
+ con = getPooledCon();\r
+ con.setAutoCommit(false);\r
+ pstmt = con.prepareStatement(sql.toString());\r
+\r
+ if (streamedInput != null) {\r
+ for (int i = 0; i < streamedInput.size(); i++) {\r
+ String inputString =\r
+ theEntity.getValue((String) streamedInput.get(i));\r
+ pstmt.setBytes(i + 1, inputString.getBytes());\r
+ }\r
+ }\r
+\r
+ pstmt.executeUpdate();\r
+ } catch (SQLException sqe) {\r
+ throwSQLException(sqe, "update");\r
+ } finally {\r
+ try {\r
+ con.setAutoCommit(true);\r
+ } catch (Exception e) {\r
+ ;\r
+ }\r
+\r
+ freeConnection(con, pstmt);\r
+ }\r
+ }\r
+\r
+ /*\r
+ * delete-Operator\r
+ * @param id des zu loeschenden Datensatzes\r
+ * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.\r
+ */\r
+ public boolean delete(String id) throws StorageObjectFailure {\r
+ invalidatePopupCache();\r
+\r
+ // ostore send notification\r
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+ String uniqueId = id;\r
+\r
+ if (theEntityClass.equals(StorableObjectEntity.class)) {\r
+ uniqueId += ("@" + theTable);\r
+ }\r
+\r
+ logger.debug("CACHE: (del) " + id);\r
+\r
+ StoreIdentifier search_sid =\r
+ new StoreIdentifier(theEntityClass,\r
+ StoreContainerType.STOC_TYPE_ENTITY, uniqueId);\r
+ o_store.invalidate(search_sid);\r
+ }\r
+\r
+ /** @todo could be prepared Statement */\r
+ Statement stmt = null;\r
+ Connection con = null;\r
+ int res = 0;\r
+ String sql =\r
+ "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";\r
+\r
+ //theLog.printInfo("DELETE " + sql);\r
+ try {\r
+ con = getPooledCon();\r
+ stmt = con.createStatement();\r
+ res = stmt.executeUpdate(sql);\r
+ } catch (SQLException sqe) {\r
+ throwSQLException(sqe, "delete");\r
+ } finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ return (res > 0) ? true : false;\r
+ }\r
+\r
+ /* noch nicht implementiert.\r
+ * @return immer false\r
+ */\r
+ public boolean delete(EntityList theEntityList) {\r
+ invalidatePopupCache();\r
+\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse\r
+ * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.\r
+ * @return null\r
+ */\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Holt Daten fuer Popups.\r
+ * @param name Name des Feldes.\r
+ * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.\r
+ * @return SimpleList Gibt freemarker.template.SimpleList zurueck.\r
+ */\r
+ public SimpleList getPopupData(String name, boolean hasNullValue)\r
+ throws StorageObjectFailure {\r
+ return getPopupData(name, hasNullValue, null);\r
+ }\r
+\r
+ /**\r
+ * Holt Daten fuer Popups.\r
+ * @param name Name des Feldes.\r
+ * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.\r
+ * @param where Schraenkt die Selektion der Datensaetze ein.\r
+ * @return SimpleList Gibt freemarker.template.SimpleList zurueck.\r
+ */\r
+ public SimpleList getPopupData(String name, boolean hasNullValue, String where)\r
+ throws StorageObjectFailure {\r
+ return getPopupData(name, hasNullValue, where, null);\r
+ }\r
+\r
+ /**\r
+ * Holt Daten fuer Popups.\r
+ * @param name Name des Feldes.\r
+ * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.\r
+ * @param where Schraenkt die Selektion der Datensaetze ein.\r
+ * @param order Gibt ein Feld als Sortierkriterium an.\r
+ * @return SimpleList Gibt freemarker.template.SimpleList zurueck.\r
+ */\r
+ public SimpleList getPopupData(String name, boolean hasNullValue,\r
+ String where, String order) throws StorageObjectFailure {\r
+ // caching\r
+ if (hasPopupCache && (popupCache != null)) {\r
+ return popupCache;\r
+ }\r
+\r
+ SimpleList simpleList = null;\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+\r
+ // build sql\r
+ StringBuffer sql =\r
+ new StringBuffer("select ").append(thePKeyName).append(",").append(name)\r
+ .append(" from ").append(theTable);\r
+\r
+ if ((where != null) && !(where.length() == 0)) {\r
+ sql.append(" where ").append(where);\r
+ }\r
+\r
+ sql.append(" order by ");\r
+\r
+ if ((order != null) && !(order.length() == 0)) {\r
+ sql.append(order);\r
+ } else {\r
+ sql.append(name);\r
+ }\r
+\r
+ // execute sql\r
+ try {\r
+ con = getPooledCon();\r
+ } catch (Exception e) {\r
+ throw new StorageObjectFailure(e);\r
+ }\r
+\r
+ try {\r
+ stmt = con.createStatement();\r
+\r
+ ResultSet rs = executeSql(stmt, sql.toString());\r
+\r
+ if (rs != null) {\r
+ if (!evaluatedMetaData) {\r
+ get_meta_data();\r
+ }\r
+\r
+ simpleList = new SimpleList();\r
+\r
+ // if popup has null-selector\r
+ if (hasNullValue) {\r
+ simpleList.add(POPUP_EMPTYLINE);\r
+ }\r
+\r
+ SimpleHash popupDict;\r
+\r
+ while (rs.next()) {\r
+ popupDict = new SimpleHash();\r
+ popupDict.put("key", getValueAsString(rs, 1, thePKeyType));\r
+ popupDict.put("value", rs.getString(2));\r
+ simpleList.add(popupDict);\r
+ }\r
+\r
+ rs.close();\r
+ }\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("getPopupData: " + e.getMessage());\r
+ throw new StorageObjectFailure(e);\r
+ } finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ if (hasPopupCache) {\r
+ popupCache = simpleList;\r
+ }\r
+\r
+ return simpleList;\r
+ }\r
+\r
+ /**\r
+ * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,\r
+ * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen\r
+ * Tabellen Verwendung finden.\r
+ * @return SimpleHash mit den Tabellezeilen.\r
+ */\r
+ public SimpleHash getHashData() {\r
+ /** @todo dangerous! this should have a flag to be enabled, otherwise\r
+ * very big Hashes could be returned */\r
+ if (hashCache == null) {\r
+ try {\r
+ hashCache =\r
+ HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1));\r
+ }\r
+ catch (StorageObjectFailure e) {\r
+ logger.debug(e.getMessage());\r
+ }\r
+ }\r
+\r
+ return hashCache;\r
+ }\r
+\r
+ /* invalidates the popupCache\r
+ */\r
+ protected void invalidatePopupCache() {\r
+ /** @todo invalidates toooo much */\r
+ popupCache = null;\r
+ hashCache = null;\r
+ }\r
+\r
+ /**\r
+ * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.\r
+ * @param stmt Statemnt\r
+ * @param sql Sql-String\r
+ * @return ResultSet\r
+ * @exception StorageObjectException\r
+ */\r
+ public ResultSet executeSql(Statement stmt, String sql)\r
+ throws StorageObjectFailure, SQLException {\r
+ ResultSet rs;\r
+ long startTime = System.currentTimeMillis();\r
+\r
+ try {\r
+ rs = stmt.executeQuery(sql);\r
+\r
+ logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+ }\r
+ catch (SQLException e) {\r
+ logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+ throw e;\r
+ }\r
+\r
+ return rs;\r
+ }\r
+\r
+ /**\r
+ * returns the number of rows in the table\r
+ */\r
+ public int getSize(String where) throws SQLException, StorageObjectFailure {\r
+ long startTime = System.currentTimeMillis();\r
+ String sql = "SELECT Count(*) FROM " + theTable;\r
+\r
+ if ((where != null) && !(where.length() == 0)) {\r
+ sql = sql + " where " + where;\r
+ }\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ int result = 0;\r
+\r
+ try {\r
+ con = getPooledCon();\r
+ stmt = con.createStatement();\r
+\r
+ ResultSet rs = executeSql(stmt, sql);\r
+\r
+ while (rs.next()) {\r
+ result = rs.getInt(1);\r
+ }\r
+ }\r
+ catch (SQLException e) {\r
+ logger.error("Database.getSize: " + e.getMessage());\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ //theLog.printInfo(theTable + " has "+ result +" rows where " + where);\r
+ logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+\r
+ return result;\r
+ }\r
+\r
+ public int executeUpdate(Statement stmt, String sql)\r
+ throws StorageObjectFailure, SQLException {\r
+ int rs;\r
+ long startTime = System.currentTimeMillis();\r
+\r
+ try {\r
+ rs = stmt.executeUpdate(sql);\r
+\r
+ logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+ }\r
+ catch (SQLException e) {\r
+ logger.debug("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+ throw e;\r
+ }\r
+\r
+ return rs;\r
+ }\r
+\r
+ public int executeUpdate(String sql)\r
+ throws StorageObjectFailure, SQLException {\r
+ int result = -1;\r
+ long startTime = System.currentTimeMillis();\r
+ Connection con = null;\r
+ PreparedStatement pstmt = null;\r
+\r
+ try {\r
+ con = getPooledCon();\r
+ pstmt = con.prepareStatement(sql);\r
+ result = pstmt.executeUpdate();\r
+ }\r
+ catch (Throwable e) {\r
+ logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());\r
+ throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);\r
+ }\r
+ finally {\r
+ freeConnection(con, pstmt);\r
+ }\r
+\r
+ logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+ return result;\r
+ }\r
+\r
+ /**\r
+ * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend\r
+ * @param md ResultSetMetaData\r
+ * @exception StorageObjectException\r
+ */\r
+ private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {\r
+ this.evaluatedMetaData = true;\r
+ this.metadataFields = new ArrayList();\r
+ this.metadataLabels = new ArrayList();\r
+ this.metadataNotNullFields = new ArrayList();\r
+\r
+ try {\r
+ int numFields = md.getColumnCount();\r
+ this.metadataTypes = new int[numFields];\r
+\r
+ String aField;\r
+ int aType;\r
+\r
+ for (int i = 1; i <= numFields; i++) {\r
+ aField = md.getColumnName(i);\r
+ metadataFields.add(aField);\r
+ metadataLabels.add(md.getColumnLabel(i));\r
+ aType = md.getColumnType(i);\r
+ metadataTypes[i - 1] = aType;\r
+\r
+ if (aField.equals(thePKeyName)) {\r
+ thePKeyType = aType;\r
+ thePKeyIndex = i;\r
+ }\r
+\r
+ if (md.isNullable(i) == ResultSetMetaData.columnNullable) {\r
+ metadataNotNullFields.add(aField);\r
+ }\r
+ }\r
+ }\r
+ catch (SQLException e) {\r
+ throwSQLException(e, "evalMetaData");\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,\r
+ * um die alle Columns und Typen einer Tabelle zu ermitteln.\r
+ */\r
+ private void get_meta_data() throws StorageObjectFailure {\r
+ Connection con = null;\r
+ PreparedStatement pstmt = null;\r
+ String sql = "select * from " + theTable + " where 0=1";\r
+\r
+ try {\r
+ con = getPooledCon();\r
+ pstmt = con.prepareStatement(sql);\r
+\r
+ logger.debug("METADATA: " + sql);\r
+ ResultSet rs = pstmt.executeQuery();\r
+ evalMetaData(rs.getMetaData());\r
+ rs.close();\r
+ }\r
+ catch (SQLException e) {\r
+ throwSQLException(e, "get_meta_data");\r
+ }\r
+ finally {\r
+ freeConnection(con, pstmt);\r
+ }\r
+ }\r
+\r
+ public Connection getPooledCon() throws StorageObjectFailure {\r
+ Connection con = null;\r
+\r
+ try {\r
+ con = SQLManager.getInstance().requestConnection();\r
+ }\r
+ catch (SQLException e) {\r
+ logger.error("could not connect to the database " + e.getMessage());\r
+ System.err.println("could not connect to the database " + e.getMessage());\r
+ throw new StorageObjectFailure("Could not connect to the database", e);\r
+ }\r
+\r
+ return con;\r
+ }\r
+\r
+ public void freeConnection(Connection con, Statement stmt)\r
+ throws StorageObjectFailure {\r
+ SQLManager.closeStatement(stmt);\r
+ SQLManager.getInstance().returnConnection(con);\r
+ }\r
+\r
+ /**\r
+ * Wertet SQLException aus und wirft dannach eine StorageObjectException\r
+ * @param sqe SQLException\r
+ * @param wo Funktonsname, in der die SQLException geworfen wurde\r
+ * @exception StorageObjectException\r
+ */\r
+ protected void throwSQLException(SQLException sqe, String aFunction)\r
+ throws StorageObjectFailure {\r
+ String state = "";\r
+ String message = "";\r
+ int vendor = 0;\r
+\r
+ if (sqe != null) {\r
+ state = sqe.getSQLState();\r
+ message = sqe.getMessage();\r
+ vendor = sqe.getErrorCode();\r
+ }\r
+\r
+ String information =\r
+ "SQL Error: " +\r
+ "state= " + state +\r
+ ", vendor= " + vendor +\r
+ ", message=" + message +\r
+ ", function= " + aFunction;\r
+\r
+ logger.error(information);\r
+\r
+ throw new StorageObjectFailure(information, sqe);\r
+ }\r
+\r
+ protected void _throwStorageObjectException(Exception e, String aFunction)\r
+ throws StorageObjectFailure {\r
+\r
+ if (e != null) {\r
+ logger.error(e.getMessage() + aFunction);\r
+ throw new StorageObjectFailure(aFunction, e);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach\r
+ * eine StorageObjectException\r
+ * @param message Nachricht mit dem Fehler\r
+ * @exception StorageObjectException\r
+ */\r
+ void throwStorageObjectException(String aMessage) throws StorageObjectFailure {\r
+ logger.error(aMessage);\r
+ throw new StorageObjectFailure(aMessage, null);\r
+ }\r
+}\r
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.ArrayList;
+import java.util.List;
/**
* @return ArrayList
* @exception StorageObjectException
*/
- abstract public ArrayList getFields() throws StorageObjectFailure;
+ abstract public List getFields() throws StorageObjectFailure;
/**
* Dokumentation siehe Database.java
* @return ArrayList
* @exception StorageObjectException
*/
- abstract public ArrayList getLabels() throws StorageObjectFailure;
+ abstract public List getLabels() throws StorageObjectFailure;
/**
* Dokumentation siehe Database.java
-/*
- * 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 "<i>"+version()+"</i>"; }
-
- /**
- * Method: version()
- * Description: returns ObjectStore version as String
- *
- * @return String
- */
- private String version() { return "v_sstart3__1.0"; }
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.storage.store;\r
+\r
+/**\r
+ * Title: ObjectStore for StorableObjects\r
+ * Description: ObjectStore holds a Map of @see StoreContainer for all possible\r
+ * @see StoreIdentifier.\r
+ *\r
+ * @see StorageIdentifier - identitfies one object in the ObjectStore\r
+ * i.e. in its apropriate bucket. It holds a unique identifier\r
+ * of a StorableObject and a reference on the StorableObject.\r
+ *\r
+ * @see StoreContainer - "Buckets" to store different types of Objects\r
+ * in one Container. These buckets are cofigurable via\r
+ * config.properties.\r
+ *\r
+ * @see StoreContainerType - is a signature for all StoreContainer\r
+ * and StoreIdentifier.\r
+ *\r
+ * @see StorableObjects - Interface Object have to implement to\r
+ * be handled by the ObjectStore\r
+ *\r
+ * @see ServletStoreInfo - Maintenance Servlet for ObjectStore.\r
+ * Displays information about current content of the\r
+ * ObjectStore.\r
+ *\r
+ *\r
+ * Copyright: Copyright (c) 2002\r
+ * Company: indy\r
+ * @author rk\r
+ * @version 1.0\r
+ */\r
+\r
+import java.io.BufferedInputStream;\r
+import java.io.FileInputStream;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.MissingResourceException;\r
+import java.util.Properties;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.log.LoggerWrapper;\r
+\r
+public class ObjectStore {\r
+\r
+ private final static ObjectStore INSTANCE = new ObjectStore();\r
+ private final static HashMap containerMap = new HashMap(); // StoreContainerType/StoreContainer\r
+ private static long storeHit = 0, storeMiss = 0;\r
+ private Properties ostoreConf;\r
+ private LoggerWrapper logger;\r
+\r
+ private ObjectStore() {\r
+ String confName = null;\r
+\r
+ logger = new LoggerWrapper("Database.ObjectStore");\r
+ Properties conf = new Properties();\r
+\r
+ try {\r
+ confName =\r
+ MirPropertiesConfiguration.instance().getString("Home") +\r
+ "etc/objectstore.properties";\r
+ conf.load(new BufferedInputStream(new FileInputStream(confName)));\r
+ }\r
+ catch (java.io.FileNotFoundException fnfe) {\r
+ logger.error("could not read config file. not found: " + confName);\r
+ }\r
+ catch (Throwable t) {\r
+ logger.error("could not get config: " + t.getMessage());\r
+ }\r
+ ostoreConf = conf;\r
+ }\r
+\r
+ public static ObjectStore getInstance() {\r
+ return INSTANCE;\r
+ }\r
+\r
+ /**\r
+ * Method: use\r
+ * Description: The ObjectStore tries to find the @see StoreIdentifier sid\r
+ * and returns the stored Object.\r
+ *\r
+ * @return StorableObject is null when no StorableObject for the\r
+ * StoreIdentifier sid is found.\r
+ */\r
+ public StorableObject use(StoreIdentifier sid) {\r
+ if (sid != null) {\r
+ StorableObject storeObject = null;\r
+ StoreContainer stoc = getStoreContainerForSid(sid);\r
+ if (stoc != null)\r
+ storeObject = stoc.use(sid);\r
+ else\r
+ logger.warn("container not found for: " + sid.toString());\r
+ if (storeObject != null) {\r
+ storeHit++;\r
+ return storeObject;\r
+ }\r
+ }\r
+ storeMiss++;\r
+ return null;\r
+\r
+ }\r
+\r
+ /**\r
+ * Method: add\r
+ * Description: A StoreIdentifier is added to the ObjectStore, if it\r
+ * contains a reference to a @see StorableObject.\r
+ */\r
+ public void add(StoreIdentifier sid) {\r
+ if (sid != null && sid.hasReference()) {\r
+ // find the right StoreContainer for sid\r
+ StoreContainer stoc = getStoreContainerForSid(sid);\r
+ if (stoc == null) {\r
+ // we have to make new StoreContainer\r
+ StoreContainerType stocType = sid.getStoreContainerType();\r
+ stoc = new StoreContainer(stocType);\r
+ containerMap.put(stocType, stoc);\r
+ }\r
+ stoc.add(sid);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Method: invalidate(StorableObject sto)\r
+ * Description: ObjectStore is notified of change of a @see StorableObject\r
+ * sto and invalidates all relevant cache entries.\r
+ */\r
+\r
+ public void invalidate(StoreIdentifier sid) {\r
+ // propagate invalidation to StoreContainer\r
+ if (sid != null) {\r
+ StoreContainer stoc = getStoreContainerForSid(sid);\r
+ stoc.invalidate(sid);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Method: invalidate(StoreContainerType)\r
+ * Description: serves to invalidate a whole StoreContainer\r
+ *\r
+ * @return\r
+ */\r
+ public void invalidate(StoreContainerType stoc_type) {\r
+ if (stoc_type != null) {\r
+ /** @todo invalidates too much:\r
+ * improvement: if instanceof StoreContainerEntity && EntityList\r
+ * then invalidate only StoreIdentifier matching the right table\r
+ */\r
+ StoreContainer stoc = getStoreContainerForStocType(stoc_type);\r
+ if (stoc != null)\r
+ stoc.invalidate();\r
+ }\r
+\r
+ }\r
+\r
+ // internal methods for StoreContainer managment\r
+\r
+ /**\r
+ * Method: getStoreContainerForSid\r
+ * Description: private method to find the right @see StoreContainer for\r
+ * the @see StoreIdentifier sid.\r
+ *\r
+ * @return StoreContainer is null when no Container is found.\r
+ */\r
+ private StoreContainer getStoreContainerForSid(StoreIdentifier sid) {\r
+ // find apropriate container for a specific sid\r
+ if (sid != null) {\r
+ StoreContainerType stoc_type = sid.getStoreContainerType();\r
+ return getStoreContainerForStocType(stoc_type);\r
+ }\r
+ return null;\r
+ }\r
+\r
+ private StoreContainer getStoreContainerForStocType(StoreContainerType\r
+ stoc_type) {\r
+ if (stoc_type != null && containerMap.containsKey(stoc_type))\r
+ return (StoreContainer) containerMap.get(stoc_type);\r
+ return null;\r
+ }\r
+\r
+ private boolean has(StoreIdentifier sid) {\r
+ StoreContainer stoc = getStoreContainerForSid(sid);\r
+ return (stoc != null && stoc.has(sid)) ? true : false;\r
+ }\r
+\r
+ public String getConfProperty(String name) {\r
+ if (name != null) {\r
+ String returnValue = "";\r
+ try {\r
+ return ostoreConf.getProperty(name);\r
+ }\r
+ catch (MissingResourceException e) {\r
+ logger.error("getConfProperty: " + e.toString());\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Method: toString()\r
+ * Description: Displays statistical information about the ObjectStore.\r
+ * Further information is gathered from all @see StoreContainer\r
+ *\r
+ * @return String\r
+ */\r
+ public String toString() {\r
+ return toHtml(null);\r
+ }\r
+\r
+ public String toHtml(HttpServletRequest req) {\r
+ float hitRatio = 0;\r
+ long divisor = storeHit + storeMiss;\r
+ if (divisor > 0)\r
+ hitRatio = (float) storeHit / (float) divisor;\r
+ hitRatio *= 100;\r
+\r
+ StringBuffer sb = new StringBuffer("Mir-ObjectStore ");\r
+ sb.append( ( (req != null) ? html_version() : version())).append("\n");\r
+ sb.append("ObjectStore overall hits/misses/ratio: ").append(storeHit);\r
+ sb.append("/").append(storeMiss).append("/").append(hitRatio);\r
+ sb.append("%\nCurrently ").append(containerMap.size());\r
+ sb.append(" StoreContainer in use - listing information:\n");\r
+\r
+ // ask container for information\r
+ StoreContainer currentStoc;\r
+ for (Iterator it = containerMap.keySet().iterator(); it.hasNext(); ) {\r
+ currentStoc = (StoreContainer) containerMap.get(it.next());\r
+ sb.append(currentStoc.toHtml(req));\r
+ }\r
+\r
+ return sb.toString();\r
+ }\r
+\r
+ /**\r
+ * Method: html_version()\r
+ * Description: returns ObjectStore version as String for HTML representation\r
+ *\r
+ * @return String\r
+ */\r
+ private String html_version() {\r
+ return "<i>" + version() + "</i>";\r
+ }\r
+\r
+ /**\r
+ * Method: version()\r
+ * Description: returns ObjectStore version as String\r
+ *\r
+ * @return String\r
+ */\r
+ private String version() {\r
+ return "v_sstart3__1.0";\r
+ }\r
+\r
}
\ No newline at end of file
--- /dev/null
+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();
+ }
+}
}\r
}\r
\r
- public void characters(char[] aBuffer, int aStart, int anEnd) throws SAXParseException {\r
- String text = new String(aBuffer, aStart, anEnd).trim();\r
- if ( text.length() > 0) {\r
- throw new SAXParseException("Text not allowed", null, new XMLReaderExc("Text not allowed"));\r
+ public void characters(char[] aBuffer, int aStart, int anEnd) throws SAXException {\r
+ try {\r
+ String text = new String(aBuffer, aStart, anEnd);\r
+\r
+ manager.currentHandler().characters(text);\r
+ }\r
+ catch (XMLReaderExc e) {\r
+ throw new SAXParseException(e.getMessage(), null, e);\r
+ }\r
+ catch (Exception e) {\r
+ throw new SAXException(e);\r
}\r
}\r
}\r
\r
public abstract void endElement(SectionHandler aHandler) throws XMLReaderExc;\r
\r
+ public void characters(String aCharacters) throws XMLReaderExc;\r
+\r
public void finishSection() throws XMLReaderExc;\r
}\r
\r
\r
public void finishSection() throws XMLReaderExc {\r
}\r
+\r
+ public void characters(String aCharacters) throws XMLReaderExc {\r
+ if ( aCharacters.trim().length() > 0) {\r
+ throw new XMLReaderExc("Text not allowed");\r
+ }\r
+ }\r
}\r
\r
public static class XMLReaderExc extends Exc {\r
+++ /dev/null
-/*
- * 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
* 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 $
*/
}
catch (StorageObjectFailure e) {
throwStorageObjectFailure(e, "get MediaType failed -- ");
- } catch (StorageObjectExc e) {
- throwStorageObjectFailure(e, "get MediaType failed -- ");
}
return ent;
}
}
public static MirPropertiesConfiguration config() {
- try {
+ try {
return MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- e.printStackTrace();
+ }
+ catch (PropertiesConfigExc e) {
throw new RuntimeException(e.getMessage());
}
}
} catch (Throwable t) {
result = aDefault;
}
-
+
if (result==null)
result = aDefault;
package mircoders.localizer;
import java.util.List;
+import java.util.Map;
import mir.entity.adapter.EntityAdapter;
+/**
+ *
+ * <p>Title: Interface to allow for localized changed to the workings of the admin system</p>
+ * @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
+ * <p>
+ * <code>anArticle.put("creator", "editorial team");</code>
+ */
+ public void initializeArticle(Map anArticle);
+
public List simpleCommentOperations();
public MirSimpleEntityOperation simpleCommentOperationForName(String aName);
import mir.entity.Entity;\r
import mir.entity.adapter.EntityAdapter;\r
import mir.storage.StorageObjectFailure;\r
+import mir.misc.StringUtil;\r
import mir.util.StringRoutines;\r
import mircoders.entity.EntityComment;\r
import mircoders.entity.EntityContent;\r
addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0"));\r
}\r
\r
+ public void initializeArticle(Map anArticle) {\r
+ anArticle.put("is_published", "0");\r
+ anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
+ };\r
+\r
public List simpleCommentOperations() {\r
return simpleCommentOperations;\r
};\r
\r
if (logOperation) {\r
StringBuffer comment = new StringBuffer();\r
- try {\r
+ try {\r
comment.append(StringRoutines.interpretAsString(anEntity.getValue("comment")));\r
- }\r
- catch (Throwable t) {\r
- }\r
+ }\r
+ catch (Throwable t) {\r
+ }\r
if (comment.length()>0 && comment.charAt(comment.length()-1)!='\n') {\r
comment.append('\n');\r
}\r
import mir.media.MediaHelper;\r
import mir.media.MirMedia;\r
import mir.util.RewindableIterator;\r
+import mir.log.LoggerWrapper;\r
import mircoders.entity.EntityUploadedMedia;\r
import mircoders.global.MirGlobal;\r
import mircoders.localizer.MirAdminInterfaceLocalizer;\r
\r
public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {\r
private EntityAdapterModel model;\r
+ protected LoggerWrapper logger;\r
\r
public MirBasicDataModelLocalizer() {\r
}\r
\r
public EntityAdapterModel adapterModel() throws MirLocalizerFailure {\r
+ logger = new LoggerWrapper("Localizer.Basic");\r
+\r
if (model==null)\r
model = buildModel();\r
\r
anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));\r
anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data"));\r
\r
+ anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField());\r
+ anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField());\r
+\r
anEntityAdapterDefinition.addCalculatedField("operations",\r
new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations()));\r
}\r
}\r
}\r
\r
+ protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ logger.debug("ContentToParentField.getValue");\r
+ return anEntityAdapter.getToOneRelation(\r
+ "id="+anEntityAdapter.get("to_content"),\r
+ "id",\r
+ "content" );\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return anEntityAdapter.getRelation(\r
+ "to_content="+anEntityAdapter.get("id"),\r
+ "id",\r
+ "content" );\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField {\r
public Object getValue(EntityAdapter anEntityAdapter) {\r
try {\r
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);
}
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();
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;
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");
afterCommentProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(commentProducers);
}
catch (Throwable t) {
- logger.printError("Setting up MirBasicOpenPostingLocalizer failed: " + t.getMessage());
+ logger.error("Setting up MirBasicOpenPostingLocalizer failed: " + t.getMessage());
}
}
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;
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;
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"));
aValueSet.put("utility", utilityMap);
-
EntityList topicList=null;
EntityList entityList=null;
EntityList parentList=null;
}
catch (Throwable t) {
- logger.printError("initializeGenerationValueSet: Exception "+t.getMessage());
+ logger.error("initializeGenerationValueSet: Exception "+t.getMessage());
}
aValueSet.put("topics", topicList);
}
}
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);
}
}
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);
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;
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);
nameToFactory = new HashMap();
}
catch (Throwable t) {
- logger.printError("MirBasicProducerLocalizer(): Exception "+t.getMessage());
+ logger.error("MirBasicProducerLocalizer(): Exception "+t.getMessage());
model = new EntityAdapterModel();
}
}
producerFactories = newProducers;
fileMonitor = newFileMonitor;
- logger.printInfo("MirBasicProducerLocalizer.factories(): successfully setup factories");
+ logger.info("MirBasicProducerLocalizer.factories(): successfully setup factories");
nameToFactory.clear();
Iterator i = producerFactories.iterator();
}
}
catch (Throwable t) {
- logger.printError("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage());
+ logger.error("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage());
}
}
-/*
- * 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");
- }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.io.PrintWriter;\r
+import java.io.IOException;\r
+import java.util.*;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import mir.entity.EntityList;\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.module.ModuleException;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleException;\r
+import mir.storage.StorageObjectFailure;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.HTMLRoutines;\r
+import mir.util.JDBCStringRoutines;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.URLBuilder;\r
+import mir.util.SQLQueryBuilder;\r
+import mir.log.*;\r
+\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.module.ModuleImages;\r
+import mircoders.module.ModuleSchwerpunkt;\r
+import mircoders.module.ModuleTopics;\r
+import mircoders.search.IndexUtil;\r
+import mircoders.storage.DatabaseArticleType;\r
+import mircoders.storage.DatabaseComment;\r
+import mircoders.storage.DatabaseContent;\r
+import mircoders.storage.DatabaseContentToTopics;\r
+import mircoders.storage.DatabaseFeature;\r
+import mircoders.storage.DatabaseImages;\r
+import mircoders.storage.DatabaseLanguage;\r
+import mircoders.storage.DatabaseTopics;\r
+\r
+import org.apache.lucene.index.IndexReader;\r
+\r
+import freemarker.template.SimpleHash;\r
+import freemarker.template.SimpleScalar;\r
+import freemarker.template.TemplateModelRoot;\r
+\r
+/*\r
+ * ServletModuleContent -\r
+ * deliver html for the article admin form.\r
+ *\r
+ * @version $Id: ServletModuleContent.java,v 1.33 2003/02/20 16:05:34 zapata Exp $\r
+ * @author rk, mir-coders\r
+ *\r
+ */\r
+\r
+public class ServletModuleContent extends ServletModule\r
+{\r
+ private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;\r
+ private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");\r
+\r
+ private static ServletModuleContent instance = new ServletModuleContent();\r
+ public static ServletModule getInstance() { return instance; }\r
+\r
+ private ServletModuleContent() {\r
+ super();\r
+ logger = new LoggerWrapper("ServletModule.Content");\r
+ try {\r
+\r
+ templateListString = configuration.getString("ServletModule.Content.ListTemplate");\r
+ templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");\r
+ templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");\r
+\r
+ mainModule = new ModuleContent(DatabaseContent.getInstance());\r
+ }\r
+ catch (StorageObjectFailure e) {\r
+ logger.error("servletmodulecontent konnte nicht initialisiert werden");\r
+ }\r
+ }\r
+\r
+ public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException\r
+ {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+ String where = requestParser.getParameter("where");\r
+ String order = requestParser.getParameterWithDefault("order", "webdb_create desc");\r
+ int offset = requestParser.getIntegerWithDefault("offset", 0);\r
+ String selectArticleUrl = requestParser.getParameter("selectarticleurl");\r
+\r
+ returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl);\r
+ }\r
+\r
+ public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException {\r
+ try {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
+ String searchField = requestParser.getParameterWithDefault("searchfield", "");\r
+ String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();\r
+ String searchOrder = requestParser.getParameterWithDefault("searchorder", "");\r
+ String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");\r
+ String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");\r
+ String selectArticleUrl = requestParser.getParameter("selectarticleurl");\r
+\r
+ if (searchValue.length()>0) {\r
+ if (searchField.equals("contents"))\r
+ queryBuilder.appendAndCondition(\r
+ "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+\r
+ " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");\r
+ else\r
+ queryBuilder.appendAndCondition(\r
+ "lower("+ searchField + ") like " +\r
+ "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");\r
+ }\r
+\r
+ if (searchispublished.length()>0) {\r
+ if (searchispublished.equals("0"))\r
+ queryBuilder.appendAndCondition("is_published='f'");\r
+ else\r
+ queryBuilder.appendAndCondition("is_published='t'");\r
+ }\r
+\r
+ if (searchArticleType.length()>0) {\r
+ queryBuilder.appendAndCondition("to_article_type="+searchArticleType);\r
+ }\r
+\r
+ if (searchOrder.length()>0) {\r
+ if (searchOrder.equals("datedesc"))\r
+ queryBuilder.appendAscendingOrder("webdb_create");\r
+ else if (searchOrder.equals("dateasc"))\r
+ queryBuilder.appendDescendingOrder("webdb_create");\r
+ else if (searchOrder.equals("title"))\r
+ queryBuilder.appendDescendingOrder("title");\r
+ else if (searchOrder.equals("creator"))\r
+ queryBuilder.appendDescendingOrder("creator");\r
+ }\r
+\r
+ returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);\r
+ }\r
+ catch (Throwable e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ }\r
+\r
+ public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException {\r
+ _showObject(null, req, res);\r
+ }\r
+\r
+\r
+ public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
+ {\r
+//theLog.printDebugInfo(":: content :: trying to insert");\r
+ try {\r
+ EntityUsers user = _getUser(req);\r
+ HashMap withValues = getIntersectingValues(req, DatabaseContent.getInstance());\r
+\r
+ String now = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ withValues.put("date", now);\r
+ withValues.put("publish_path", StringUtil.webdbDate2path(now));\r
+ withValues.put("to_publisher", user.getId());\r
+ withValues.put("is_produced", "0");\r
+ if (!withValues.containsKey("is_published"))\r
+ withValues.put("is_published","0");\r
+ if (!withValues.containsKey("is_html"))\r
+ withValues.put("is_html","0");\r
+\r
+ String id = mainModule.add(withValues);\r
+ DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));\r
+\r
+ _showObject(id, req, res);\r
+ }\r
+ catch (StorageObjectFailure e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ catch (ModuleException e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ }\r
+\r
+ public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
+ {\r
+ EntityUsers user = _getUser(req);\r
+\r
+ String idParam = req.getParameter("id");\r
+ if (idParam == null) throw new ServletModuleException("Invalid call: id missing");\r
+\r
+ String confirmParam = req.getParameter("confirm");\r
+ String cancelParam = req.getParameter("cancel");\r
+\r
+ logger.info("where = " + req.getParameter("where"));\r
+\r
+ if (confirmParam == null && cancelParam == null) {\r
+\r
+ SimpleHash mergeData = new SimpleHash();\r
+ mergeData.put("module", "Content");\r
+ mergeData.put("infoString", "Content: " + idParam);\r
+ mergeData.put("id", idParam);\r
+ mergeData.put("where", req.getParameter("where"));\r
+ mergeData.put("order", req.getParameter("order"));\r
+ mergeData.put("offset", req.getParameter("offset"));\r
+ deliver(req, res, mergeData, templateConfirmString);\r
+ }\r
+ else {\r
+ if (confirmParam!= null && !confirmParam.equals("")) {\r
+ try {\r
+ mainModule.deleteById(idParam);\r
+\r
+ /** @todo the following two should be implied in\r
+ * DatabaseContent */\r
+\r
+ //delete rows in the content_x_topic-table\r
+ DatabaseContentToTopics.getInstance().deleteByContentId(idParam);\r
+ //delete rows in the comment-table\r
+ DatabaseComment.getInstance().deleteByContentId(idParam);\r
+ //delete from lucene index, if any\r
+ String index = configuration.getString("IndexPath");\r
+ if (IndexReader.indexExists(index)){\r
+ IndexUtil.unindexID(idParam,index);\r
+ }\r
+\r
+ }\r
+ catch (ModuleException e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ catch (StorageObjectFailure e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ catch (IOException e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ list(req,res);\r
+ }\r
+ else {\r
+ // Datensatz anzeigen\r
+ _showObject(idParam, req, res);\r
+ }\r
+ }\r
+ }\r
+\r
+ public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
+ {\r
+ String idParam = req.getParameter("id");\r
+ if (idParam == null)\r
+ throw new ServletModuleException("Invalid call: id not supplied ");\r
+ _showObject(idParam, req, res);\r
+ }\r
+\r
+// methods for attaching media file\r
+ public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
+ {\r
+ String mediaIdParam = req.getParameter("mid");\r
+ String idParam = req.getParameter("cid");\r
+ if (idParam == null||mediaIdParam==null) throw new ServletModuleException("smod content :: attach :: cid/mid missing");\r
+\r
+ try {\r
+ EntityContent entContent = (EntityContent)mainModule.getById(idParam);\r
+ entContent.attach(mediaIdParam);\r
+ }\r
+ catch(ModuleException e) {\r
+ logger.error("smod content :: attach :: could not get entityContent");\r
+ }\r
+ catch(StorageObjectFailure e) {\r
+ logger.error("smod content :: attach :: could not get entityContent");\r
+ }\r
+\r
+ _showObject(idParam, req, res);\r
+ }\r
+\r
+ public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
+ {\r
+ String cidParam = req.getParameter("cid");\r
+ String midParam = req.getParameter("mid");\r
+ if (cidParam == null) throw new ServletModuleException("smod content :: dettach :: cid missing");\r
+ if (midParam == null) throw new ServletModuleException("smod content :: dettach :: mid missing");\r
+\r
+ try {\r
+ EntityContent entContent = (EntityContent)mainModule.getById(cidParam);\r
+ entContent.dettach(cidParam,midParam);\r
+ }\r
+ catch(ModuleException e) {\r
+ logger.error("smod content :: dettach :: could not get entityContent");\r
+ }\r
+ catch(StorageObjectFailure e) {\r
+ logger.error("smod content :: dettach :: could not get entityContent");\r
+ }\r
+\r
+ _showObject(cidParam, req, res);\r
+ }\r
+\r
+ public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+ throws ServletModuleException\r
+ {\r
+ try {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+ String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+ String idParam = aRequest.getParameter("id");\r
+ if (idParam == null) throw new ServletModuleException("Wrong call: (id) is missing");\r
+\r
+ HashMap withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
+ String[] topic_id = aRequest.getParameterValues("to_topic");\r
+ String content_id = aRequest.getParameter("id");\r
+\r
+ withValues.put("is_produced", "0");\r
+ if (!withValues.containsKey("is_published"))\r
+ withValues.put("is_published","0");\r
+ if (!withValues.containsKey("is_html"))\r
+ withValues.put("is_html","0");\r
+\r
+ String id = mainModule.set(withValues);\r
+ DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id);\r
+\r
+ String whereParam = aRequest.getParameter("where");\r
+ String orderParam = aRequest.getParameter("order");\r
+\r
+ if (returnUrl!=null){\r
+ redirect(aResponse, returnUrl);\r
+ }\r
+ else\r
+ _showObject(idParam, aRequest, aResponse);\r
+ }\r
+ catch (Throwable e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ }\r
+\r
+/*\r
+ * HelperMethod shows the basic article editing form.\r
+ *\r
+ * if the "id" parameter is null, it means show an empty form to add a new\r
+ * article.\r
+*/\r
+ private void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+ throws ServletModuleException {\r
+\r
+ try {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));\r
+ EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
+ Map article;\r
+ URLBuilder urlBuilder = new URLBuilder();\r
+\r
+ urlBuilder.setValue("module", "Content");\r
+ urlBuilder.setValue("do", "edit");\r
+ urlBuilder.setValue("id", id);\r
+ urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+\r
+ if (id!=null) {\r
+ responseData.put("new", Boolean.FALSE);\r
+ article = model.makeEntityAdapter("content", mainModule.getById(id));\r
+ }\r
+ else {\r
+ List fields = DatabaseContent.getInstance().getFields();\r
+ responseData.put("new", Boolean.TRUE);\r
+ article = new HashMap();\r
+ Iterator i = fields.iterator();\r
+ while (i.hasNext()) {\r
+ article.put(i.next(), null);\r
+ }\r
+\r
+ article.put("to_topics", null);\r
+\r
+ MirGlobal.localizer().adminInterface().initializeArticle(article);\r
+ }\r
+ responseData.put("article", article);\r
+\r
+ Object languages =\r
+ new CachingRewindableIterator(\r
+ new EntityIteratorAdapter( "", "id", 30,\r
+ MirGlobal.localizer().dataModel().adapterModel(), "language"));\r
+ Object topics =\r
+ new CachingRewindableIterator(\r
+ new EntityIteratorAdapter("", "id", 30,\r
+ MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
+ Object articleTypes =\r
+ new CachingRewindableIterator(\r
+ new EntityIteratorAdapter( "", "id", 30,\r
+ MirGlobal.localizer().dataModel().adapterModel(), "articleType"));\r
+\r
+ responseData.put("articleTypes", articleTypes);\r
+ responseData.put("languages", languages);\r
+ responseData.put("topics", topics);\r
+ responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
+ responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);\r
+ }\r
+ catch (Exception e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ }\r
+\r
+ public void returnArticleList(\r
+ HttpServletRequest aRequest,\r
+ HttpServletResponse aResponse,\r
+ String aWhereClause,\r
+ String anOrderByClause,\r
+ int anOffset,\r
+ String aSelectArticleUrl) throws ServletModuleException {\r
+\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ URLBuilder urlBuilder = new URLBuilder();\r
+ EntityAdapterModel model;\r
+ int nrArticlesPerPage = 20;\r
+ int count;\r
+\r
+ try {\r
+ Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));\r
+ model = MirGlobal.localizer().dataModel().adapterModel();\r
+\r
+ Object articleList =\r
+ new CachingRewindableIterator(\r
+ new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,\r
+ MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)\r
+ );\r
+\r
+ responseData.put("nexturl", null);\r
+ responseData.put("prevurl", null);\r
+\r
+ count=mainModule.getSize(aWhereClause);\r
+\r
+ urlBuilder.setValue("module", "Content");\r
+ urlBuilder.setValue("do", "list");\r
+ urlBuilder.setValue("where", aWhereClause);\r
+ urlBuilder.setValue("order", anOrderByClause);\r
+\r
+\r
+ urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
+ urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));\r
+ urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
+ urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
+ urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));\r
+ urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);\r
+\r
+ responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
+ responseData.put("searchvalue", requestParser.getParameter("searchvalue"));\r
+ responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
+ responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
+ responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));\r
+ responseData.put("selectarticleurl", aSelectArticleUrl);\r
+\r
+ urlBuilder.setValue("offset", anOffset);\r
+ responseData.put("offset" , new Integer(anOffset).toString());\r
+ responseData.put("thisurl" , urlBuilder.getQuery());\r
+\r
+ if (count>=anOffset+nrArticlesPerPage) {\r
+ urlBuilder.setValue("offset", anOffset + nrArticlesPerPage);\r
+ responseData.put("nexturl" , urlBuilder.getQuery());\r
+ }\r
+\r
+ if (anOffset>0) {\r
+ urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));\r
+ responseData.put("prevurl" , urlBuilder.getQuery());\r
+ }\r
+\r
+ responseData.put("articles", articleList);\r
+\r
+ responseData.put("from" , Integer.toString(anOffset+1));\r
+ responseData.put("count", Integer.toString(count));\r
+ responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));\r
+ responseData.put("offset" , Integer.toString(anOffset));\r
+ responseData.put("order", anOrderByClause);\r
+ responseData.put("where" , aWhereClause);\r
+\r
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);\r
+ }\r
+ catch (Throwable e) {\r
+ throw new ServletModuleException(e.toString());\r
+ }\r
+ }\r
+\r
+ public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException\r
+ {\r
+ try {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ URLBuilder urlBuilder = new URLBuilder();\r
+\r
+ urlBuilder.setValue("module", "Content");\r
+ urlBuilder.setValue("do", "setparent");\r
+ urlBuilder.setValue("childid", requestParser.getParameter("id"));\r
+ urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+\r
+ returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());\r
+ }\r
+ catch (Throwable e) {\r
+ throw new ServletModuleException(e.getMessage());\r
+ }\r
+ }\r
+\r
+ public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException\r
+ {\r
+ try {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ String articleId = requestParser.getParameter("article_id");\r
+\r
+ if (articleId == null)\r
+ throw new ServletModuleException("ServletModuleContent.listchildren: article_id not set!");\r
+\r
+ returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);\r
+ }\r
+ catch (Throwable e) {\r
+ throw new ServletModuleException(e.getMessage());\r
+ }\r
+ }\r
+\r
+ public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException\r
+ {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ String articleId = aRequest.getParameter("childid");\r
+ String parentId = aRequest.getParameter("id");\r
+ String returnUrl = aRequest.getParameter("returnurl");\r
+\r
+ try {\r
+ EntityContent article = (EntityContent) mainModule.getById(articleId);\r
+ article.setValueForProperty("to_content", parentId);\r
+ article.setProduced(false);\r
+ article.update();\r
+ }\r
+ catch(Throwable e) {\r
+ logger.error("ServletModuleContent.setparent: " + e.getMessage());\r
+ throw new ServletModuleException("ServletModuleContent.setparent: " + e.getMessage());\r
+ }\r
+\r
+ redirect(aResponse, returnUrl);\r
+ }\r
+\r
+ public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleException\r
+ {\r
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+ String articleId = requestParser.getParameter("id");\r
+ String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+ try {\r
+ EntityContent article = (EntityContent) mainModule.getById(articleId);\r
+ article.setValueForProperty("to_content", "");\r
+ article.setProduced(false);\r
+ article.update();\r
+ }\r
+ catch(Throwable e) {\r
+ e.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
+ logger.error("ServletModuleContent.clearparent: " + e.getMessage());\r
+\r
+ throw new ServletModuleException("ServletModuleContent.clearparent: " + e.getMessage());\r
+ }\r
+\r
+ redirect(aResponse, returnUrl);\r
+ }\r
+\r
+ private EntityUsers _getUser(HttpServletRequest req)\r
+ {\r
+ HttpSession session=req.getSession(false);\r
+\r
+ return (EntityUsers)session.getAttribute("login.uid");\r
+ }\r
+}\r
* @version 1.0\r
*/\r
\r
+import mir.log.LoggerWrapper;\r
import mir.storage.Database;\r
import mir.storage.StorageObject;\r
import mir.storage.StorageObjectFailure;\r
\r
private DatabaseArticleType() throws StorageObjectFailure {\r
super();\r
+ logger = new LoggerWrapper("Database.ArticleType");\r
this.hasTimestamp = false;\r
this.theTable = "article_type";\r
}\r
-/*
- * 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;
-
-/**
- * <b>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
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.util.GregorianCalendar;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.entity.Entity;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+public class DatabaseAudio extends Database implements StorageObject{\r
+\r
+ private static DatabaseAudio instance;\r
+ private static SimpleList publisherPopupData;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseAudio getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseAudio();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseAudio() throws StorageObjectFailure {\r
+ super();\r
+ logger = new LoggerWrapper("Database.Audio");\r
+\r
+ hasTimestamp = true;\r
+ theTable = "audio";\r
+ theCoreTable = "media";\r
+ theEntityClass = mircoders.entity.EntityAudio.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+\r
+ public void update(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+\r
+ super.update(theEntity);\r
+ }\r
+\r
+ public String insert(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+ return super.insert(theEntity);\r
+ }\r
+\r
+}\r
package mircoders.storage;
+import mir.log.LoggerWrapper;
import mir.storage.Database;
import mir.storage.StorageObject;
import mir.storage.StorageObjectFailure;
private DatabaseBreaking() throws StorageObjectFailure
{
super();
- //this.cache = new DatabaseCache(4);
+ logger = new LoggerWrapper("Database.Breaking");
this.theTable="breaking";
}
-/*
- * 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;
-
-/**
- * <b>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;
- }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.sql.Connection;\r
+import java.sql.SQLException;\r
+import java.sql.Statement;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+/**\r
+ * <b>This class implements the access to the comment-table for the\r
+ * media table.\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseComment extends Database implements StorageObject{\r
+\r
+ private static DatabaseComment instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseComment getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseComment();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseComment() throws StorageObjectFailure {\r
+ super();\r
+ hasTimestamp = false;\r
+ theTable = "comment";\r
+ logger = new LoggerWrapper("Database.Comment");\r
+\r
+ try {\r
+ this.theEntityClass = Class.forName("mircoders.entity.EntityComment");\r
+ }\r
+ catch (Exception e) {\r
+ throw new StorageObjectFailure(e);\r
+ }\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+\r
+ public boolean deleteByContentId(String id) throws StorageObjectFailure {\r
+ Statement stmt = null;\r
+ Connection con = null;\r
+ String sql;\r
+ int res = 0;\r
+\r
+ /** @todo comments and topics should be deleted */\r
+ sql = "delete from " + theTable + " where to_media=" + id;\r
+ logger.info("DELETE "+ sql);\r
+\r
+ try {\r
+ con = getPooledCon();\r
+ stmt = con.createStatement();\r
+ res = stmt.executeUpdate(sql);\r
+ }\r
+ catch (SQLException sqe) {\r
+ new StorageObjectFailure(sqe);\r
+ return false;\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ return true;\r
+ }\r
+}\r
* @version 1.0\r
*/\r
\r
+import mir.log.LoggerWrapper;\r
import mir.storage.Database;\r
import mir.storage.StorageObject;\r
import mir.storage.StorageObjectFailure;\r
\r
private DatabaseCommentStatus() throws StorageObjectFailure {\r
super();\r
- this.hasTimestamp = false;\r
- this.theTable = "comment_status";\r
+ hasTimestamp = false;\r
+ theTable = "comment_status";\r
+ logger = new LoggerWrapper("Database.CommentStatus");\r
}\r
\r
public SimpleList getPopupData() throws StorageObjectFailure {\r
import java.sql.Connection;
import java.sql.Statement;
+import mir.log.LoggerWrapper;
import mir.entity.EntityList;
import mir.entity.EntityRelation;
import mir.storage.Database;
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
{
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);}
-/*
- * 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;
-
-/**
- * <b>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;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) {
- theLog.printDebugInfo("-- 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) {
- theLog.printDebugInfo("-- 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) {
- 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
-
- 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) {
- theLog.printDebugInfo("-- 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) {
- theLog.printDebugInfo("-- 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);
- theLog.printDebugInfo("-- delete media success ");
- } catch (Exception e) {
- theLog.printDebugInfo("-- 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) {
- theLog.printDebugInfo("-- 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);
- theLog.printDebugInfo("-- delete content_x_media success ");
- } catch (Exception e) {
- theLog.printDebugInfo("-- 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) {
- theLog.printDebugInfo("-- 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) {
- theLog.printDebugInfo("-- get content failed");
- throw new StorageObjectFailure("-- get content failed -- ",e );
- }
- finally { freeConnection(con,stmt);}
-
- return returnList;
- }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.sql.Connection;\r
+import java.sql.ResultSet;\r
+import java.sql.Statement;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.entity.EntityList;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectExc;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityUploadedMedia;\r
+\r
+/**\r
+ * <b>implements abstract DB connection to the content_x_media SQL table\r
+ *\r
+ * @author RK, mir-coders group\r
+ * @version $Id: DatabaseContentToMedia.java,v 1.13 2003/02/20 16:05:35 zapata Exp $\r
+ *\r
+ */\r
+\r
+public class DatabaseContentToMedia extends Database implements StorageObject{\r
+\r
+ private static DatabaseContentToMedia instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo.\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseContentToMedia getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseContentToMedia();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseContentToMedia() throws StorageObjectFailure {\r
+ super();\r
+ logger = new LoggerWrapper("Database.ContentToMedia");\r
+\r
+ hasTimestamp = false;\r
+ theTable = "content_x_media";\r
+\r
+ theEntityClass = mir.entity.GenericEntity.class;\r
+ }\r
+\r
+ /**\r
+ * get all the media-files belonging to a content entity\r
+ *\r
+ */\r
+ public EntityList getMedia(EntityContent content) throws StorageObjectFailure {\r
+ EntityList returnList = null;\r
+ if (content != null) {\r
+ // get all to_topic from media_x_topic\r
+ String id = content.getId();\r
+ String subselect = "id in (select media_id from " + theTable +\r
+ " where content_id=" + id + ")";\r
+\r
+ try {\r
+ // media should stay in uploaded order. this is especially important\r
+ // for photo stories which require a specific chronologic order.\r
+ // this is why we have the the second parameter "id"\r
+ returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect,\r
+ "id", -1);\r
+ }\r
+ catch (Throwable e) {\r
+ logger.debug("-- get media failed " + e.toString());\r
+ throw new StorageObjectFailure("-- get media failed ", e);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ public boolean hasMedia(EntityContent content) throws StorageObjectFailure,\r
+ StorageObjectExc {\r
+ if (content != null) {\r
+ try {\r
+ if (selectByWhereClause("content_id=" + content.getId(), -1).size() ==\r
+ 0)\r
+ return false;\r
+ else\r
+ return true;\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("DatabaseContentToMedia.hasMedia: " + e.toString());\r
+ throw new StorageObjectFailure("DatabaseContentToMedia.hasMedia: " +\r
+ e.toString(), e);\r
+ }\r
+ }\r
+ else {\r
+ logger.error("DatabaseContentToMedia.hasMedia: content == null");\r
+ throw new StorageObjectExc(\r
+ "DatabaseContentToMedia.hasMedia: content == null");\r
+ }\r
+ }\r
+\r
+ /**\r
+ * get all the audio belonging to a content entity\r
+ *\r
+ */\r
+ public EntityList getAudio(EntityContent content) throws StorageObjectFailure {\r
+ EntityList returnList = null;\r
+ if (content != null) {\r
+ // get all to_topic from media_x_topic\r
+ String id = content.getId();\r
+ //this is not supported by mysql\r
+ String subselect = "id in (select media_id from " + theTable +\r
+ " where content_id=" + id + ")";\r
+\r
+ try {\r
+ // media should stay in uploaded order. this is especially important\r
+ // for photo stories which require a specific chronologic order.\r
+ // this is why we have the the second parameter "id"\r
+ returnList = DatabaseAudio.getInstance().selectByWhereClause(subselect,\r
+ "id", -1);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("DatabaseContentToMedia.getAudio: " + e.toString());\r
+ throw new StorageObjectFailure("DatabaseContentToMedia.getAudio: " +\r
+ e.toString(), e);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ /**\r
+ * get all the video belonging to a content entity\r
+ *\r
+ */\r
+ public EntityList getVideo(EntityContent content) throws StorageObjectFailure {\r
+ EntityList returnList = null;\r
+ if (content != null) {\r
+ // get all to_topic from media_x_topic\r
+ String id = content.getId();\r
+ //this is not supported by mysql\r
+ String subselect = "id in (select media_id from " + theTable +\r
+ " where content_id=" + id + ")";\r
+\r
+ try {\r
+ // media should stay in uploaded order. this is especially important\r
+ // for photo stories which require a specific chronologic order.\r
+ // this is why we have the the second parameter "id"\r
+ returnList = DatabaseVideo.getInstance().selectByWhereClause(subselect,\r
+ "id", -1);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("DatabaseContentToMedia.getVideo: " + e.toString());\r
+ throw new StorageObjectFailure("DatabaseContentToMedia.getVideo: " +\r
+ e.toString(), e);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ /**\r
+ * get all the images belonging to a content entity\r
+ *\r
+ */\r
+ public EntityList getImages(EntityContent content) throws\r
+ StorageObjectFailure {\r
+ EntityList returnList = null;\r
+ if (content != null) {\r
+ // get all to_topic from media_x_topic\r
+ String id = content.getId();\r
+ //this is not supported by mysql\r
+ String subselect = "id in (select media_id from " + theTable +\r
+ " where content_id=" + id + ")";\r
+\r
+ try {\r
+ // media should stay in uploaded order. this is especially important\r
+ // for photo stories which require a specific chronologic order.\r
+ // this is why we have the the second parameter "id"\r
+ returnList = DatabaseImages.getInstance().selectByWhereClause(subselect,\r
+ "id", -1);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("DatabaseContentToMedia.getImages: " + e.toString());\r
+ throw new StorageObjectFailure("DatabaseContentToMedia.getImages: " +\r
+ e.toString(), e);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ /**\r
+ * get all the uploaded/other Media belonging to a content entity\r
+ *\r
+ */\r
+ public EntityList getOther(EntityContent content) throws StorageObjectFailure {\r
+ /** @todo this should only fetch published media / rk */\r
+\r
+ EntityList returnList = null;\r
+ if (content != null) {\r
+ // get all to_topic from media_x_topic\r
+ String id = content.getId();\r
+ //this is not supported by mysql\r
+ String subselect = "id in (select media_id from " + theTable +\r
+ " where content_id=" + id + ")";\r
+\r
+ try {\r
+ // media should stay in uploaded order. this is especially important\r
+ // for photo stories which require a specific chronologic order.\r
+ // this is why we have the the second parameter "id"\r
+ returnList = DatabaseOther.getInstance().selectByWhereClause(subselect,\r
+ "id");\r
+ }\r
+ catch (Exception e) {\r
+ e.printStackTrace();\r
+ logger.error("DatabaseContentToMedia.getOther: " + e.toString());\r
+ throw new StorageObjectFailure("DatabaseContentToMedia.getOther: " +\r
+ e.toString(), e);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ /**\r
+ * get all the uploaded/other Media belonging to a content entity\r
+ *\r
+ */\r
+ public EntityList getUploadedMedia(EntityContent content) throws\r
+ StorageObjectFailure {\r
+ /** @todo this should only fetch published media / rk */\r
+\r
+ EntityList returnList = null;\r
+ if (content != null) {\r
+ // get all to_topic from media_x_topic\r
+ String id = content.getId();\r
+ //this is not supported by mysql\r
+ String subselect = "id in (select media_id from " + theTable +\r
+ " where content_id=" + id + ")";\r
+\r
+ try {\r
+ returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause(\r
+ subselect,\r
+ "id");\r
+ }\r
+ catch (Exception e) {\r
+ e.printStackTrace();\r
+ logger.error("DatabaseContentToMedia.getUploadedMedia: " + e.toString());\r
+ throw new StorageObjectFailure(\r
+ "DatabaseContentToMedia.getUploadedMedia: " + e.toString(), e);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ public void setMedia(String contentId, String[] mediaId) throws\r
+ StorageObjectFailure {\r
+ if (contentId == null) {\r
+ return;\r
+ }\r
+ if (mediaId == null || mediaId[0] == null) {\r
+ return;\r
+ }\r
+ //first delete all row with content_id=contentId\r
+ String sql = "delete from " + theTable + " where content_id=" + contentId;\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ ResultSet rs = executeSql(stmt, sql);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- set media failed -- delete");\r
+ throw new StorageObjectFailure("-- set media failed -- delete", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ //now insert\r
+ //first delete all row with content_id=contentId\r
+ for (int i = 0; i < mediaId.length; i++) {\r
+ sql = "insert into " + theTable + " (content_id,media_id) values ("\r
+ + contentId + "," + mediaId[i] + ")";\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- set topics failed -- insert");\r
+ throw new StorageObjectFailure("-- set topics failed -- insert ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+ }\r
+\r
+ public void addMedia(String contentId, String mediaId) throws\r
+ StorageObjectFailure {\r
+ if (contentId == null && mediaId == null) {\r
+ return;\r
+ }\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ //now insert\r
+\r
+ String sql = "insert into " + theTable + " (content_id,media_id) values ("\r
+ + contentId + "," + mediaId + ")";\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- add media failed -- insert");\r
+ throw new StorageObjectFailure("-- add media failed -- insert ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+\r
+ public void setMedia(String contentId, String mediaId) throws\r
+ StorageObjectFailure {\r
+ if (contentId == null && mediaId == null) {\r
+ return;\r
+ }\r
+ //first delete all row with content_id=contentId\r
+ String sql = "delete from " + theTable + " where content_id=" + contentId;\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- set media failed -- delete");\r
+ throw new StorageObjectFailure("-- set media failed -- delete ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ //now insert\r
+ //first delete all row with content_id=contentId\r
+\r
+ sql = "insert into " + theTable + " (content_id,media_id) values ("\r
+ + contentId + "," + mediaId + ")";\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- set media failed -- insert");\r
+ throw new StorageObjectFailure("-- set media failed -- insert ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+\r
+ public void deleteByContentId(String contentId) throws StorageObjectFailure {\r
+ if (contentId == null) {\r
+ //theLog.printDebugInfo("-- delete topics failed -- no content id");\r
+ return;\r
+ }\r
+ //delete all row with content_id=contentId\r
+ String sql = "delete from " + theTable + " where content_id=" + contentId;\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- delete by contentId failed ");\r
+ throw new StorageObjectFailure(\r
+ "-- delete by content id failed -- delete ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+\r
+ public void deleteByMediaId(String mediaId) throws StorageObjectFailure {\r
+ if (mediaId == null) {\r
+ //theLog.printDebugInfo("-- delete topics failed -- no topic id");\r
+ return;\r
+ }\r
+ //delete all row with content_id=contentId\r
+ String sql = "delete from " + theTable + " where media_id=" + mediaId;\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ logger.debug("-- delete media success ");\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- delete media failed ");\r
+ throw new StorageObjectFailure("-- delete by media id failed -- ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+\r
+ public void delete(String contentId, String mediaId) throws\r
+ StorageObjectFailure {\r
+ if (mediaId == null || contentId == null) {\r
+ logger.debug("-- delete media failed -- missing parameter");\r
+ return;\r
+ }\r
+ //delete all row with content_id=contentId and media_id=mediaId\r
+ String sql = "delete from " + theTable + " where media_id=" + mediaId +\r
+ " and content_id= " + contentId;\r
+\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ int rs = executeUpdate(stmt, sql);\r
+ logger.debug("-- delete content_x_media success ");\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- delete content_x_media failed ");\r
+ throw new StorageObjectFailure("-- delete content_x_media failed -- ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+\r
+ public EntityList getContent(EntityUploadedMedia media) throws\r
+ StorageObjectFailure {\r
+ EntityList returnList = null;\r
+ if (media != null) {\r
+ String id = media.getId();\r
+ String select = "select content_id from " + theTable + " where media_id=" +\r
+ id;\r
+\r
+ // execute select statement\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ ResultSet rs = executeSql(stmt, select);\r
+ if (rs != null) {\r
+ String mediaSelect = "id IN (";\r
+ boolean first = true;\r
+ while (rs.next()) {\r
+ if (first == false)\r
+ mediaSelect += ",";\r
+ mediaSelect += rs.getString(1);\r
+ first = false;\r
+ }\r
+ mediaSelect += ")";\r
+ if (first == false)\r
+ returnList = DatabaseContent.getInstance().selectByWhereClause(\r
+ mediaSelect, -1);\r
+ }\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- get content failed");\r
+ throw new StorageObjectFailure("-- get content failed -- ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+ }\r
+ return returnList;\r
+ }\r
+\r
+ /**\r
+ * Returns a EntityList with all content-objects having a relation to a media\r
+ */\r
+\r
+ public EntityList getContent() throws StorageObjectFailure {\r
+ EntityList returnList = null;\r
+\r
+ String select = "select distinct content_id from " + theTable;\r
+ // execute select statement\r
+ Connection con = null;\r
+ Statement stmt = null;\r
+ try {\r
+ con = getPooledCon();\r
+ // should be a preparedStatement because is faster\r
+ stmt = con.createStatement();\r
+ ResultSet rs = executeSql(stmt, select);\r
+ if (rs != null) {\r
+ String mediaSelect = "id IN (";\r
+ boolean first = true;\r
+ while (rs.next()) {\r
+ if (first == false)\r
+ mediaSelect += ",";\r
+ mediaSelect += rs.getString(1);\r
+ first = false;\r
+ }\r
+ mediaSelect += ")";\r
+ if (first == false)\r
+ returnList = DatabaseContent.getInstance().selectByWhereClause(\r
+ mediaSelect, "webdb_lastchange desc");\r
+ }\r
+ }\r
+ catch (Exception e) {\r
+ logger.error("-- get content failed");\r
+ throw new StorageObjectFailure("-- get content failed -- ", e);\r
+ }\r
+ finally {\r
+ freeConnection(con, stmt);\r
+ }\r
+\r
+ return returnList;\r
+ }\r
+\r
+}\r
import java.util.Collection;
import java.util.Iterator;
+import mir.log.LoggerWrapper;
import mir.entity.EntityList;
import mir.storage.Database;
import mir.storage.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); }
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;
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;
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);
}
}
}
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
}
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
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);
}
// 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);
}
// 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);
}
}
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;
-/*
- * 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;
-
-/**
- * <b>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);
- }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import freemarker.template.SimpleList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseFeature extends Database implements StorageObject{\r
+\r
+ private static DatabaseFeature instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseFeature getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseFeature();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseFeature() throws StorageObjectFailure {\r
+ super();\r
+ logger = new LoggerWrapper("Database.Feature");\r
+\r
+ hasTimestamp = false;\r
+ theTable = "feature";\r
+\r
+ theEntityClass = mircoders.entity.EntityFeature.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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); }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import freemarker.template.SimpleList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseImageColor extends Database implements StorageObject{\r
+\r
+ private static DatabaseImageColor instance;\r
+ private static SimpleList publisherPopupData;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseImageColor getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseImageColor();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseImageColor() {\r
+ super();\r
+ logger = new LoggerWrapper("Database.ImageColor");\r
+ hasTimestamp = false;\r
+ theTable = "img_color";\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("name", true);\r
+ }\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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); }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import freemarker.template.SimpleList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseImageFormat extends Database implements StorageObject{\r
+\r
+ private static DatabaseImageFormat instance;\r
+ private static SimpleList publisherPopupData;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseImageFormat getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseImageFormat();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseImageFormat() {\r
+ super();\r
+ logger = new LoggerWrapper("Database.ImageFormat");\r
+ hasTimestamp = false;\r
+ theTable = "img_format";\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("name", true);\r
+ }\r
+\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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); }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import freemarker.template.SimpleList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseImageLayout extends Database implements StorageObject{\r
+\r
+ private static DatabaseImageLayout instance;\r
+ private static SimpleList publisherPopupData;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseImageLayout getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseImageLayout();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseImageLayout() {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.ImageLayout");\r
+ hasTimestamp = false;\r
+ theTable = "img_layout";\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("name", true);\r
+ }\r
+\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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); }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import freemarker.template.SimpleList;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseImageType extends Database implements StorageObject{\r
+ private static DatabaseImageType instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseImageType getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseImageType();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseImageType() {\r
+ super();\r
+ logger = new LoggerWrapper("Database.ImageType");\r
+\r
+ hasTimestamp = false;\r
+ theTable = "img_type";\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("name", true);\r
+ }\r
+\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.util.GregorianCalendar;\r
+\r
+import freemarker.template.SimpleList;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.entity.Entity;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseImages extends Database implements StorageObject{\r
+\r
+ private static DatabaseImages instance;\r
+ private static SimpleList publisherPopupData;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseImages getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseImages();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseImages() {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.Images");\r
+\r
+ hasTimestamp = true;\r
+ theTable = "images";\r
+ theCoreTable = "media";\r
+ theEntityClass = mircoders.entity.EntityImages.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+\r
+ public void update(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+\r
+ super.update(theEntity);\r
+ }\r
+\r
+ public String insert(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+\r
+ return super.insert(theEntity);\r
+ }\r
+\r
+ // initialisierungen aus den statischen Tabellen\r
+\r
+}\r
* @version 1.0\r
*/\r
\r
+import freemarker.template.SimpleList;\r
+\r
+import mir.log.LoggerWrapper;\r
import mir.storage.Database;\r
import mir.storage.StorageObject;\r
import mir.storage.StorageObjectFailure;\r
-import freemarker.template.SimpleList;\r
\r
\r
public class DatabaseLanguage extends Database implements StorageObject{\r
\r
private DatabaseLanguage() throws StorageObjectFailure {\r
super();\r
+ logger = new LoggerWrapper("Database.Language");\r
+\r
this.hasTimestamp = false;\r
this.theTable = "language";\r
}\r
import java.sql.PreparedStatement;\r
import java.sql.ResultSet;\r
import java.sql.SQLException;\r
-import java.util.ArrayList;\r
+import java.util.List;\r
import java.util.HashMap;\r
\r
+import mir.log.LoggerWrapper;\r
import mir.entity.Entity;\r
import mir.storage.Database;\r
import mir.storage.StorageObject;\r
*\r
*\r
*/\r
-public class DatabaseLinksImcs extends Database\r
- implements StorageObject {\r
+public class DatabaseLinksImcs extends Database implements StorageObject {\r
+\r
private static DatabaseLinksImcs instance;\r
\r
- /**\r
- * put your documentation comment here\r
- * @return\r
- * @exception StorageObjectException\r
- */\r
- // the following *has* to be sychronized cause this static method\r
- // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
- // see the "Singletons with needles and thread" article at JavaWorld -mh\r
- public synchronized static DatabaseLinksImcs getInstance() throws\r
- StorageObjectFailure {\r
+ public static DatabaseLinksImcs getInstance() {\r
if (instance == null) {\r
- instance = new DatabaseLinksImcs();\r
- instance.myselfDatabase = instance;\r
+ synchronized (DatabaseLinksImcs.class) {\r
+ if (instance == null) {\r
+ DatabaseLinksImcs newInstance;\r
+\r
+ newInstance = new DatabaseLinksImcs();\r
+ newInstance.myselfDatabase = newInstance;\r
+ instance = newInstance;\r
+ }\r
+ }\r
}\r
+\r
return instance;\r
}\r
\r
- /**\r
- * put your documentation comment here\r
- */\r
- private DatabaseLinksImcs() throws StorageObjectFailure {\r
+ private DatabaseLinksImcs() {\r
super();\r
- ////this.cache = new HashMap();\r
- this.hasTimestamp = false;\r
- this.theTable = "links_imcs";\r
- try {\r
- this.theEntityClass = Class.forName("mircoders.entity.EntityLinksImcs");\r
- }\r
- catch (Exception e) {\r
- throw new StorageObjectFailure(e);\r
- }\r
+\r
+ logger = new LoggerWrapper("ServletModule.Database.LinksImcs");\r
+ hasTimestamp = false;\r
+ theTable = "links_imcs";\r
+\r
+ theEntityClass = mircoders.entity.EntityLinksImcs.class;\r
}\r
\r
/** @todo toooo much copy/paste in this class //rk */\r
invalidatePopupCache();\r
try {\r
HashMap theEntityValues = theEntity.getValues();\r
- ArrayList streamedInput = theEntity.streamedInput();\r
+ List streamedInput = theEntity.streamedInput();\r
StringBuffer f = new StringBuffer();\r
StringBuffer v = new StringBuffer();\r
String aField, aValue;\r
}\r
} // end for\r
// insert into db\r
- StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).\r
- append("(").append(f).append(") values (").append(v).append(")");\r
+ StringBuffer sqlBuf =\r
+ new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");\r
String sql = sqlBuf.toString();\r
- theLog.printInfo("INSERT: " + sql);\r
+\r
+ logger.info("INSERT: " + sql);\r
+\r
con = getPooledCon();\r
con.setAutoCommit(false);\r
pstmt = con.prepareStatement(sql);\r
public void update(Entity theEntity) throws StorageObjectFailure {\r
Connection con = null;\r
PreparedStatement pstmt = null;\r
- ArrayList streamedInput = theEntity.streamedInput();\r
+ List streamedInput = theEntity.streamedInput();\r
HashMap theEntityValues = theEntity.getValues();\r
String id = theEntity.getId();\r
String aField;\r
}\r
}\r
sql.append(" where id=").append(id);\r
- theLog.printInfo("UPDATE: " + sql);\r
+ logger.info("UPDATE: " + sql);\r
// execute sql\r
try {\r
con = getPooledCon();\r
package mircoders.storage;
+import mir.log.LoggerWrapper;
import mir.entity.Entity;
import mir.entity.EntityRelation;
import mir.storage.Database;
// 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;
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
* 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;
}
}
package mircoders.storage;
+import mir.log.LoggerWrapper;
import mir.storage.Database;
import mir.storage.StorageObject;
import mir.storage.StorageObjectFailure;
// 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;
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;
}
}
* @version
*/
+import mir.log.LoggerWrapper;
import mir.storage.Database;
import mir.storage.StorageObject;
import mir.storage.StorageObjectFailure;
// 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;
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 {
package mircoders.storage;
+import mir.log.LoggerWrapper;
import mir.storage.Database;
import mir.storage.StorageObject;
import mir.storage.StorageObjectFailure;
// 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;
return instance;
}
- private DatabaseMessages() throws StorageObjectFailure
+ private DatabaseMessages()
{
super();
- //this.cache = new DatabaseCache(10);
+
+ logger = new LoggerWrapper("Database.Messages");
+
this.theTable="messages";
}
-/*
- * 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;
-
-/**
- * <b>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
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+\r
+import java.util.GregorianCalendar;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.entity.Entity;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseOther extends Database implements StorageObject{\r
+ private static DatabaseOther instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseOther getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseOther();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseOther() {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.OtherMedia");\r
+\r
+ hasTimestamp = true;\r
+ theTable = "other_media";\r
+ theCoreTable = "media";\r
+ theEntityClass = mircoders.entity.EntityOther.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+\r
+ public void update(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+\r
+ super.update(theEntity);\r
+ }\r
+\r
+ public String insert(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+ return super.insert(theEntity);\r
+ }\r
+\r
+ // initialisierungen aus den statischen Tabellen\r
+\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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); }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseRights extends Database implements StorageObject{\r
+ private static DatabaseRights instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseRights getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseRights();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseRights() throws StorageObjectFailure {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.Rights");\r
+\r
+ hasTimestamp = false;\r
+ theTable = "rights";\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("name", true);\r
+ }\r
+\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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);
- }
-
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseTopics extends Database implements StorageObject{\r
+\r
+ private static DatabaseTopics instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseTopics getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseTopics();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseTopics() throws StorageObjectFailure {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.Topics");\r
+\r
+ hasTimestamp = false;\r
+ theTable = "topic";\r
+ theEntityClass = mircoders.entity.EntityTopics.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+}\r
package mircoders.storage;
+import mir.log.LoggerWrapper;
import mir.entity.Entity;
import mir.entity.EntityRelation;
import mir.storage.Database;
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);
* 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;
}
-/*
- * 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;
-
-/**
- * <b>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);
- }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseUsers extends Database implements StorageObject{\r
+\r
+ private static DatabaseUsers instance;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseUsers getInstance() throws\r
+ StorageObjectFailure {\r
+ if (instance == null) {\r
+ instance = new DatabaseUsers();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseUsers() throws StorageObjectFailure {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.Users");\r
+\r
+ hasTimestamp = false;\r
+ theTable = "webdb_users";\r
+ theEntityClass = mircoders.entity.EntityUsers.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("login", true);\r
+ }\r
+}\r
-/*
- * 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;
-
-/**
- * <b>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);
- }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with the com.oreilly.servlet library, any library\r
+ * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
+ * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
+ * the above that use the same license as the above), and distribute linked\r
+ * combinations including the two. You must obey the GNU General Public\r
+ * License in all respects for all of the code used other than the above\r
+ * mentioned libraries. If you modify this file, you may extend this exception\r
+ * to your version of the file, but you are not obligated to do so. If you do\r
+ * not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.util.GregorianCalendar;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.entity.Entity;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import freemarker.template.SimpleList;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseVideo extends Database implements StorageObject{\r
+\r
+ private static DatabaseVideo instance;\r
+ private static SimpleList publisherPopupData;\r
+\r
+ // the following *has* to be sychronized cause this static method\r
+ // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+ // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+ public synchronized static DatabaseVideo getInstance() {\r
+ if (instance == null) {\r
+ instance = new DatabaseVideo();\r
+ instance.myselfDatabase = instance;\r
+ }\r
+ return instance;\r
+ }\r
+\r
+ private DatabaseVideo() {\r
+ super();\r
+\r
+ logger = new LoggerWrapper("Database.Video");\r
+\r
+ hasTimestamp = true;\r
+ theTable = "video";\r
+ theCoreTable = "media";\r
+ theEntityClass = mircoders.entity.EntityVideo.class;\r
+ }\r
+\r
+ public SimpleList getPopupData() throws StorageObjectFailure {\r
+ return getPopupData("title", true);\r
+ }\r
+\r
+ public void update(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+\r
+ super.update(theEntity);\r
+ }\r
+\r
+ public String insert(Entity theEntity) throws StorageObjectFailure {\r
+ String date = theEntity.getValue("date");\r
+ if (date == null) {\r
+ date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+ theEntity.setValueForProperty("date", date);\r
+ }\r
+ return super.insert(theEntity);\r
+ }\r
+\r
+}\r