KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > fields > JahiaFieldPropertiesDB


1 /*
2  * ____.
3  * __/\ ______| |__/\. _______
4  * __ .____| | \ | +----+ \
5  * _______| /--| | | - \ _ | : - \_________
6  * \\______: :---| : : | : | \________>
7  * |__\---\_____________:______: :____|____:_____\
8  * /_____|
9  *
10  * . . . i n j a h i a w e t r u s t . . .
11  *
12  *
13  *
14  * ----- BEGIN LICENSE BLOCK -----
15  * Version: JCSL 1.0
16  *
17  * The contents of this file are subject to the Jahia Community Source License
18  * 1.0 or later (the "License"); you may not use this file except in
19  * compliance with the License. You may obtain a copy of the License at
20  * http://www.jahia.org/license
21  *
22  * Software distributed under the License is distributed on an "AS IS" basis,
23  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
24  * for the rights, obligations and limitations governing use of the contents
25  * of the file. The Original and Upgraded Code is the Jahia CMS and Portal
26  * Server. The developer of the Original and Upgraded Code is JAHIA Ltd. JAHIA
27  * Ltd. owns the copyrights in the portions it created. All Rights Reserved.
28  *
29  * The Shared Modifications are Jahia View Helper.
30  *
31  * The Developer of the Shared Modifications is Jahia Solution S�rl.
32  * Portions created by the Initial Developer are Copyright (C) 2002 by the
33  * Initial Developer. All Rights Reserved.
34  *
35  * Contributor(s):
36  * 17-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
37  *
38  * ----- END LICENSE BLOCK -----
39  */

40
41 package org.jahia.services.fields;
42
43 import org.apache.log4j.Logger;
44 import org.jahia.data.fields.JahiaField;
45 import org.jahia.exceptions.JahiaException;
46 import org.jahia.exceptions.JahiaInitializationException;
47 import org.jahia.services.cache.Cache;
48 import org.jahia.services.cache.CacheFactory;
49 import org.jahia.services.cache.CacheListener;
50
51 import java.sql.Connection JavaDoc;
52 import java.sql.ResultSet JavaDoc;
53 import java.sql.SQLException JavaDoc;
54 import java.sql.Statement JavaDoc;
55 import java.util.Enumeration JavaDoc;
56 import java.util.Properties JavaDoc;
57 import java.util.Vector JavaDoc;
58
59 public class JahiaFieldPropertiesDB implements CacheListener {
60
61     /** logging */
62     private static Logger logger = Logger.getLogger (JahiaFieldBaseService.class);
63
64     // the Fields Properties cache name.
65
public static final String JavaDoc FIELD_PROPS_CACHE = "FieldPropsCache";
66     /** cache definition */
67     private Cache cacheFieldProps = null;
68     private boolean tableEmpty = false;
69
70
71     /**
72      * Default constructor, creates a new <code>JahiaFieldPropertiesDB</code> instance.
73      */

74     public JahiaFieldPropertiesDB () {
75         try {
76             cacheFieldProps = CacheFactory.createCache (FIELD_PROPS_CACHE);
77             cacheFieldProps.registerListener(this);
78
79         } catch (JahiaInitializationException e) {
80             logger.warn("Could not instanciate the Field Properties Cache ... bad sign!!", e);
81         }
82
83         // cache all the field's properties
84
cacheAllFieldProperties ();
85     }
86
87     /**
88      * Put put _ALL_ field properties in cache. For now we don't
89      * use much field properties so it's ok. But else it may take
90      * too much RAM so we'll have to think of a better way to cache it.
91      */

92     private static final int CHUNK_SIZE = 100;
93
94     protected void cacheAllFieldProperties () {
95         Connection JavaDoc dbConn = null;
96         Statement JavaDoc stmt = null;
97         ResultSet JavaDoc rs = null;
98         try {
99
100             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
101             stmt = dbConn.createStatement ();
102
103             String JavaDoc query = "SELECT fieldid_jahia_fields_prop FROM jahia_fields_prop ORDER BY fieldid_jahia_fields_prop ASC";
104             rs = stmt.executeQuery (query);
105             Vector JavaDoc entries = new Vector JavaDoc ();
106             tableEmpty = true;
107             if (rs != null) {
108                 while (rs.next ()) {
109                     tableEmpty = false;
110                     entries.add (new Integer JavaDoc (rs.getInt (
111                             "fieldid_jahia_fields_prop")));
112                 }
113             }
114
115             // cache them, approx. 100 by 100
116
int ptr = 0;
117             while (ptr < entries.size ()) {
118
119                 int max = (ptr + CHUNK_SIZE < entries.size () ?
120                         ptr + CHUNK_SIZE : entries.size () - 1);
121                 query =
122                         "SELECT * FROM jahia_fields_prop WHERE fieldid_jahia_fields_prop>=" +
123                         (entries.elementAt (ptr)) +
124                         " AND fieldid_jahia_fields_prop<=" +
125                         (entries.elementAt (max));
126
127                 String JavaDoc sqlQuery = "SELECT * FROM jahia_fields_prop";
128
129                 rs = stmt.executeQuery (sqlQuery);
130
131                 while (rs.next ()) {
132                     String JavaDoc propName = rs.getString ("propertyname_jahia_fields_prop");
133                     String JavaDoc propValue = rs.getString ("propvalue_jahia_fields_prop");
134                     String JavaDoc propFieldID = rs.getString ("fieldid_jahia_fields_prop");
135                     if ((propName != null) && (propValue != null)) {
136                         Properties JavaDoc cachedTable = (Properties JavaDoc) cacheFieldProps.get (
137                                 new Integer JavaDoc (propFieldID));
138                         // field not already cached, let's cache it
139
if (cachedTable == null) {
140                             cachedTable = new Properties JavaDoc ();
141                             cacheFieldProps.put (new Integer JavaDoc (propFieldID), cachedTable);
142                         }
143                         cachedTable.put (propName, propValue);
144                     }
145                 }
146                 ptr += CHUNK_SIZE;
147             }
148         } catch (SQLException JavaDoc se) {
149             String JavaDoc errorMsg = "Error in db_load_field_properties : " + se.getMessage () +
150                     "-> BAILING OUT";
151             logger.warn (errorMsg, se);
152
153         } finally {
154             closeStatement(stmt);
155         }
156     }
157
158     /**
159      * loads field properties for a field
160      *
161      * @param theField the field to load properties for
162      *
163      * @throws JahiaException if SQL error
164      */

165     public void db_load_field_properties (JahiaField theField)
166             throws JahiaException {
167         if ((cacheFieldProps.size () == 0) && (!tableEmpty)) {
168             cacheAllFieldProperties ();
169         }
170         Properties JavaDoc cachedTable = (Properties JavaDoc) cacheFieldProps.get (
171                 new Integer JavaDoc (theField.getID ()));
172         // properties not it cache ----> there is no property for this field!
173
if (cachedTable == null) {
174             theField.setProperties (new Properties JavaDoc ());
175         }
176         theField.setProperties (cachedTable);
177     }
178
179
180     /**
181      * saves field properties
182      *
183      * @param theField the field to save properties for
184      *
185      * @throws JahiaException if SQL error
186      */

187     public void db_save_field_properties (JahiaField theField)
188             throws JahiaException {
189         if (theField.getProperties () == null) {
190             // properties were never set, we don't need to save anything.
191
return;
192         }
193         cacheFieldProps.put (new Integer JavaDoc (theField.getID ()), theField.getProperties ());
194         Connection JavaDoc dbConn = null;
195         Statement JavaDoc stmt = null;
196
197         try {
198             // erases all existing properties
199
db_delete_field_properties (theField.getID ());
200
201             // gets connection
202
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
203             stmt = dbConn.createStatement ();
204             String JavaDoc sqlQuery = "";
205
206             // saves properties
207
Properties JavaDoc fProps = theField.getProperties ();
208             Enumeration JavaDoc keys = fProps.keys ();
209             while (keys.hasMoreElements ()) {
210                 String JavaDoc theKey = (String JavaDoc) keys.nextElement ();
211                 String JavaDoc theVal = (String JavaDoc) fProps.get (theKey);
212                 sqlQuery = "INSERT INTO jahia_fields_prop (fieldid_jahia_fields_prop,propertyname_jahia_fields_prop,propvalue_jahia_fields_prop) VALUES(";
213                 sqlQuery += theField.getID () + ",";
214                 sqlQuery += "'" + theKey + "',";
215                 sqlQuery += "'" + theVal + "')";
216                 stmt.execute (sqlQuery);
217             }
218         } catch (SQLException JavaDoc se) {
219             String JavaDoc errorMsg = "Error in db_save_field_properties : " + se.getMessage ();
220             logger.error (errorMsg + " -> BAILING OUT", se);
221             throw new JahiaException ("Cannot load fields from the database",
222                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.ERROR_SEVERITY);
223
224         } finally {
225             closeStatement(stmt);
226         }
227     }
228
229
230     /**
231      * deletes field properties
232      *
233      * @param fieldID the field id to delete properties for
234      *
235      * @throws JahiaException if SQL error
236      */

237     public void db_delete_field_properties (int fieldID)
238             throws JahiaException {
239         cacheFieldProps.remove (new Integer JavaDoc (fieldID));
240         Connection JavaDoc dbConn = null;
241         Statement JavaDoc stmt = null;
242         try {
243             // gets connection
244
dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
245             stmt = dbConn.createStatement ();
246             String JavaDoc sqlQuery = "";
247
248             // erases all existing properties
249
sqlQuery = "DELETE FROM jahia_fields_prop ";
250             sqlQuery += "WHERE (fieldid_jahia_fields_prop=" + fieldID + ")";
251             stmt.execute (sqlQuery);
252
253         } catch (SQLException JavaDoc se) {
254             String JavaDoc errorMsg = "Error in db_delete_field_properties : " + se.getMessage ();
255             logger.error (errorMsg + " -> BAILING OUT");
256             throw new JahiaException ("Cannot load fields from the database",
257                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.ERROR_SEVERITY);
258
259         } finally {
260             closeStatement (stmt);
261         }
262     }
263
264     private void closeStatement(Statement JavaDoc statement) {
265         // Close the opened statement
266
try {
267             if (statement != null) {
268                 statement.close();
269             }
270         } catch (SQLException JavaDoc sqlEx) {
271             logger.warn("Cannot close a statement", sqlEx);
272         }
273     }
274
275     /**
276      * This method is called each time the cache flushes its items.
277      *
278      * @param cacheName the name of the cache which flushed its items.
279      */

280     public void onCacheFlush(String JavaDoc cacheName) {
281
282         if (FIELD_PROPS_CACHE.equals(cacheName)) {
283             cacheFieldProps.flush(false);
284             cacheAllFieldProperties();
285         }
286     }
287
288     public void onCachePut(String JavaDoc cacheName, Object JavaDoc entryKey) {
289         // do nothing;
290
}
291
292 }
293
Popular Tags