View Javadoc

1   package net.sf.jguard.ext.authentication.manager;
2   
3   import java.util.logging.Level;
4   import javax.naming.InitialContext;
5   import javax.naming.NamingException;
6   
7   import org.hibernate.SessionFactory;
8   import org.hibernate.cfg.Configuration;
9   import org.hibernate.cfg.Environment;
10  import org.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  
14  
15  /**
16   * <b>this class comes from the <i>caveEmptor</i> Hibernate example application</b>.
17   * 
18   * Basic Hibernate helper class for Hibernate configuration and startup.
19   * <p>
20   * Uses a static initializer to read startup options and initialize
21   * <tt>Configuration</tt> and <tt>SessionFactory</tt>.
22   * <p>
23   * This class also tries to figure out if JNDI binding of the <tt>SessionFactory</tt>
24   * is used, otherwise it falls back to a global static variable (Singleton). If
25   * you use this helper class to obtain a <tt>SessionFactory</tt> in your code,
26   * you are shielded from these deployment differences.
27   * <p>
28   * Another advantage of this class is access to the <tt>Configuration</tt> object
29   * that was used to build the current <tt>SessionFactory</tt>. You can access
30   * mapping metadata programmatically with this API, and even change it and rebuild
31   * the <tt>SessionFactory</tt>.
32   * <p>
33   * Note: This class supports annotations if you replace the line that creates
34   * a Configuration object.
35   * <p>
36   * Note: This class supports only one data store. Support for several
37   * <tt>SessionFactory</tt> instances can be easily added (through a static <tt>Map</tt>,
38   * for example). You could then lookup a <tt>SessionFactory</tt> by its name.
39   *
40   * @author Christian Bauer
41   */
42  public class HibernateUtil {
43  
44      private static Logger logger = LoggerFactory.getLogger(HibernateUtil.class.getName());
45  
46      private static Configuration configuration;
47      private static SessionFactory sessionFactory;
48  
49      public static void init(){
50          // Create the initial SessionFactory from the default configuration files
51          try {
52              logger.debug("Initializing Hibernate");
53  
54              // Read hibernate.properties, if present
55              configuration = new Configuration();
56              // Use annotations: configuration = new AnnotationConfiguration();
57  
58              // Read hibernate.cfg.xml (has to be present)
59              configuration.configure();
60  
61              // Build and store (either in JNDI or static variable)
62              rebuildSessionFactory(configuration);
63  
64              logger.debug("Hibernate initialized, call HibernateUtil.getSessionFactory()");
65          } catch (Throwable ex) {
66              // We have to catch Throwable, otherwise we will miss
67              // NoClassDefFoundError and other subclasses of Error
68              logger.error("Building SessionFactory failed.", ex);
69              throw new ExceptionInInitializerError(ex);
70          }
71      }
72  
73      /**
74       * Returns the Hibernate configuration that was used to build the SessionFactory.
75       *
76       * @return Configuration
77       */
78      public static Configuration getConfiguration() {
79          return configuration;
80      }
81  
82      /**
83       * Returns the global SessionFactory either from a static variable or a JNDI lookup.
84       *
85       * @return SessionFactory
86       */
87      public static SessionFactory getSessionFactory() {
88          if(configuration==null){
89              init();
90          }
91          String sfName = configuration.getProperty(Environment.SESSION_FACTORY_NAME);
92          if ( sfName != null) {
93              logger.debug("Looking up SessionFactory in JNDI");
94              try {
95                  return (SessionFactory) new InitialContext().lookup(sfName);
96              } catch (NamingException ex) {
97                  throw new RuntimeException(ex);
98              }
99          } else if (sessionFactory == null) {
100             rebuildSessionFactory();
101         }
102         return sessionFactory;
103     }
104 
105     /**
106      * Closes the current SessionFactory and releases all resources.
107      * <p>
108      * The only other method that can be called on HibernateUtil
109      * after this one is rebuildSessionFactory(Configuration).
110      */
111     public static void shutdown() {
112         logger.debug("Shutting down Hibernate");
113         // Close caches and connection pools
114         getSessionFactory().close();
115 
116         // Clear static variables
117         sessionFactory = null;
118     }
119 
120 
121     /**
122      * Rebuild the SessionFactory with the static Configuration.
123      * <p>
124      * Note that this method should only be used with static SessionFactory
125      * management, not with JNDI or any other external registry. This method also closes
126      * the old static variable SessionFactory before, if it is still open.
127      */
128      public static void rebuildSessionFactory() {
129         logger.debug("Using current Configuration to rebuild SessionFactory");
130         rebuildSessionFactory(configuration);
131      }
132 
133     /**
134      * Rebuild the SessionFactory with the given Hibernate Configuration.
135      * <p>
136      * HibernateUtil does not configure() the given Configuration object,
137      * it directly calls buildSessionFactory(). This method also closes
138      * the old static variable SessionFactory before, if it is still open.
139      *
140      * @param cfg
141      */
142      public static void rebuildSessionFactory(Configuration cfg) {
143         logger.debug("Rebuilding the SessionFactory from given Configuration");
144         if (sessionFactory != null && !sessionFactory.isClosed())
145             sessionFactory.close();
146         if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) {
147             logger.debug("Managing SessionFactory in JNDI");
148             cfg.buildSessionFactory();
149         } else {
150             logger.debug("Holding SessionFactory in static variable");
151             sessionFactory = cfg.buildSessionFactory();
152         }
153         configuration = cfg;
154      }
155 
156 }