465366bc0ba2364f6bb2d285eda98d8c6d433970
[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  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package  mir.entity;
31
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35
36 import mir.config.MirPropertiesConfiguration;
37 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
38 import mir.log.LoggerWrapper;
39 import mir.misc.StringUtil;
40 import mir.storage.StorageObject;
41 import mir.storage.StorageObjectExc;
42 import mir.storage.StorageObjectFailure;
43 import freemarker.template.SimpleScalar;
44 import freemarker.template.TemplateHashModel;
45 import freemarker.template.TemplateModel;
46 import freemarker.template.TemplateModelException;
47 import freemarker.template.TemplateModelRoot;
48
49 /**
50  * Base class the entities are derived from. Provides base functionality of
51  * an entity. Entities are used to represent rows of a database table.<p>
52  * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant
53  *
54  * @version $Id: Entity.java,v 1.21.2.1 2003/05/22 03:15:07 zapata Exp $
55  * @author rk
56  *
57  */
58
59 public class Entity implements TemplateHashModel, TemplateModelRoot
60 {
61   protected static MirPropertiesConfiguration configuration;
62
63   protected Map theValuesHash; // tablekey / value
64   protected StorageObject theStorageObject;
65   protected List streamedInput = null;
66   protected LoggerWrapper logger;
67
68   static {
69     try {
70       configuration = MirPropertiesConfiguration.instance();
71     }
72     catch (PropertiesConfigExc e) {
73       throw new RuntimeException(e.getMessage());
74     }
75   }
76
77   public Entity() {
78     logger = new LoggerWrapper("Entity");
79   }
80
81   /**
82    * Constructor
83    * @param StorageObject The StorageObject of the Entity.
84    */
85   public Entity(StorageObject StorageObject) {
86     this();
87     setStorage(StorageObject);
88   }
89
90   /*
91    * Sets the StorageObject of the Entity.
92    */
93   public void setStorage(StorageObject storage) {
94     this.theStorageObject = storage;
95   }
96
97   /**
98    * Sets the values of the Entity. (Only to be called by the Storage Object)
99    * @param theStringValues Map containing the new values of the Entity
100    */
101
102   public void setValues(Map theStringValues) {
103     /** @todo should be synchronized */
104     if (theStringValues != null) {
105       theValuesHash = new HashMap();
106       theValuesHash.putAll(theStringValues);
107     }
108     else
109       logger.warn("Entity.setValues called with null Map");
110   }
111
112   /**
113    * Returns the primary key of the Entity.
114    * @return String Id
115    */
116   public String getId() {
117     return (String) getValue(theStorageObject.getIdName());
118   }
119
120   /**
121    * Defines the primary key of the Entity (only to be set by the StorageObject)
122    * @param id
123    */
124   public void setId(String id) {
125     theValuesHash.put(theStorageObject.getIdName(), id);
126   }
127
128   /**
129    * Returns the value of a field by field name.
130    * @param field The name of the field
131    * @return value of the field
132    */
133   public String getValue(String field) {
134     String returnValue = null;
135     if (field != null) {
136       if (field.equals("webdb_create_formatted")) {
137         if (hasValueForField("webdb_create"))
138           returnValue = StringUtil.dateToReadableDate(getValue("webdb_create"));
139       }
140       else if (field.equals("webdb_lastchange_formatted")) {
141         if (hasValueForField("webdb_lastchange"))
142           returnValue = StringUtil.dateToReadableDate(getValue(
143               "webdb_lastchange"));
144       }
145       else
146         returnValue = (String) theValuesHash.get(field);
147     }
148     return returnValue;
149   }
150
151   public boolean hasValueForField(String field) {
152     if (theValuesHash != null)
153       return theValuesHash.containsKey(field);
154     return false;
155   }
156
157   /**
158    * Insers Entity into the database via StorageObject
159    * @return Primary Key of the Entity
160    * @exception StorageObjectException
161    */
162   public String insert() throws StorageObjectExc {
163     logger.debug("Entity: trying to insert ...");
164     if (theStorageObject != null) {
165       return theStorageObject.insert(this);
166     }
167     else
168       throw new StorageObjectExc("theStorageObject == null!");
169   }
170
171   /**
172    * Saves changes of this Entity to the database
173    * @exception StorageObjectException
174    */
175   public void update() throws StorageObjectFailure {
176     theStorageObject.update(this);
177   }
178
179   /**
180    * Sets the value for a field. Issues a log message if the field name
181    * supplied was not found in the Entity.
182    * @param theProp The field name whose value has to be set
183    * @param theValue The new value of the field
184    * @exception StorageObjectException
185    */
186   public void setValueForProperty(String theProp, String theValue) throws StorageObjectFailure {
187     if (isField(theProp))
188       theValuesHash.put(theProp, theValue);
189     else {
190       logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")");
191     }
192   }
193
194   /**
195    * Returns the field names of the Entity as ArrayListe.
196    * @return ArrayList with field names
197        * @exception StorageObjectException is throuwn if database access was impossible
198    */
199   public List getFields() throws StorageObjectFailure {
200     return theStorageObject.getFields();
201   }
202
203   /**
204    * Returns an int[] with the types of the fields
205    * @return int[] that contains the types of the fields
206    * @exception StorageObjectException
207    */
208   public int[] getTypes() throws StorageObjectFailure {
209     return theStorageObject.getTypes();
210   }
211
212   /**
213    * Returns an ArrayList with field names
214    * @return List with field names
215    * @exception StorageObjectException
216    */
217   public List getLabels() throws StorageObjectFailure {
218     return theStorageObject.getLabels();
219   }
220
221
222   /**
223    * Returns an ArrayList with all database fields that can
224    * be evaluated as streamedInput.
225    * Could be automated by the types (blob, etc.)
226    * Until now to be created manually in the inheriting class
227    *
228    *  Liefert einen ArrayList mit allen Datenbankfeldern, die
229    *  als streamedInput ausgelesen werden muessen.
230    *  Waere automatisierbar ueber die types (blob, etc.)
231    *  Bisher manuell anzulegen in der erbenden Klasse
232    */
233
234   public List streamedInput() {
235     return streamedInput;
236   }
237
238   /** Returns whether fieldName is a valid field name of this Entity.
239    * @param fieldName
240    * @return true in case fieldName is a field name, else false.
241    * @exception StorageObjectException
242    */
243   public boolean isField(String fieldName) throws StorageObjectFailure {
244     return theStorageObject.getFields().contains(fieldName);
245   }
246
247   protected void throwStorageObjectFailure(Throwable e, String wo) throws StorageObjectFailure {
248     logger.error(e.toString() + " function: " + wo);
249     e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
250
251     throw new StorageObjectFailure("Storage Object Exception in entity", e);
252   }
253
254   // Now implements freemarkers TemplateHashModel
255   // two methods have to be overridden:
256   // 1. public boolean isEmpty() throws TemplateModelException
257   // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException
258
259   public boolean isEmpty() throws TemplateModelException {
260     return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false;
261   }
262
263   public TemplateModel get(java.lang.String key) throws TemplateModelException {
264     return new SimpleScalar(getValue(key));
265   }
266
267   public void put(java.lang.String key, TemplateModel model) {
268     // putting should only take place via setValue and is limited to the
269     // database fields associated with the entity. no additional freemarker
270     // stuff will be available via Entity.
271     logger.warn("put is called on entity! - the values will be lost!");
272   }
273
274   public void remove(java.lang.String key) {
275     // do we need this?
276   }
277
278   //////////////////////////////////////////////////////////////////////////////////
279 }
280