KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > database > JahiaIncrementorsDBBaseService


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  * 02-NOV-2000, Xo3 SA, Eric Vassalli: Initial version
37  * 06-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
38  *
39  * ----- END LICENSE BLOCK -----
40  */

41
42
43 package org.jahia.services.database;
44
45 import org.jahia.data.JahiaDBDOMObject;
46 import org.jahia.data.JahiaDOMObject;
47 import org.jahia.exceptions.JahiaException;
48
49 import java.sql.Connection JavaDoc;
50 import java.sql.ResultSet JavaDoc;
51 import java.sql.SQLException JavaDoc;
52 import java.sql.Statement JavaDoc;
53 import java.util.HashMap JavaDoc;
54 import java.util.Map JavaDoc;
55
56
57 public class JahiaIncrementorsDBBaseService extends JahiaIncrementorsDBService {
58
59     private static org.apache.log4j.Logger logger =
60             org.apache.log4j.Logger.getLogger (JahiaIncrementorsDBBaseService.class);
61
62     /** the unique instance of this class */
63     private static JahiaIncrementorsDBBaseService instance = null;
64
65     private static Map JavaDoc tableNames = new HashMap JavaDoc();
66
67     /**
68      * constructor
69      * EV 31.10.2000
70      * NK 24.12.2000 Client should always call getInstance() method instead
71      */

72     protected JahiaIncrementorsDBBaseService () {
73         logger.debug ("***** Starting the Jahia Incrementors DB Base Service *****");
74     }
75
76
77     /**
78      * Retrieve the unique instance of this class.
79      * @return the unique class instance
80      *
81      */

82     public static synchronized JahiaIncrementorsDBBaseService getInstance () {
83         if (instance == null) {
84             instance = new JahiaIncrementorsDBBaseService ();
85         }
86         return instance;
87     }
88
89
90     /**
91      * autoIncrement
92      * EV 02.11.2000
93      *
94      */

95     public int autoIncrement (String JavaDoc tableName)
96             throws JahiaException {
97
98         synchronized(tableNames) {
99             // get unique string instance - cause methods is not always called with the same constant
100
if (tableNames.containsKey(tableName)) {
101                 tableName = (String JavaDoc) tableNames.get(tableName);
102             } else {
103                 tableNames.put(tableName, tableName);
104             }
105         }
106
107         try {
108             synchronized(tableName) {
109                 // gets the last id in the incrementors table
110
int lastID = getLastID (tableName);
111
112                 // adds the new id
113
lastID++;
114                 updateLastID (tableName, lastID);
115                 return lastID;
116             }
117         }
118                 // catches sql error
119
catch (JahiaException je) {
120             logger.debug ("error in autoIncrement -> BAILING OUT", je);
121             throw je;
122         }
123     }
124
125
126     /**
127      * getLastID
128      * EV 02.11.2000
129      *
130      */

131     private int getLastID (String JavaDoc tableName)
132             throws JahiaException {
133         Connection JavaDoc dbConn = null;
134         Statement JavaDoc stmt = null;
135         ResultSet JavaDoc rs = null;
136         int lastID = 0;
137         int thereCanBeOnlyOne = 0;
138         boolean success = false;
139
140         try {
141             int current = 0;
142             // composes the query
143
String JavaDoc sqlQuery = "";
144             sqlQuery += "SELECT jahia_autoids_currentindex FROM jahia_autoids ";
145             sqlQuery += "WHERE jahia_autoids_tablename='" + tableName + "'";
146
147             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
148
149             // executes the query
150
stmt = dbConn.createStatement ();
151             rs = stmt.executeQuery (sqlQuery);
152
153             // parses the results
154
while (rs.next ()) {
155                 current = rs.getInt ("jahia_autoids_currentindex");
156                 if (current > thereCanBeOnlyOne) {
157                     thereCanBeOnlyOne = current;
158                 }
159             }
160
161             success = true;
162
163         } catch (SQLException JavaDoc se) {
164             String JavaDoc errorMsg = "Error in finding last ID : " + se.getMessage ();
165             logger.debug (errorMsg, se);
166             throw new JahiaException ("Cannot access database incrementors",
167                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY, se);
168         } finally {
169             try {
170
171                 if (stmt != null) stmt.close ();
172                 //if ( rs != null ) rs.close();
173
} catch (SQLException JavaDoc ex) {
174                 logger.debug ("Error while freeing connection or statement", ex);
175                 throw new JahiaException ("Cannot free resources",
176                         "getLastID : cannot free resources",
177                         JahiaException.DATABASE_ERROR, JahiaException.WARNING_SEVERITY, ex);
178             }
179         }
180         if (success) {
181             // if no index was found, create a new one
182
if (thereCanBeOnlyOne == 0) {
183                 createNewID (tableName);
184             }
185
186             lastID = thereCanBeOnlyOne;
187         }
188         return lastID;
189     }
190
191
192     /**
193      * createNewID
194      * EV 02.11.2000
195      * EV 04.11.2000 method is now synchrionized
196      *
197      */

198     private synchronized void createNewID (String JavaDoc tableName)
199             throws JahiaException {
200         Connection JavaDoc dbConn = null;
201         Statement JavaDoc stmt = null;
202         try {
203             // composes the query
204
String JavaDoc sqlQuery = "";
205             sqlQuery += "INSERT INTO jahia_autoids (jahia_autoids_tablename, jahia_autoids_currentindex) ";
206             sqlQuery += "VALUES('" + tableName + "',1)";
207
208             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
209
210             // executes the query
211
stmt = dbConn.createStatement ();
212             stmt.executeUpdate (sqlQuery);
213
214             logger.debug ("Creating new ID for " + tableName);
215
216         } catch (SQLException JavaDoc se) {
217             String JavaDoc errorMsg = "Error in createNewID : " + se.getMessage ();
218             logger.debug (errorMsg, se);
219             throw new JahiaException ("Cannot create new identifiers in the database",
220                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY, se);
221         } finally {
222             try {
223
224                 if (stmt != null) stmt.close ();
225             } catch (SQLException JavaDoc ex) {
226                 logger.debug ("Error while freeing connection or statement", ex);
227                 throw new JahiaException ("Cannot free resources",
228                         "createNewID : cannot free resources",
229                         JahiaException.DATABASE_ERROR, JahiaException.WARNING_SEVERITY, ex);
230             }
231         }
232     }
233
234
235     /**
236      * updateLastID
237      * EV 02.11.2000
238      * EV 04.11.2000 method is now synchrionized
239      *
240      */

241     private synchronized void updateLastID (String JavaDoc tableName, int lastID)
242             throws JahiaException {
243         Statement JavaDoc stmt = null;
244         Connection JavaDoc dbConn = null;
245
246         try {
247             // composes the query
248
StringBuffer JavaDoc sqlQuery = new StringBuffer JavaDoc ("UPDATE jahia_autoids SET ");
249             sqlQuery.append ("jahia_autoids_currentindex=");
250             sqlQuery.append (lastID);
251             sqlQuery.append (" WHERE jahia_autoids_tablename='" + tableName + "'");
252
253             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
254
255             // executes the query
256
stmt = dbConn.createStatement ();
257             stmt.executeUpdate (sqlQuery.toString ());
258
259         } catch (SQLException JavaDoc se) {
260             String JavaDoc errorMsg = "Error in updateLastID : " + se.getMessage ();
261             logger.debug ("Cannot update auto-ids for table " + tableName + " : " + errorMsg, se);
262             throw new JahiaException ("Cannot update identifiers in the database",
263                     errorMsg, JahiaException.DATABASE_ERROR, JahiaException.CRITICAL_SEVERITY, se);
264         } finally {
265             try {
266
267                 if (stmt != null) stmt.close ();
268             } catch (SQLException JavaDoc ex) {
269                 logger.debug ("Error while freeing connection or statement", ex);
270                 throw new JahiaException ("Cannot free resources",
271                         "updateLastID : cannot free resources",
272                         JahiaException.DATABASE_ERROR, JahiaException.WARNING_SEVERITY, ex);
273             }
274         }
275     }
276
277
278     /**
279      * returns a DOM representation of the auto ids table
280      * NK 13.08.2001
281      *
282      */

283     public JahiaDOMObject getAutoIdsAsDOM ()
284             throws JahiaException {
285
286         Connection JavaDoc dbConn = null;
287         Statement JavaDoc statement = null;
288         ResultSet JavaDoc rs = null;
289
290         JahiaDBDOMObject dom = null;
291
292         try {
293             String JavaDoc sqlQuery = "SELECT * FROM jahia_autoids";
294
295             dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
296             statement = dbConn.createStatement ();
297             if (statement != null) {
298                 rs = statement.executeQuery (sqlQuery);
299                 if (rs != null) {
300                     dom = new JahiaDBDOMObject ();
301                     dom.addTable ("jahia_autoids", rs);
302                     return dom;
303                 }
304             }
305         } catch (SQLException JavaDoc se) {
306             String JavaDoc errorMsg = "Error in getAutoIdsAsDOM() : " + se.getMessage ();
307             logger.debug ("Error while exporting auto-ids as DOM ", se);
308             throw new JahiaException ("Cannot load data from the database",
309                     errorMsg, JahiaException.DATABASE_ERROR,
310                     JahiaException.CRITICAL_SEVERITY, se);
311         } finally {
312             try {
313                 rs.close ();
314                 rs = null;
315             } catch (Throwable JavaDoc t) {
316                 logger.debug ("Error while trying to free ResultSet object", t);
317             }
318             closeStatement (statement);
319         }
320
321         return dom;
322     }
323
324
325
326     private void closeStatement (Statement JavaDoc statement) {
327         // Close the opened statement
328
try {
329             if (statement != null) {
330                 statement.close ();
331             }
332         } catch (SQLException JavaDoc sqlEx) {
333             // just create an exception without raising it, just to notify it
334
// in the logs.
335
logger.debug ("Error while closing statement", sqlEx);
336         }
337     }
338
339 }
340
Popular Tags