KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > sites > SiteLanguagesPersistance


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
42 package org.jahia.services.sites;
43
44 import org.jahia.data.JahiaDBDOMObject;
45 import org.jahia.data.JahiaDOMObject;
46 import org.jahia.exceptions.JahiaException;
47 import org.jahia.exceptions.JahiaInitializationException;
48 import org.jahia.registries.ServicesRegistry;
49 import org.jahia.services.cache.Cache;
50 import org.jahia.services.cache.CacheFactory;
51 import org.jahia.utils.JahiaTools;
52
53 import java.sql.*;
54 import java.util.Set JavaDoc;
55 import java.util.TreeSet JavaDoc;
56 import java.util.Vector JavaDoc;
57
58 /**
59  * <p>Title: Site language settings persistance manager </p>
60  * <p>Description: This class manages the storage and retrieval in the
61  * database of the site's language settings. </p>
62  * <p>Copyright: Copyright (c) 2002</p>
63  * <p>Company: </p>
64  *
65  * @author Serge Huber.
66  * @version 1.0
67  */

68
69 public class SiteLanguagesPersistance {
70
71     /** logging */
72     private static org.apache.log4j.Logger logger =
73             org.apache.log4j.Logger.getLogger (SiteLanguagesPersistance.class);
74
75     /** unique instance */
76     private static SiteLanguagesPersistance instance;
77
78     // the Site Languages cache name.
79
public static final String JavaDoc SITE_LANGUAGES_CACHE = "siteLanguagesCache";
80     private Cache siteLanguagesCache;
81
82     private static final String JavaDoc GET_ALLSITELANGUAGES_QUERY =
83             "SELECT DISTINCT code FROM jahia_site_lang_list";
84
85     /**
86      * Private constructor since we are using a singleton pattern.
87      */

88     private SiteLanguagesPersistance () {
89
90         try {
91             siteLanguagesCache = CacheFactory.createCache (SITE_LANGUAGES_CACHE);
92
93         } catch (JahiaInitializationException e) {
94             logger.warn ("Could not instanciate the [" + SITE_LANGUAGES_CACHE +
95                     "] cache. Jahia might become unstable!", e);
96         }
97     }
98
99     /**
100      * Retrieve the unique instance of this persistance manager
101      *
102      * @return the unique instance of this persistance manager
103      */

104     public static synchronized SiteLanguagesPersistance getInstance () {
105
106         if (instance == null) {
107             instance = new SiteLanguagesPersistance ();
108         }
109         return instance;
110     }
111
112     /**
113      * Retrieve from the database a list of language settings for a given
114      * site.
115      *
116      * @param siteID the identifier of the site for which to retrieve the
117      * language settings
118      *
119      * @return a Vector containing SiteLanguageSettings objects that are the
120      * list of language settings for the specified site. The Vector might be
121      * empty if there are no settings for a site but it should never be null.
122      * The list is ordered according to the rank of the languages (lower rank
123      * value first)
124      *
125      * @throws JahiaException if an error occured while retrieving the language
126      * settings for the site.
127      */

128     public Vector JavaDoc getSiteLanguages (int siteID) throws JahiaException {
129
130         Connection dbConn = null;
131         Statement statement = null;
132
133         // first let's check the cache
134

135         Vector JavaDoc siteLanguages = (Vector JavaDoc) siteLanguagesCache.get (new Integer JavaDoc (siteID));
136
137         if (siteLanguages != null) {
138             return siteLanguages;
139         }
140
141         siteLanguages = new Vector JavaDoc ();
142         SiteLanguageSettings siteLanguageSettings = null;
143
144         try {
145             String JavaDoc sqlQuery = "SELECT * FROM jahia_site_lang_list WHERE site_id=" +
146                     siteID + " ORDER BY rank";
147
148             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
149             statement = dbConn.createStatement ();
150             if (statement != null) {
151                 ResultSet rs = statement.executeQuery (sqlQuery);
152                 if (rs != null) {
153                     while (rs.next ()) {
154                         siteLanguageSettings = getSiteLanguageFromResultSet (rs);
155                         siteLanguages.add (siteLanguageSettings);
156                     }
157                 }
158             }
159
160         } catch (SQLException se) {
161             String JavaDoc errorMsg = "Error in SiteLanguagePersistance.getSiteLanguages : " +
162                     se.getMessage ();
163             logger.debug (errorMsg, se);
164             throw new JahiaException ("Cannot load site language settings from the database",
165                     errorMsg,
166                     JahiaException.DATABASE_ERROR,
167                     JahiaException.CRITICAL_SEVERITY,
168                     se);
169         } finally {
170
171             closeStatement (statement);
172         }
173
174         // add / update the cache
175
siteLanguagesCache.put (new Integer JavaDoc (siteID), siteLanguages);
176
177         return siteLanguages;
178     }
179
180
181     /**
182      * Retrieve a language settings entry specified by it's identifier
183      *
184      * @param id identifier of the site language setttings entry in the database
185      *
186      * @return a SiteLanguageSettings object corresponding to the identifier
187      * specified or null if not found
188      *
189      * @throws JahiaException thrown if a database error occured while retrieving
190      * the language settings entry
191      */

192     public SiteLanguageSettings getSiteLanguageSettings (int id) throws JahiaException {
193
194         Connection dbConn = null;
195         Statement statement = null;
196
197         SiteLanguageSettings siteLangSettings = null;
198
199         try {
200             String JavaDoc sqlQuery = "SELECT * FROM jahia_site_lang_list where id=" + id;
201
202             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
203             statement = dbConn.createStatement ();
204             if (statement != null) {
205                 ResultSet rs = statement.executeQuery (sqlQuery);
206                 if (rs != null) {
207                     if (rs.next ()) {
208                         siteLangSettings = getSiteLanguageFromResultSet (rs);
209                     }
210                 }
211             }
212         } catch (SQLException se) {
213             String JavaDoc errorMsg = "Error in SiteLanguagesPersistance.getSiteLanguageSettings(int id) : " + se.getMessage ();
214             logger.debug (errorMsg, se);
215             throw new JahiaException ("Cannot load site language settings from the database",
216                     errorMsg, JahiaException.DATABASE_ERROR,
217                     JahiaException.CRITICAL_SEVERITY,
218                     se);
219         } finally {
220
221             closeStatement (statement);
222         }
223
224         // as we have loaded a value from the database, let's make sure we
225
// maintain cache consistency.
226
siteLanguagesCache.remove (new Integer JavaDoc (siteLangSettings.getSiteID ()));
227
228         return siteLangSettings;
229     }
230
231
232     /**
233      * Insert a new language setting entry in the database. This new entry has
234      * all it's values already defined except it's identifier, which is
235      * determined in this call. The passed object is modified (!) by this method
236      * to include the new ID.
237      *
238      * @param siteLangSettings the object to insert into the database, and
239      * whose ID to set.
240      *
241      * @throws JahiaException is thrown if an error occured while communicating
242      * with the database.
243      */

244     public void addSiteLanguageSettings (SiteLanguageSettings siteLangSettings)
245             throws JahiaException {
246
247         // first let's flush the site ID's cache
248
siteLanguagesCache.remove (new Integer JavaDoc (siteLangSettings.getSiteID ()));
249
250         try {
251
252             int id = ServicesRegistry.getInstance ().getJahiaIncrementorsDBService ()
253                     .autoIncrement ("jahia_site_lang_list");
254
255             StringBuffer JavaDoc sqlQuery = new StringBuffer JavaDoc (
256                     "INSERT INTO jahia_site_lang_list VALUES(");
257             sqlQuery.append (id);
258             sqlQuery.append (", ");
259             sqlQuery.append (siteLangSettings.getSiteID ());
260             sqlQuery.append (", '");
261             sqlQuery.append (JahiaTools.quote (siteLangSettings.getCode ()));
262             sqlQuery.append ("', ");
263             sqlQuery.append (siteLangSettings.getRank ());
264
265             sqlQuery.append (", ");
266
267             if (siteLangSettings.isActivated ()) {
268                 sqlQuery.append (1);
269             } else {
270                 sqlQuery.append (0);
271             }
272
273             sqlQuery.append (", ");
274
275             if (siteLangSettings.isMandatory ()) {
276                 sqlQuery.append (1);
277             } else {
278                 sqlQuery.append (0);
279             }
280             sqlQuery.append (")");
281
282             executeQueryNoResultSet (sqlQuery.toString ());
283
284             logger.debug (sqlQuery.toString ());
285
286             siteLangSettings.setID (id);
287
288         } catch (JahiaException je) {
289             String JavaDoc errorMsg = "Error in SiteLanguagesPersistance.addSiteLanguageSettings : " + je.getMessage ();
290             logger.debug (errorMsg, je);
291             throw new JahiaException ("Cannot add site in the database",
292                     errorMsg,
293                     JahiaException.DATABASE_ERROR,
294                     JahiaException.CRITICAL_SEVERITY,
295                     je);
296         }
297     }
298
299     /**
300      * Removes a site language setting entry from the database
301      *
302      * @param id the identifier of the entry to remove from the database
303      *
304      * @throws JahiaException is thrown if an error occured while executing
305      * the database request.
306      */

307     public void removeSiteLanguageSettings (int id) throws JahiaException {
308
309         // first let's remove the site ID's cache...
310
SiteLanguageSettings foundSettings = getSiteLanguageSettings (id);
311         siteLanguagesCache.remove (new Integer JavaDoc (foundSettings.getSiteID ()));
312
313         try {
314             String JavaDoc sqlQuery = "DELETE FROM jahia_site_lang_list WHERE id=" + id;
315             executeQueryNoResultSet (sqlQuery);
316         } catch (JahiaException je) {
317             String JavaDoc errorMsg = "SiteLanguagesPersistance.removeSiteLanguageSettings : " + je.getMessage ();
318             logger.debug (errorMsg, je);
319             throw new JahiaException ("Cannot remove site language settings in the database",
320                     errorMsg, JahiaException.DATABASE_ERROR,
321                     JahiaException.CRITICAL_SEVERITY, je);
322         }
323     }
324
325
326     /**
327      * Updates the settings for a site language
328      *
329      * @param siteLangSettings the object containing the updated values to
330      * store in the database
331      *
332      * @throws JahiaException is thrown if an error occured while executing
333      * the database request.
334      */

335     public void updateSiteLanguageSettings (SiteLanguageSettings siteLangSettings)
336             throws JahiaException {
337
338         // as we are updating, let's remove the site's cache
339
siteLanguagesCache.remove (new Integer JavaDoc (siteLangSettings.getSiteID ()));
340
341         try {
342             StringBuffer JavaDoc sqlQuery = new StringBuffer JavaDoc ("UPDATE jahia_site_lang_list SET ");
343             sqlQuery.append ("site_id=");
344             sqlQuery.append (siteLangSettings.getSiteID ());
345             sqlQuery.append (", code='");
346             sqlQuery.append (JahiaTools.quote (siteLangSettings.getCode ()));
347             sqlQuery.append ("', rank=");
348             sqlQuery.append (siteLangSettings.getRank ());
349
350             sqlQuery.append (", activated=");
351
352             if (siteLangSettings.isActivated ()) {
353                 sqlQuery.append (1);
354             } else {
355                 sqlQuery.append (0);
356             }
357
358             sqlQuery.append (", mandatory=");
359
360             if (siteLangSettings.isMandatory ()) {
361                 sqlQuery.append (1);
362             } else {
363                 sqlQuery.append (0);
364             }
365             sqlQuery.append (" WHERE id=");
366             sqlQuery.append (siteLangSettings.getID ());
367
368             logger.debug (sqlQuery.toString ());
369             executeQueryNoResultSet (sqlQuery.toString ());
370
371         } catch (JahiaException je) {
372             String JavaDoc errorMsg = "Error in SiteLanguagesPersistance.updateSiteLanguageSettings : " + je.getMessage ();
373             logger.debug (errorMsg, je);
374             throw new JahiaException ("Cannot update site in the database",
375                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY,
376                     je);
377         }
378     }
379
380
381     /**
382      * Build a SiteLanguageSettings object from a database result set
383      *
384      * @param rs the result set from which to retrieve one line of data
385      *
386      * @return a SiteLanguageSettings object containing the data from the
387      * result set, or null if an error occured
388      *
389      * @throws JahiaException is thrown if an error occured while retrieving
390      * the object data from the result set.
391      */

392     protected SiteLanguageSettings getSiteLanguageFromResultSet (ResultSet rs)
393             throws JahiaException {
394
395         SiteLanguageSettings siteLangSettings = null;
396
397         if (rs != null) {
398
399             int id = 0;
400             int site_id = 0;
401             String JavaDoc code = "";
402             int rank = 0;
403             boolean activated = false;
404             boolean mandatory = false;
405
406             try {
407
408                 id = rs.getInt ("id");
409                 site_id = rs.getInt ("site_id");
410                 code = rs.getString ("code");
411                 rank = rs.getInt ("rank");
412                 activated = (rs.getInt ("activated") == 1);
413                 mandatory = (rs.getInt ("mandatory") == 1);
414
415                 siteLangSettings = new SiteLanguageSettings (id, site_id, code,
416                         activated, rank,
417                         mandatory, true);
418
419             } catch (SQLException se) {
420                 String JavaDoc errorMsg = "Error in SiteLanguagesPersistance.getSiteLanguageFromResultSet : " + se.getMessage ();
421                 logger.debug (errorMsg, se);
422                 throw new JahiaException ("Cannot read data from resultset",
423                         errorMsg, JahiaException.DATABASE_ERROR,
424                         JahiaException.CRITICAL_SEVERITY,
425                         se);
426             }
427
428         }
429
430         return siteLangSettings;
431     }
432
433
434     private void executeQueryNoResultSet (String JavaDoc queryStr) throws JahiaException {
435
436         Connection dbConn = null;
437         Statement statement = null;
438
439         try {
440             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
441             statement = dbConn.createStatement ();
442             if (statement != null) {
443                 statement.executeUpdate (queryStr);
444             }
445         } catch (SQLException se) {
446             String JavaDoc errorMsg = "Error in SiteLanguagesPersistance.executeQueryNoResultSet(" + queryStr + ") : " + se.getMessage ();
447             logger.debug (errorMsg, se);
448             throw new JahiaException ("Cannot execute query" + queryStr,
449                     errorMsg, JahiaException.DATABASE_ERROR,
450                     JahiaException.CRITICAL_SEVERITY, se);
451         } finally {
452             closeStatement (statement);
453         }
454
455     }
456
457
458     private void closeStatement (Statement statement) {
459         // Close the opened statement
460
try {
461             if (statement != null) {
462                 statement.close ();
463                 statement = null;
464             }
465         } catch (SQLException sqlEx) {
466             logger.warn ("Cannot close a statement", sqlEx);
467         }
468     }
469
470     /**
471      * Retrieve a DOM representing of the site language settings table for a
472      * given site
473      *
474      * @param siteID the identifier of the site for which to retrieve the
475      * DOM tree
476      *
477      * @return a DOM object that contains the database table entries for the
478      * given site
479      *
480      * @throws JahiaException is thrown if an occured if while communicating
481      * with the database.
482      */

483     public JahiaDOMObject getSiteLanguagesAsDOM (int siteID) throws JahiaException {
484
485         Connection dbConn = null;
486         Statement statement = null;
487
488         JahiaDBDOMObject dom = null;
489
490         // first let's flush the cache
491
siteLanguagesCache.flush ();
492
493         try {
494             String JavaDoc sqlQuery = "SELECT * FROM jahia_site_lang_list where site_id=" + siteID;
495
496             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
497             statement = dbConn.createStatement ();
498             if (statement != null) {
499                 ResultSet rs = statement.executeQuery (sqlQuery);
500                 if (rs != null) {
501                     dom = new JahiaDBDOMObject ();
502                     dom.addTable ("jahia_site_lang_list", rs);
503                     return dom;
504                 }
505             }
506         } catch (SQLException se) {
507             String JavaDoc errorMsg = "Error in SiteLanguagesPersistance.getSiteLanguageAsDOM : " + se.getMessage ();
508             logger.debug (errorMsg, se);
509             throw new JahiaException ("Cannot load site from the database",
510                     errorMsg, JahiaException.DATABASE_ERROR,
511                     JahiaException.CRITICAL_SEVERITY, se);
512         } finally {
513
514             closeStatement (statement);
515         }
516
517         return dom;
518     }
519
520     /**
521      * Returns all the language codes used in *all* the site in the Jahia
522      * database. This request will return both active and inactive languages
523      *
524      * @return a Set of String objects containing language codes in the format
525      * similar to the output of a Locale.toString() method call.
526      *
527      * @throws JahiaException is thrown if an occured if while communicating
528      * with the database.
529      */

530     public Set JavaDoc getAllSitesLanguages () throws JahiaException {
531
532         Connection dbConn = null;
533         PreparedStatement statement = null;
534         Set JavaDoc languageCodeSet = new TreeSet JavaDoc ();
535
536         try {
537             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
538             statement = dbConn.prepareStatement (GET_ALLSITELANGUAGES_QUERY);
539             ResultSet rs = statement.executeQuery ();
540             while (rs.next ()) {
541                 String JavaDoc curLanguageCode = rs.getString ("code");
542                 languageCodeSet.add (curLanguageCode);
543             }
544         } catch (SQLException se) {
545             String JavaDoc errorMsg = "Error : " +
546                     se.getMessage ();
547             logger.debug (errorMsg, se);
548             throw new JahiaException ("Cannot load all sites langauges",
549                     errorMsg,
550                     JahiaException.DATABASE_ERROR,
551                     JahiaException.CRITICAL_SEVERITY,
552                     se);
553         } finally {
554             closeStatement (statement);
555         }
556
557         return languageCodeSet;
558     }
559
560
561 }
562
Popular Tags