KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portal > core > hibernate > SessionFactoryBinder


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.core.hibernate;
10
11 import org.jboss.portal.server.util.Service;
12 import org.jboss.portal.common.util.Tools;
13 import org.hibernate.cfg.Configuration;
14 import org.hibernate.cfg.Environment;
15 import org.hibernate.SessionFactory;
16 import org.hibernate.Session;
17 import org.hibernate.Query;
18 import org.hibernate.exception.SQLGrammarException;
19 import org.hibernate.metadata.ClassMetadata;
20 import org.hibernate.tool.hbm2ddl.SchemaExport;
21
22 import java.net.URL JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27
28 import bsh.Interpreter;
29 import bsh.EvalError;
30
31 /**
32  * Configures and binds the hibernate session factory.
33  *
34  * @jmx.mbean
35  * @jboss.xmbean
36  *
37  * @author <a HREF="mailto:julien@jboss.org">Julien Viet</a>
38  * @version $Revision: 1.2 $
39  */

40 public class SessionFactoryBinder extends Service
41 {
42
43    /** . */
44    private String JavaDoc configLocation;
45
46    /** . */
47    private String JavaDoc setupLocation;
48
49    /** If true checks the schema existence on start and create it if necessary. */
50    private boolean doChecking;
51
52    /** The session factory. */
53    private SessionFactory sessionFactory;
54
55    /** Where we configure hibernate. */
56    private URL JavaDoc configURL;
57
58    /** . */
59    private URL JavaDoc setupURL;
60
61    /** The hibernate configuration object. */
62    private Configuration config;
63
64    /**
65     * @jmx.managed-attribute
66     */

67    public boolean getDoChecking()
68    {
69       return doChecking;
70    }
71
72    /**
73     * @jmx.managed-attribute
74     */

75    public void setDoChecking(boolean doChecking)
76    {
77       this.doChecking = doChecking;
78    }
79
80    /**
81     * @jmx.managed-attribute
82     */

83    public String JavaDoc getConfigLocation()
84    {
85       return configLocation;
86    }
87
88    /**
89     * @jmx.managed-attribute
90     */

91    public void setConfigLocation(String JavaDoc configLocation)
92    {
93       this.configLocation = configLocation;
94    }
95
96    /**
97     * @jmx.managed-attribute
98     */

99    public String JavaDoc getSetupLocation()
100    {
101       return setupLocation;
102    }
103
104    /**
105     * @jmx.managed-attribute
106     */

107    public void setSetupLocation(String JavaDoc setupLocation)
108    {
109       this.setupLocation = setupLocation;
110    }
111
112    protected void startService() throws Exception JavaDoc
113    {
114       // Setup URLs
115
configURL = Thread.currentThread().getContextClassLoader().getResource(configLocation);
116       setupURL = Thread.currentThread().getContextClassLoader().getResource(setupLocation);
117
118       // Perform configuration
119
config = new Configuration();
120       config.configure(configURL);
121
122       // Force transaction manager lookup class
123
config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.transaction.JBossTransactionManagerLookup");
124       config.setProperty(Environment.CACHE_PROVIDER, "org.hibernate.cache.HashtableCacheProvider");
125
126       //
127
createSessionFactory();
128
129       //
130
if (doChecking && !doCheck())
131       {
132          //
133
createSchema();
134
135          //
136
createContent();
137       }
138    }
139
140    protected void stopService() throws Exception JavaDoc
141    {
142       if (sessionFactory != null)
143       {
144          sessionFactory.close();
145          sessionFactory = null;
146       }
147       else
148       {
149          log.debug("No session factory to close");
150       }
151    }
152
153    /**
154     * Create the schema in the database.
155     *
156     * @jmx.managed-operation
157     */

158    public boolean doCheck()
159    {
160       Session session = null;
161       try
162       {
163          session = sessionFactory.openSession();
164          for (Iterator JavaDoc i = sessionFactory.getAllClassMetadata().values().iterator();i.hasNext();)
165          {
166             ClassMetadata cmd = (ClassMetadata)i.next();
167             Query query = session.createQuery("from " + cmd.getEntityName());
168             query.setFirstResult(0);
169             query.setMaxResults(0);
170             try
171             {
172                query.list();
173             }
174             catch (SQLGrammarException e)
175             {
176                // We consider that exception means that the schema deos not exist
177
log.debug("Got sql grammar exception from hibernate, we consider the schema does not exists", e);
178                return false;
179             }
180          }
181       }
182       finally
183       {
184          Tools.safeClose(session);
185       }
186
187       //
188
log.debug("The schema was checked as valid");
189       return true;
190    }
191
192    /**
193     * Create the schema in the database.
194     *
195     * @jmx.managed-operation
196     */

197    public void createSchema()
198    {
199       log.debug("Creating database schema");
200       SchemaExport export = new SchemaExport(config);
201       export.create(false, true);
202    }
203
204    /**
205     * Destroy the schema in the database.
206     *
207     * @jmx.managed-operation
208     */

209    public void destroySchema()
210    {
211       log.debug("Destroying database schema");
212       SchemaExport export = new SchemaExport(config);
213       export.drop(false, true);
214    }
215
216    /**
217     * Populate with the default content.
218     *
219     * @jmx.managed-operation
220     */

221    public void createContent()
222    {
223       InputStream JavaDoc in = null;
224       try
225       {
226          log.info("Creating database content");
227
228          //
229
ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
230          in = setupURL.openStream();
231          Tools.copy(in, out);
232          String JavaDoc script = out.toString("UTF-8");
233
234          // Create an interpreter and configures it
235
Interpreter interpreter = new Interpreter();
236          interpreter.setClassLoader(Thread.currentThread().getContextClassLoader());
237          interpreter.setOut(System.out);
238          interpreter.set("SessionFactory", sessionFactory);
239          interpreter.eval(script);
240       }
241       catch (EvalError e)
242       {
243          log.error("Error in the bsh script", e);
244       }
245       catch (IOException JavaDoc e)
246       {
247          log.error("Cannot load setup script", e);
248       }
249       finally
250       {
251          Tools.safeClose(in);
252       }
253    }
254
255    /**
256     * Create the session factory.
257     */

258    protected void createSessionFactory()
259    {
260       // Build and bind the session factory
261
sessionFactory = config.buildSessionFactory();
262
263       //
264
String JavaDoc dialect = config.getProperty(Environment.DIALECT);
265       log.info("Hibernate dialect used " + dialect);
266    }
267 }
268
Popular Tags