new admin templates! with many thanks to init...
[mir.git] / source / mir / entity / Entity.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 /**
33  * Base class the entities are derived from. Provides base functionality of
34  * an entity. Entities are used to represent rows of a database table.<p>
35  */
36
37 package  mir.entity;
38
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42
43 import mir.config.MirPropertiesConfiguration;
44 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
45 import mir.log.LoggerWrapper;
46 import mir.misc.StringUtil;
47 import mir.storage.StorageObject;
48 import mir.storage.StorageObjectExc;
49 import mir.storage.StorageObjectFailure;
50 import freemarker.template.SimpleScalar;
51 import freemarker.template.TemplateHashModel;
52 import freemarker.template.TemplateModel;
53 import freemarker.template.TemplateModelException;
54 import freemarker.template.TemplateModelRoot;
55
56 /**
57  * Base Class of Entities
58  * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant
59  *
60  * @version $Id: Entity.java,v 1.19 2003/04/09 02:06:06 zapata Exp $
61  * @author rk
62  *
63  */
64
65 public class Entity implements TemplateHashModel, TemplateModelRoot
66 {
67   protected static MirPropertiesConfiguration configuration;
68
69   private boolean changed;
70   protected Map theValuesHash; // tablekey / value
71   protected StorageObject theStorageObject;
72   protected List streamedInput = null;
73   protected LoggerWrapper logger;
74
75   static {
76     try {
77       configuration = MirPropertiesConfiguration.instance();
78     }
79     catch (PropertiesConfigExc e) {
80       throw new RuntimeException(e.getMessage());
81     }
82   }
83
84   public Entity() {
85     logger = new LoggerWrapper("Entity");
86
87     this.changed = false;
88   }
89
90   /**
91    * Constructor
92    * @param StorageObject The StorageObject of the Entity.
93    */
94   public Entity(StorageObject StorageObject) {
95     this();
96     setStorage(StorageObject);
97   }
98
99   /*
100    * Sets the StorageObject of the Entity.
101    */
102   public void setStorage(StorageObject storage) {
103     this.theStorageObject = storage;
104   }
105
106   /**
107    * Sets the values of the Entity.
108    * @param theStringValues Map containing the new values of the Entity
109    */
110
111   public void setValues(Map theStringValues) {
112     /** @todo should be synchronized */
113     if (theStringValues != null) {
114       theValuesHash = new HashMap();
115       theValuesHash.putAll(theStringValues);
116     }
117     else
118       logger.warn("Entity.setValues called with null Map");
119   }
120
121   /**
122    * Returns whether the content of the Entity has changed.
123    * @return true wenn ja, sonst false
124    */
125   public boolean changed() {
126     return changed;
127   }
128
129   /**
130    * Returns the primary key of the Entity.
131    * @return String Id
132    */
133   public String getId() {
134     return (String) getValue(theStorageObject.getIdName());
135   }
136
137   /**
138    * Defines the primary key of the Entity
139    * @param id
140    */
141   public void setId(String id) {
142     theValuesHash.put(theStorageObject.getIdName(), id);
143   }
144
145   /**
146    * Returns the value of a field by field name.
147    * @param field The name of the field
148    * @return value of the field
149    */
150   public String getValue(String field) {
151     String returnValue = null;
152     if (field != null) {
153       if (field.equals("webdb_create_formatted")) {
154         if (hasValueForField("webdb_create"))
155           returnValue = StringUtil.dateToReadableDate(getValue("webdb_create"));
156       }
157       else if (field.equals("webdb_lastchange_formatted")) {
158         if (hasValueForField("webdb_lastchange"))
159           returnValue = StringUtil.dateToReadableDate(getValue(
160               "webdb_lastchange"));
161       }
162       else
163         returnValue = (String) theValuesHash.get(field);
164     }
165     return returnValue;
166   }
167
168   public boolean hasValueForField(String field) {
169     if (theValuesHash != null)
170       return theValuesHash.containsKey(field);
171     return false;
172   }
173
174   /**
175    * Insers Entity into the database via StorageObject
176    * @return Primary Key of the Entity
177    * @exception StorageObjectException
178    */
179   public String insert() throws StorageObjectExc {
180     logger.debug("Entity: trying to insert ...");
181     if (theStorageObject != null) {
182       return theStorageObject.insert( (Entity)this);
183     }
184     else
185       throw new StorageObjectExc("theStorageObject == null!");
186   }
187
188   /**
189    * Saves changes of this Entity to the database
190    * @exception StorageObjectException
191    */
192   public void update() throws StorageObjectFailure {
193     theStorageObject.update( (Entity)this);
194   }
195
196   /**
197    * Sets the value for a field. Issues a log message if the field name
198    * supplied was not found in the Entity.
199    * @param theProp The field name whose value has to be set
200    * @param theValue The new value of the field
201    * @exception StorageObjectException
202    */
203   public void setValueForProperty(String theProp, String theValue) throws
204       StorageObjectFailure {
205     this.changed = true;
206     if (isField(theProp))
207       theValuesHash.put(theProp, theValue);
208     else {
209       logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")");
210     }
211
212   }
213
214   /**
215    * Returns the field names of the Entity as ArrayListe.
216    * @return ArrayList with field names
217        * @exception StorageObjectException is throuwn if database access was impossible
218    */
219   public List getFields() throws StorageObjectFailure {
220     return theStorageObject.getFields();
221   }
222
223   /**
224    * Returns an int[] with the types of the fields
225    * @return int[] that contains the types of the fields
226    * @exception StorageObjectException
227    */
228   public int[] getTypes() throws StorageObjectFailure {
229     return theStorageObject.getTypes();
230   }
231
232   /**
233    * Returns an ArrayList with field names
234    * @return List with field names
235    * @exception StorageObjectException
236    */
237   public List getLabels() throws StorageObjectFailure {
238     return theStorageObject.getLabels();
239   }
240
241   /**
242    * Returns a Map with all values of the Entity.
243    * @return Map with field name as key and the corresponding values
244    *
245        * @deprecated This method is deprecated and will be deleted in the next release.
246    *  Entity interfaces freemarker.template.TemplateHashModel now and can
247    *  be used in the same way as SimpleHash.
248    */
249   public Map getValues() {
250     logger.warn("using deprecated Entity.getValues() - a waste of resources");
251     return theValuesHash;
252   }
253
254   /**
255    * Returns an ArrayList with all database fields that can
256    * be evaluated as streamedInput.
257    * Could be automated by the types (blob, etc.)
258    * Until now to be created manually in the inheriting class
259    *
260    *  Liefert einen ArrayList mit allen Datenbankfeldern, die
261    *  als streamedInput ausgelesen werden muessen.
262    *  Waere automatisierbar ueber die types (blob, etc.)
263    *  Bisher manuell anzulegen in der erbenden Klasse
264    */
265
266   public List streamedInput() {
267     return streamedInput;
268   }
269
270   /** Returns whether fieldName is a valid field name of this Entity.
271    * @param fieldName
272    * @return true in case fieldName is a field name, else false.
273    * @exception StorageObjectException
274    */
275   public boolean isField(String fieldName) throws StorageObjectFailure {
276     return theStorageObject.getFields().contains(fieldName);
277   }
278
279   protected void throwStorageObjectFailure(Throwable e, String wo) throws
280       StorageObjectFailure {
281     logger.error(e.toString() + " function: " + wo);
282     e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
283
284     throw new StorageObjectFailure("Storage Object Exception in entity", e);
285   }
286
287   // Now implements freemarkers TemplateHashModel
288   // two methods have to be overridden:
289   // 1. public boolean isEmpty() throws TemplateModelException
290   // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException
291
292   public boolean isEmpty() throws TemplateModelException {
293     return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false;
294   }
295
296   public TemplateModel get(java.lang.String key) throws TemplateModelException {
297     return new SimpleScalar(getValue(key));
298   }
299
300   public void put(java.lang.String key, TemplateModel model) {
301     // putting should only take place via setValue and is limited to the
302     // database fields associated with the entity. no additional freemarker
303     // stuff will be available via Entity.
304     logger.warn("put is called on entity! - the values will be lost!");
305   }
306
307   public void remove(java.lang.String key) {
308     // do we need this?
309   }
310
311   //////////////////////////////////////////////////////////////////////////////////
312 }
313