KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > rift > coad > hibernate > util > HibernateUtil


1 /*
2  * CoadunationHibernate: The hibernate configuration.
3  * Copyright (C) 2006 Rift IT Contracting
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  *
19  * HibernateUtil.java
20  */

21
22 package com.rift.coad.hibernate.util;
23
24 // java imports
25
import java.util.StringTokenizer JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.concurrent.ConcurrentHashMap JavaDoc;
29 import javax.naming.Context JavaDoc;
30 import javax.naming.InitialContext JavaDoc;
31 import javax.transaction.Transaction JavaDoc;
32 import javax.transaction.TransactionManager JavaDoc;
33 import javax.transaction.xa.XAException JavaDoc;
34 import javax.transaction.xa.XAResource JavaDoc;
35 import javax.transaction.xa.Xid JavaDoc;
36
37
38 // logging import
39
import org.apache.log4j.Logger;
40
41 // hibernate imports
42
import org.hibernate.*;
43 import org.hibernate.cfg.*;
44
45 /**
46  * This class sets up a hibernate SessionFactory.
47  */

48 public class HibernateUtil implements XAResource JavaDoc {
49     
50     // class constants
51
public final static String JavaDoc RESOURCES_CONFIG = "hibernate_resource_config";
52     public final static String JavaDoc HIBERNATE_SQL = "hibernate_sql";
53     public final static String JavaDoc DB_SOURCE = "db_datasource";
54     public final static String JavaDoc HBM2DDL = "hibernate_hbm2ddl_auto";
55     public final static String JavaDoc TRANSACTION_TIMEOUT = "transaction_timeout";
56     public final static int DEFAULT_TRANSACTION_TIMEOUT = 180000;
57     
58     // class singleton
59
private static Map JavaDoc singletons = new HashMap JavaDoc();
60     
61     // the logger reference
62
protected static Logger log =
63             Logger.getLogger(HibernateUtil.class.getName());
64     
65     // class private member variables
66
private int timeout = 0;
67     private Context JavaDoc context = null;
68     private SessionFactory sessionFactory = null;
69     private Map JavaDoc sessions = new ConcurrentHashMap JavaDoc();
70     private ThreadLocal JavaDoc currentSession = new ThreadLocal JavaDoc();
71     
72     
73     /**
74      * The constructor of the hibernate util object.
75      *
76      * @param configId The identifier of the configuration.
77      * @exception MessageServiceException
78      */

79     private HibernateUtil(Class JavaDoc configId) throws HibernateUtilException {
80         try {
81             // retrieve the initial context
82
context = new InitialContext JavaDoc();
83             
84             // Retrieve the configuration for the message service implementation
85
com.rift.coad.lib.configuration.Configuration coadConfig =
86                     com.rift.coad.lib.configuration.ConfigurationFactory.
87                     getInstance()
88                     .getConfig(configId);
89             
90             // retrieve the default transaction timeout
91
timeout = (int)coadConfig.getLong(TRANSACTION_TIMEOUT,
92                     DEFAULT_TRANSACTION_TIMEOUT);
93             
94             // init the configuration for the hibernate object.
95
org.hibernate.cfg.Configuration config = new
96                     org.hibernate.cfg.Configuration()
97                     .configure(coadConfig.getString(RESOURCES_CONFIG))
98                     .setProperty("hibernate.dialect",
99                     coadConfig.getString("db_dialect"))
100                     .setProperty("hibernate.connection.datasource",
101                     coadConfig.getString(DB_SOURCE))
102                     .setProperty("hibernate.current_session_context_class","jta")
103                     .setProperty("hibernate.transaction.factory_class",
104                     "org.hibernate.transaction.JTATransactionFactory")
105                     .setProperty("hibernate.transaction.manager_lookup_class",
106                     "org.hibernate.transaction.JOTMTransactionManagerLookup")
107                     .setProperty("hibernate.connection.autocommit","false")
108                     .setProperty("hibernate.cache.provider_class",
109                     "org.hibernate.cache.NoCacheProvider")
110                     .setProperty("hibernate.show_sql",
111                     coadConfig.getString(HIBERNATE_SQL,"false"))
112                     .setProperty("hibernate.hbm2ddl.auto",
113                     coadConfig.getString(HBM2DDL,"update"));
114             
115             sessionFactory = config.buildSessionFactory();
116         } catch (Throwable JavaDoc ex) {
117             log.error("Initial SessionFactory " +
118                     "creation failed: " + ex.getMessage(),ex);
119             throw new HibernateUtilException("Initial SessionFactory " +
120                     "creation failed: " + ex.getMessage(),ex);
121         }
122     }
123     
124     
125     /**
126      * Configures up hibernate programmatically using Coadunations configuration
127      * file.
128      *
129      * @return The reference to the hibernate util singleton.
130      * @param configId The id of the configuration.
131      * @excepiton MessageServiceException
132      */

133     public synchronized static HibernateUtil getInstance(Class JavaDoc configId) throws
134             HibernateUtilException {
135         HibernateUtil singleton = null;
136         if (!singletons.containsKey(configId)) {
137             singleton = new HibernateUtil(configId);
138             singletons.put(configId,singleton);
139         } else {
140             singleton = (HibernateUtil)singletons.get(configId);
141         }
142         return singleton;
143     }
144     
145     
146     /**
147      * This method returns a reference to the session factory object.
148      *
149      * @return Returns the current session for this thread.
150      * @exception
151      */

152     public Session getSession() throws HibernateUtilException {
153         try {
154             Transaction JavaDoc transaction = getTransaction();
155             transaction.enlistResource(this);
156             return (Session)currentSession.get();
157         } catch (HibernateUtilException ex) {
158             throw ex;
159         } catch (Exception JavaDoc ex) {
160             log.error("Failed to retrieve the current session for this thread : "
161                     + ex.getMessage(),ex);
162             throw new HibernateUtilException(
163                     "Failed to retrieve the current session for this thread : "
164                     + ex.getMessage(),ex);
165         }
166     }
167     
168     
169     /**
170      * This method is responsible for handling the committing of a transaction
171      * identified by the xid.
172      *
173      * @param xid The id of the transaction to commit.
174      * @param onePhase If true a one phase commit should be used.
175      * @exception XAException
176      */

177     public void commit(Xid JavaDoc xid, boolean b) throws XAException JavaDoc {
178         if (this.sessions.containsKey(xid)) {
179             Session session = (Session)sessions.get(xid);
180             sessions.remove(xid);
181             try {
182                 session.connection().setAutoCommit(true);
183             } catch (Exception JavaDoc ex) {
184                 log.error("Failed to reset the auto commit flag on the " +
185                         "connection : " + ex.getMessage(),ex);
186             }
187         }
188     }
189     
190     
191     /**
192      * The resource manager has dissociated this object from the transaction.
193      *
194      * @param xid The id of the transaction that is getting ended.
195      * @param flags The flags associated with this operation.
196      * @exception XAException
197      */

198     public void end(Xid JavaDoc xid, int flags) throws XAException JavaDoc {
199     }
200     
201     
202     /**
203      * The transaction has been completed and must be forgotten.
204      *
205      * @param xid The id of the transaction to forget.
206      * @exception XAException
207      */

208     public void forget(Xid JavaDoc xid) throws XAException JavaDoc {
209         if (this.sessions.containsKey(xid)) {
210             Session session = (Session)sessions.get(xid);
211             sessions.remove(xid);
212             try {
213                 session.connection().setAutoCommit(true);
214             } catch (Exception JavaDoc ex) {
215                 log.error("Failed to reset the auto commit flag on the " +
216                         "connection : " + ex.getMessage(),ex);
217             }
218         }
219     }
220     
221     
222     /**
223      * This method returns the transaction timeout for this object.
224      *
225      * @return The int containing the transaction timeout.
226      * @exception XAException
227      */

228     public int getTransactionTimeout() throws XAException JavaDoc {
229         return timeout;
230     }
231     
232     
233     /**
234      * This method returns true if this object is the resource manager getting
235      * queried.
236      *
237      * @return TRUE if this is the resource manager, FALSE if not.
238      * @param xaResource The resource to perform the check against.
239      * @exception XAException
240      */

241     public boolean isSameRM(XAResource JavaDoc xAResource) throws XAException JavaDoc {
242         return this == xAResource;
243     }
244     
245     
246     /**
247      * This is called before a transaction is committed.
248      *
249      * @return The results of the transaction.
250      * @param xid The id of the transaction to check against.
251      * @exception XAException
252      */

253     public int prepare(Xid JavaDoc xid) throws XAException JavaDoc {
254         return XAResource.XA_OK;
255     }
256     
257     
258     /**
259      * This method returns the list of transaction branches for this resource
260      * manager.
261      *
262      * @return The list of resource branches.
263      * @param flags The flags
264      * @exception XAException
265      */

266     public Xid JavaDoc[] recover(int flags) throws XAException JavaDoc {
267         return null;
268     }
269     
270     
271     /**
272      * This method is called to roll back the specified transaction.
273      *
274      * @param xid The id of the transaction to roll back.
275      * @exception XAException
276      */

277     public void rollback(Xid JavaDoc xid) throws XAException JavaDoc {
278         if (this.sessions.containsKey(xid)) {
279             Session session = (Session)sessions.get(xid);
280             sessions.remove(xid);
281             try {
282                 session.connection().setAutoCommit(true);
283             } catch (Exception JavaDoc ex) {
284                 log.error("Failed to reset the auto commit flag on the " +
285                         "connection : " + ex.getMessage(),ex);
286             }
287             
288         }
289     }
290     
291     
292     /**
293      * This method sets the transaction timeout for this resource manager.
294      *
295      * @return TRUE if the transaction timeout can be set successfully.
296      * @param transactionTimeout The new transaction timeout value.
297      * @exception XAException
298      */

299     public boolean setTransactionTimeout(int transactionTimeout) throws
300             XAException JavaDoc {
301         timeout = transactionTimeout;
302         return true;
303     }
304     
305     
306     /**
307      * This method is called to start a transaction on a resource manager.
308      *
309      * @param xid The id of the new transaction.
310      * @param flags The flags associated with the transaction.
311      * @exception XAException
312      */

313     public void start(Xid JavaDoc xid, int i) throws XAException JavaDoc {
314         Session session = null;
315         if (this.sessions.containsKey(xid)) {
316             session = (Session)sessions.get(xid);
317         } else {
318             try {
319                 session = sessionFactory.getCurrentSession();
320                 session.connection().setAutoCommit(false);
321                 sessions.put(xid,session);
322             } catch (Exception JavaDoc ex) {
323                 log.error("Failed to start the transaction : "
324                         + ex.getMessage(),ex);
325                 throw new XAException JavaDoc(
326                         "Failed to start the transaction : " + ex.getMessage());
327             }
328         }
329         this.currentSession.set(session);
330     }
331     
332     
333     /**
334      * This method returns the transaction for this thread.
335      *
336      * @return The transaction for this thread.
337      * @exception HibernateUtilException
338      */

339     private Transaction JavaDoc getTransaction() throws HibernateUtilException {
340         try {
341             TransactionManager JavaDoc transactionManager = (TransactionManager JavaDoc)
342                     context.lookup("java:comp/TransactionManager");
343             return transactionManager.getTransaction();
344         } catch (Exception JavaDoc ex) {
345             log.error("Failed to retrieve the current transaction because : "
346                     + ex.getMessage(),ex);
347             // Make sure you log the exception, as it might be swallowed
348
throw new HibernateUtilException(
349                     "Failed to retrieve the current transaction because : "
350                     + ex.getMessage(),ex);
351         }
352     }
353 }
Popular Tags