KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portal > setup > impl > pm > HibernatePersistenceManager


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Distributable under LGPL license. *
6  * See terms of license at gnu.org. *
7  * *
8  *****************************************/

9 package org.jboss.portal.setup.impl.pm;
10
11 import org.jboss.portal.setup.pm.PersistenceManager;
12 import org.jboss.portal.setup.pm.PersistenceException;
13 import org.jboss.portal.setup.pm.PersistenceSession;
14 import org.jboss.portal.setup.config.Configuration;
15 import org.jboss.portal.setup.config.HibernateConfig;
16 import org.jboss.portal.setup.PortalSetupException;
17 import org.apache.log4j.Logger;
18 import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
19 import org.hibernate.tool.hbm2ddl.SchemaExport;
20 import org.hibernate.HibernateException;
21 import org.hibernate.SessionFactory;
22 import org.hibernate.Session;
23 import org.hibernate.MappingException;
24 import org.hibernate.dialect.Dialect;
25
26 import java.util.Iterator JavaDoc;
27
28 import java.util.List JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Properties JavaDoc;
31 import java.util.Arrays JavaDoc;
32 import java.sql.SQLException JavaDoc;
33
34
35 /**
36  * @author <a HREF="mailto:palber@novell.com">Polina Alber</a>
37  * Date: Apr 25, 2005; Time: 4:06:32 PM
38  * @since JBoss portal 2.0
39  * Class org.jboss.portal.setup.impl.pm.HibernatePersistenceManager
40  */

41 public class HibernatePersistenceManager implements PersistenceManager
42 {
43
44    private List JavaDoc m_sessions = new ArrayList JavaDoc();
45    private final Logger m_log = Logger.getLogger(getClass());
46 //Hibernate session builder configuration object
47
private org.hibernate.cfg.Configuration m_hibernateConfig = null;
48    private SessionFactory m_sessionFactory = null;
49    private Dialect m_dialect = null;
50    private boolean m_useSchemaExport = true;
51    private SchemaExport m_schExport = null;
52    private Session m_defaultSession = null;
53
54
55    public void initialize(Configuration config, List JavaDoc uris) throws PersistenceException, PortalSetupException
56    {
57       if (config instanceof HibernateConfig)
58       {
59          setupHibernate((HibernateConfig)config, uris);
60       }
61       else
62       {
63          throw new PersistenceException("Failed to initialize HibernatePersistenceManager due to invlid configuration object! Expected instance of HibernateConfig.");
64       }
65    }
66
67    public PersistenceSession getSession() throws PersistenceException
68    {
69       PersistenceSession session = null;
70       Session hbSession = null;
71       try
72       {
73          hbSession = m_sessionFactory.openSession();
74          session = new HibernatePesistenceSession(hbSession, m_dialect, m_log);
75       }
76       catch (HibernateException he)
77       {
78          throw new PersistenceException("Failed to open persistence esssion", he);
79       }
80       synchronized (m_sessions)
81       {
82          m_sessions.add(session);
83       }
84       return session;
85    }
86
87    public void closeSession(PersistenceSession ps) throws PersistenceException
88    {
89       if (ps != null)
90       {
91          synchronized (m_sessions)
92          {
93             m_sessions.remove(ps);
94          }
95          ps.close();
96       }
97    }
98
99    public void destroy() throws PersistenceException
100    {
101       synchronized (m_sessions)
102       {
103          if (m_sessions.isEmpty())
104          {
105             Iterator JavaDoc iter = m_sessions.iterator();
106             while (iter.hasNext())
107             {
108                PersistenceSession session = (PersistenceSession)iter.next();
109                try
110                {
111                   session.close();
112                }
113                catch (PersistenceException pe)
114                {
115                   //log error
116
}
117             }
118             m_sessions.clear();
119
120          }
121       }
122       m_dialect = null;
123       if (null != m_defaultSession)
124       {
125          try
126          {
127             m_defaultSession.close();
128          }
129          catch (HibernateException he)
130          {
131             m_log.warn("Failed to close Hibernate session ", he);
132          }
133          m_defaultSession = null;
134       }
135       if (null != m_sessionFactory)
136       {
137          try
138          {
139             m_sessionFactory.close();
140          }
141          catch (HibernateException he)
142          {
143             m_log.warn("Failed to close Hibernate session factory", he);
144          }
145       }
146    }
147
148
149    public boolean loadPersistenceSchema() throws PersistenceException
150    {
151       boolean result = false;
152       if (m_useSchemaExport)
153       {
154          m_schExport.create(true, true);
155          if (m_log.isDebugEnabled())
156          {
157             m_log.debug("Succesfully loaded schema via ExportSchema.create(..)");
158          }
159          result = true;
160       }
161       else
162       {
163          String JavaDoc[] loadSql = null;
164          try
165          {
166             loadSql = m_hibernateConfig.generateSchemaCreationScript(m_dialect);
167             if (m_log.isDebugEnabled())
168             {
169                m_log.debug("Succsfully generated Schema load script");
170             }
171          }
172          catch (HibernateException he)
173          {
174             String JavaDoc msg = "Failed to generate create schema script";
175             m_log.error(msg, he);
176             throw new PersistenceException("Failed to generate create schema script", he);
177          }
178          if (loadSql != null)
179          {
180             List JavaDoc sqlList = new ArrayList JavaDoc();
181             sqlList.addAll(Arrays.asList(loadSql));
182             PersistenceSession ps = this.getSession();
183             ps.openTransaction();
184             result = ps.execute(sqlList);
185          }
186       }
187
188
189       return result;
190    }
191
192    public Dialect getDialect()
193    {
194       return m_dialect;
195    }
196
197    public org.hibernate.cfg.Configuration getHibernateConfiguration()
198    {
199       return m_hibernateConfig;
200    }
201
202    public boolean destroyPersistenceSchema() throws PersistenceException
203    {
204       boolean result = false;
205       if (m_useSchemaExport)
206       {
207          m_schExport.drop(true, true);
208          result = true;
209       }
210       else
211       {
212          String JavaDoc[] dropSql = null;
213          try
214          {
215             dropSql = m_hibernateConfig.generateDropSchemaScript(m_dialect);
216          }
217          catch (HibernateException he)
218          {
219             String JavaDoc msg = "Failed to generate drop schema script";
220             m_log.error(msg, he);
221             throw new PersistenceException(msg, he);
222          }
223          if (dropSql != null)
224          {
225             result = bachExecute(dropSql);
226          }
227       }
228       return result;
229    }
230
231    public DatabaseMetadata getDatabaseMetadata() throws PersistenceException
232    {
233       try
234       {
235          return new DatabaseMetadata(m_defaultSession.connection(), m_dialect);
236       }
237       catch (HibernateException he)
238       {
239
240          throw new PersistenceException(he);
241       }
242       catch (SQLException JavaDoc se)
243       {
244          throw new PersistenceException(se);
245       }
246    }
247
248
249    private boolean bachExecute(String JavaDoc[] sql) throws PersistenceException
250    {
251       boolean result = false;
252       PersistenceSession ps = null;
253       List JavaDoc sqlList = new ArrayList JavaDoc();
254       sqlList.addAll(Arrays.asList(sql));
255       try
256       {
257          ps = getSession();
258          result = ps.execute(sqlList);
259
260       }
261       finally
262       {
263          if (ps != null)
264          {
265             ps.close();
266          }
267       }
268       return result;
269    }
270
271    private void setupHibernate(HibernateConfig hbc, List JavaDoc uris) throws PersistenceException, PortalSetupException
272    {
273       m_hibernateConfig = new org.hibernate.cfg.Configuration();
274
275       Properties JavaDoc props = null;
276
277       props = hbc.getHibernateProperties();
278
279       m_hibernateConfig.addProperties(props);
280
281       setUpSchemaMappings(hbc, uris);
282       try
283       {
284          m_dialect = Dialect.getDialect(props);
285          m_sessionFactory = m_hibernateConfig.buildSessionFactory();
286          m_defaultSession = m_sessionFactory.openSession();
287          initializeSchemaExport(null);
288       }
289       catch (HibernateException he)
290       {
291          throw new PersistenceException("Failed to setup Hibenate schema loader", he);
292       }
293
294
295    }
296
297    private void setUpSchemaMappings(HibernateConfig hbc, List JavaDoc uris) throws PersistenceException
298    {
299       ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
300       List JavaDoc classes = hbc.getSchemaClassesList();
301       Iterator JavaDoc iter = null;
302       boolean schemaDefFound = false;
303
304       if (classes != null && !classes.isEmpty())
305       {
306          try
307          {
308             iter = classes.iterator();
309             while (iter.hasNext())
310             {
311                Class JavaDoc schemaClass = (Class JavaDoc)iter.next();
312                m_hibernateConfig.addClass(schemaClass);
313             }
314             schemaDefFound = true;
315          }
316          catch (MappingException me)
317          {
318             throw new PersistenceException("Failed to setup hibernate configuration!", me);
319          }
320       }
321       else if (null != uris && !uris.isEmpty())
322       {
323          iter = null;
324          iter = uris.iterator();
325          try
326          {
327             while (iter.hasNext())
328             {
329                String JavaDoc schemaUri = (String JavaDoc)iter.next();
330                m_hibernateConfig.addResource(schemaUri, cl);
331             }
332          }
333          catch (MappingException me)
334          {
335             throw new PersistenceException("Failed to setup hibernate configuration!", me);
336          }
337       }
338    }
339
340    synchronized private void initializeSchemaExport(List JavaDoc uris) throws PersistenceException
341    {
342       ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
343 //XXXX parse URIs
344
if (null != uris)
345       {
346          Iterator JavaDoc iter = uris.iterator();
347          try
348          {
349             while (iter.hasNext())
350             {
351                String JavaDoc schemaUri = (String JavaDoc)iter.next();
352                m_hibernateConfig.addResource(schemaUri, cl);
353             }
354          }
355          catch (MappingException me)
356          {
357             throw new PersistenceException("Failed to setup hibernate configuration!", me);
358          }
359       }
360       try
361       {
362          m_schExport = new SchemaExport(m_hibernateConfig);
363       }
364       catch (HibernateException he)
365       {
366          throw new PersistenceException("Failed to initialize schema export object!", he);
367       }
368    }
369
370 }
371
Popular Tags