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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
51 try {
52 logger.debug("Initializing Hibernate");
53
54
55 configuration = new Configuration();
56
57
58
59 configuration.configure();
60
61
62 rebuildSessionFactory(configuration);
63
64 logger.debug("Hibernate initialized, call HibernateUtil.getSessionFactory()");
65 } catch (Throwable ex) {
66
67
68 logger.error("Building SessionFactory failed.", ex);
69 throw new ExceptionInInitializerError(ex);
70 }
71 }
72
73
74
75
76
77
78 public static Configuration getConfiguration() {
79 return configuration;
80 }
81
82
83
84
85
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
107
108
109
110
111 public static void shutdown() {
112 logger.debug("Shutting down Hibernate");
113
114 getSessionFactory().close();
115
116
117 sessionFactory = null;
118 }
119
120
121
122
123
124
125
126
127
128 public static void rebuildSessionFactory() {
129 logger.debug("Using current Configuration to rebuild SessionFactory");
130 rebuildSessionFactory(configuration);
131 }
132
133
134
135
136
137
138
139
140
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 }