KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > util > database > DatabaseLoader


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.util.database;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.blojsom.util.BlojsomUtils;
36 import org.hibernate.SQLQuery;
37 import org.hibernate.Session;
38 import org.hibernate.SessionFactory;
39 import org.hibernate.Transaction;
40
41 import javax.servlet.ServletConfig JavaDoc;
42 import java.io.BufferedReader JavaDoc;
43 import java.io.InputStream JavaDoc;
44 import java.io.InputStreamReader JavaDoc;
45 import java.io.StringReader JavaDoc;
46 import java.sql.Connection JavaDoc;
47 import java.sql.PreparedStatement JavaDoc;
48 import java.util.List JavaDoc;
49
50 /**
51  * Database loader
52  *
53  * @author David Czarnecki
54  * @version $Id: DatabaseLoader.java,v 1.4 2006/05/05 23:57:03 czarneckid Exp $
55  * @since blojsom 3.0
56  */

57 public class DatabaseLoader {
58
59     private Log _logger = LogFactory.getLog(DatabaseLoader.class);
60
61     private static final String JavaDoc DEFAULT_DETECT_BLOJSOM_SQL = "show tables;";
62
63     private String JavaDoc _dbScript;
64     private SessionFactory _sessionFactory;
65     private ServletConfig JavaDoc _servletConfig;
66     private String JavaDoc _detectBlojsomSQL;
67     private boolean _upgrading = false;
68
69     /**
70      * Create a new instance of the Database loader
71      */

72     public DatabaseLoader() {
73     }
74
75     /**
76      * Set the {@link SessionFactory}
77      *
78      * @param sessionFactory {@link SessionFactory}
79      */

80     public void setSessionFactory(SessionFactory sessionFactory) {
81         _sessionFactory = sessionFactory;
82     }
83
84     /**
85      * Set the DB script to initialize and load the database
86      *
87      * @param dbScript DB script to initialize and load the database
88      */

89     public void setDbScript(String JavaDoc dbScript) {
90         _dbScript = dbScript;
91     }
92
93     /**
94      * Set the {@link ServletConfig}
95      *
96      * @param servletConfig {@link ServletConfig}
97      */

98     public void setServletConfig(ServletConfig JavaDoc servletConfig) {
99         _servletConfig = servletConfig;
100     }
101
102     /**
103      * SQL to detect blojsom
104      *
105      * @param detectBlojsomSQL SQL to detect blojsom
106      */

107     public void setDetectBlojsomSQL(String JavaDoc detectBlojsomSQL) {
108         _detectBlojsomSQL = detectBlojsomSQL;
109     }
110
111     /**
112      * Signal an upgrade for the database loader
113      *
114      * @param upgrading <code>true</code> if upgrading the database using the database script, <code>false</code> otherwise
115      */

116     public void setUpgrading(boolean upgrading) {
117         _upgrading = upgrading;
118     }
119
120     /**
121      * Initalize the blojsom database
122      */

123     public void init() {
124         if (_dbScript == null) {
125             if (_logger.isErrorEnabled()) {
126                 _logger.error("No database creation script defined");
127             }
128
129             return;
130         }
131
132         if (BlojsomUtils.checkNullOrBlank(_detectBlojsomSQL)) {
133             _detectBlojsomSQL = DEFAULT_DETECT_BLOJSOM_SQL;
134         }
135
136         Session session = _sessionFactory.openSession();
137         Transaction tx = null;
138
139         try {
140             tx = session.beginTransaction();
141
142             if (!_upgrading) {
143                 if (_logger.isInfoEnabled()) {
144                     _logger.info("About to create blojsom database");
145                 }
146             } else {
147                 if (_logger.isInfoEnabled()) {
148                     _logger.info("About to upgrade blojsom database");
149                 }
150             }
151
152             SQLQuery sqlQuery = session.createSQLQuery(_detectBlojsomSQL);
153             List JavaDoc tables = sqlQuery.list();
154
155             if (tables.size() > 0 && !_upgrading) {
156                 if (_logger.isInfoEnabled()) {
157                     _logger.info("blojsom database already created");
158                 }
159             } else {
160                 Connection JavaDoc sqlConnection = session.connection();
161
162                 InputStream JavaDoc is = _servletConfig.getServletContext().getResourceAsStream(_dbScript);
163                 BufferedReader JavaDoc bufferedReader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
164                 String JavaDoc input;
165                 StringBuffer JavaDoc sql = new StringBuffer JavaDoc();
166
167                 while ((input = bufferedReader.readLine()) != null) {
168                     if (!input.startsWith("--") && !"".equals(input.trim())) {
169                         if (!input.endsWith(";")) {
170                             sql.append(input).append(" ");
171                         } else {
172                             sql.append(input).append("\n");
173                         }
174                     }
175                 }
176
177                 if (_logger.isInfoEnabled()) {
178                     _logger.info("Read in sql script");
179                 }
180
181                 bufferedReader = new BufferedReader JavaDoc(new StringReader JavaDoc(sql.toString()));
182                 PreparedStatement JavaDoc preparedStatement;
183
184                 while ((input = bufferedReader.readLine()) != null) {
185                     preparedStatement = sqlConnection.prepareStatement(input);
186                     preparedStatement.execute();
187                 }
188
189                 if (!_upgrading) {
190                     if (_logger.isInfoEnabled()) {
191                         _logger.info("Finised blojsom database creation");
192                     }
193                 } else {
194                     if (_logger.isInfoEnabled()) {
195                         _logger.info("Finised upgrading blojsom database");
196                     }
197                 }
198             }
199
200             tx.commit();
201         } catch (Exception JavaDoc e) {
202             if (_logger.isErrorEnabled()) {
203                 _logger.error(e);
204             }
205
206             if (tx != null) {
207                 tx.rollback();
208             }
209         } finally {
210             session.close();
211         }
212     }
213 }
214
Popular Tags