some small changes delting unneeded imports. two new exceptions in mir.storage. usage...
[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.ArrayList;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.Set;
43
44 import mir.config.MirPropertiesConfiguration;
45 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
46 import mir.misc.Logfile;
47 import mir.misc.StringUtil;
48 import mir.storage.StorageObject;
49 import mir.storage.StorageObjectExc;
50 import mir.storage.StorageObjectFailure;
51 import freemarker.template.SimpleScalar;
52 import freemarker.template.TemplateHashModel;
53 import freemarker.template.TemplateModel;
54 import freemarker.template.TemplateModelException;
55 import freemarker.template.TemplateModelRoot;
56
57 /**
58  * Base Class of Entities
59  * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant
60  *
61  * @version $Id: Entity.java,v 1.13 2003/01/25 17:45:17 idfx Exp $
62  * @author rk
63  *
64  */
65
66 public class Entity implements TemplateHashModel, TemplateModelRoot
67 {
68   protected static MirPropertiesConfiguration configuration;
69   protected static Logfile    theLog;
70   
71   private boolean             changed;
72   protected HashMap           theValuesHash;   // tablekey / value
73   protected StorageObject     theStorageObject;
74   protected ArrayList         streamedInput=null;
75   
76
77     static {      
78       try {
79         configuration = MirPropertiesConfiguration.instance();
80       } catch (PropertiesConfigExc e) {
81         e.printStackTrace();
82       }
83       theLog = Logfile.getInstance(configuration.getStringWithHome("Entity.Logfile"));
84     }
85
86     public Entity() {
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 HashMap containing the new values of the Entity
109    */
110
111   public void setValues(HashMap theStringValues)
112   {
113     /** @todo should be synchronized */
114     if (theStringValues!=null) {
115       theValuesHash = new HashMap();
116       String aKey;
117       Set set = theStringValues.keySet();
118       Iterator it = set.iterator();
119       int size = set.size();
120       for (int i = 0; i < size; i++) {
121         aKey = (String)it.next();
122         theValuesHash.put(aKey, (String)theStringValues.get(aKey));
123       }
124     }
125     else theLog.printWarning("Entity.setValues called with null HashMap");
126  }
127
128   /**
129    * Returns whether the content of the Entity has changed.
130    * @return true wenn ja, sonst false
131    */
132   public boolean changed () {
133     return  changed;
134   }
135
136   /**
137    * Returns the primary key of the Entity.
138    * @return String Id
139    */
140   public String getId () {
141     return  (String) getValue(theStorageObject.getIdName());
142   }
143
144   /**
145    * Defines the primary key of the Entity
146    * @param id
147    */
148   public void setId (String id) {
149     theValuesHash.put(theStorageObject.getIdName(), id);
150       }
151
152   /**
153    * Returns the value of a field by field name.
154    * @param field The name of the field
155    * @return value of the field
156    */
157   public String getValue (String field) {
158     String returnValue = null;
159     if (field != null)
160     {
161       if (field.equals("webdb_create_formatted"))
162       {
163         if (hasValueForField("webdb_create"))
164           returnValue=StringUtil.dateToReadableDate(getValue("webdb_create"));
165       }
166       else if (field.equals("webdb_lastchange_formatted"))
167       {
168         if (hasValueForField("webdb_lastchange"))
169           returnValue=StringUtil.dateToReadableDate(getValue("webdb_lastchange"));
170       }
171       else
172         returnValue = (String)theValuesHash.get(field);
173     }
174     return returnValue;
175   }
176
177   public boolean hasValueForField(String field)
178   {
179     if (theValuesHash!=null)
180       return theValuesHash.containsKey(field);
181     return false;
182   }
183
184   /**
185    * Insers Entity into the database via StorageObject
186    * @return Primary Key of the Entity
187    * @exception StorageObjectException
188    */
189   public String insert () throws StorageObjectExc {
190     theLog.printDebugInfo("Entity: trying to insert ...");
191     if (theStorageObject != null) {
192       return theStorageObject.insert((Entity)this);
193     }
194     else
195       throw  new StorageObjectExc("Kein StorageObject gesetzt!");
196   }
197
198   /**
199    * Saves changes of this Entity to the database
200    * @exception StorageObjectException
201    */
202   public void update () throws StorageObjectFailure {
203     theStorageObject.update((Entity)this);
204   }
205
206   /**
207    * Sets the value for a field. Issues a log message if the field name
208    * supplied was not found in the Entity.
209    * @param theProp The field name whose value has to be set
210    * @param theValue The new value of the field
211    * @exception StorageObjectException
212    */
213   public void setValueForProperty (String theProp, String theValue)
214     throws StorageObjectFailure {
215     this.changed = true;
216     if (isField(theProp))
217       theValuesHash.put(theProp, theValue);
218     else {
219       theLog.printWarning("Property not found: " + theProp+theValue);
220     }
221
222   }
223
224   /**
225    * Returns the field names of the Entity as ArrayListe.
226    * @return ArrayList with field names
227    * @exception StorageObjectException is throuwn if database access was impossible
228    */
229   public ArrayList getFields () throws StorageObjectFailure {
230     return  theStorageObject.getFields();
231     }
232
233   /**
234    * Returns an int[] with the types of the fields
235    * @return int[] that contains the types of the fields
236    * @exception StorageObjectException
237    */
238   public int[] getTypes () throws StorageObjectFailure {
239     return  theStorageObject.getTypes();
240     }
241
242   /**
243    * Returns an ArrayList with field names
244    * @return List with field names
245    * @exception StorageObjectException
246    */
247   public ArrayList getLabels () throws StorageObjectFailure {
248     return  theStorageObject.getLabels();
249     }
250
251   /**
252    * Returns a Hashmap with all values of the Entity.
253    * @return HashMap with field name as key and the corresponding values
254    *
255    * @deprecated This method is deprecated and will be deleted in the next release.
256    *  Entity interfaces freemarker.template.TemplateHashModel now and can
257    *  be used in the same way as SimpleHash.
258
259    */
260     public HashMap getValues() {
261       theLog.printWarning("## using deprecated Entity.getValues() - a waste of resources");
262       return theValuesHash;
263     }
264
265     /**
266      * Returns an ArrayList with all database fields that can
267      * be evaluated as streamedInput.
268      * Could be automated by the types (blob, etc.)
269      * Until now to be created manually in the inheriting class
270      *
271      *  Liefert einen ArrayList mit allen Datenbankfeldern, die
272      *  als streamedInput ausgelesen werden muessen.
273      *  Waere automatisierbar ueber die types (blob, etc.)
274      *  Bisher manuell anzulegen in der erbenden Klasse
275      */
276
277   public ArrayList streamedInput() {
278     return streamedInput;
279   }
280
281    /** Returns whether fieldName is a valid field name of this Entity.
282    * @param fieldName
283    * @return true in case fieldName is a field name, else false.
284    * @exception StorageObjectException
285    */
286   public boolean isField (String fieldName) throws StorageObjectFailure {
287     return  theStorageObject.getFields().contains(fieldName);
288   }
289
290
291
292   protected void throwStorageObjectFailure (Exception e, String wo) 
293         throws StorageObjectFailure {
294     theLog.printError( e.toString() + " Funktion: "+ wo);
295     e.printStackTrace(System.out);
296     throw  new StorageObjectFailure("Storage Object Exception in entity", e);
297   }
298
299   // Now implements freemarkers TemplateHashModel
300   // two methods have to be overridden:
301   // 1. public boolean isEmpty() throws TemplateModelException
302   // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException
303
304   public boolean isEmpty() throws TemplateModelException
305   {
306     return (theValuesHash==null || theValuesHash.isEmpty()) ? true : false;
307   }
308
309   public TemplateModel get(java.lang.String key) throws TemplateModelException
310   {
311                 return new SimpleScalar(getValue(key));
312   }
313
314         public void put(java.lang.String key, TemplateModel model)
315   {
316     // putting should only take place via setValue and is limited to the
317     // database fields associated with the entity. no additional freemarker
318     // stuff will be available via Entity.
319     theLog.printWarning("### put is called on entity! - the values will be lost!");
320   }
321
322   public void remove(java.lang.String key)
323   {
324     // do we need this?
325   }
326
327
328   //////////////////////////////////////////////////////////////////////////////////
329
330
331 }
332