KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > install > DatabaseCreator


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.outerj.daisy.install;
17
18 import java.sql.*;
19 import java.io.Reader JavaDoc;
20 import java.io.BufferedReader JavaDoc;
21 import java.security.MessageDigest JavaDoc;
22
23 public class DatabaseCreator {
24
25     /**
26      * Makes the current database empty. This is used by the testcases to start
27      * from a fresh state for each testcase.
28      *
29      * <p>This method should make the database empty, as if were just created as new.
30      */

31     public void clearDatabase(String JavaDoc dburl, String JavaDoc dbuser, String JavaDoc dbpwd, String JavaDoc dbname) throws Exception JavaDoc {
32         Connection conn = DriverManager.getConnection(dburl, dbuser, dbpwd);
33         DatabaseSpecifics dbSpecifics = null;
34         try {
35             dbSpecifics = DatabaseSpecificsFactory.getDatabaseSpecifics(conn);
36         } finally {
37             conn.close();
38         }
39         dbSpecifics.clearDatabase(dburl, dbname, dbuser, dbpwd);
40     }
41
42     /**
43      * Installs the database script, optionally first dropping the existing
44      * database if it exists, and creating a bootstrap user (with Administrator role).
45      *
46      * <p>The script is supposed to create all the required tables, and create
47      * the Administrator role with id 1. The user id 2 should be available.
48      *
49      * @param dburl
50      * @param dbuser username for the database
51      * @param dbpwd password for the database
52      * @param bootstrapUserLogin bootstrap user to be created
53      * @param bootstrapUserPassword password for bootstrap user
54      * @throws Exception
55      */

56     public void run(String JavaDoc dburl, String JavaDoc dbuser, String JavaDoc dbpwd,
57             String JavaDoc bootstrapUserLogin, String JavaDoc bootstrapUserPassword,
58             String JavaDoc internalUserLogin, String JavaDoc internalUserPassword) throws Exception JavaDoc {
59
60         Connection conn = null;
61         Statement stmt = null;
62         try {
63             conn = DriverManager.getConnection(dburl, dbuser, dbpwd);
64             DatabaseSpecifics dbSpecifics = DatabaseSpecificsFactory.getDatabaseSpecifics(conn);
65
66             stmt = conn.createStatement();
67
68             String JavaDoc[] preStmts = dbSpecifics.getPreStatements();
69             for (int i = 0; i < preStmts.length; i++)
70                 stmt.execute(preStmts[i]);
71
72             execute(dbSpecifics.getSchemaScript(), conn, dbSpecifics);
73
74             conn.setAutoCommit(false);
75             execute(dbSpecifics.getDataScript(), conn, dbSpecifics);
76             conn.commit();
77             conn.setAutoCommit(true);
78
79             stmt.execute(dbSpecifics.getForeignKeyStatement("roles", "last_modifier", "users", "id", "role_modifier_fk"));
80
81             String JavaDoc[] postStmts = dbSpecifics.getPostStatements();
82             for (int i = 0; i < postStmts.length; i++)
83                 stmt.execute(postStmts[i]);
84
85             createUser(conn, 2, internalUserLogin, internalUserPassword, 1, new long[] {1}, dbSpecifics);
86             createUser(conn, 3, bootstrapUserLogin, bootstrapUserPassword, 2, new long[] {1,2}, dbSpecifics);
87         } finally {
88             if (stmt != null)
89                 try { stmt.close(); } catch (Exception JavaDoc e) { /* ignore */ }
90             if (conn != null)
91                 conn.close();
92         }
93     }
94
95     private void createUser(Connection conn, long id, String JavaDoc login, String JavaDoc password, long defaultRoleId, long[] roles, DatabaseSpecifics dbSpecifics ) throws SQLException {
96         PreparedStatement stmt = null;
97         try {
98             StringBuffer JavaDoc sqlInsert = new StringBuffer JavaDoc();
99             sqlInsert.append("insert into users(id,login,password,default_role,first_name,last_name,email,updateable_by_user,confirmed,confirmkey,auth_scheme,last_modified,last_modifier,updatecount) ");
100             String JavaDoc valueStmt = "values(?, ?, ?, ?, null, null, null, ?, ?, null, 'daisy', @datetime@, 1, 1)";
101             valueStmt = valueStmt.replaceAll("@datetime@", dbSpecifics.getCurrentDateTimeFunction());
102             sqlInsert.append(valueStmt);
103
104             stmt = conn.prepareStatement( sqlInsert.toString() );
105             stmt.setLong(1, id);
106             stmt.setString(2, login);
107             stmt.setString(3, hashPassword(password));
108             stmt.setLong(4, defaultRoleId);
109             stmt.setBoolean(5, true);
110             stmt.setBoolean(6, true);
111             stmt.execute();
112             stmt.close();
113
114             stmt = conn.prepareStatement("insert into user_roles(user_id,role_id) values(?, ?)");
115             for (int i = 0; i < roles.length; i++) {
116                 stmt.setLong(1, id);
117                 stmt.setLong(2, roles[i]);
118                 stmt.execute();
119             }
120         } finally {
121             if (stmt != null)
122                 try { stmt.close(); } catch (Exception JavaDoc e) { /* ignore */ }
123         }
124     }
125
126     private void execute(Reader JavaDoc script, Connection conn, DatabaseSpecifics dbSpecifics) throws Exception JavaDoc {
127         BufferedReader JavaDoc reader = new BufferedReader JavaDoc(script);
128
129         StringBuffer JavaDoc stmtBuffer = new StringBuffer JavaDoc();
130         char statementSeparator = dbSpecifics.getStatementSeparator();
131         boolean dropStatementSeparator = dbSpecifics.getDropStatementSeparator();
132
133         String JavaDoc line;
134         int lineno = 0;
135         for (line = reader.readLine(); line != null; line = reader.readLine(), ++lineno) {
136             line = line.trim();
137             if (line.length() == 0)
138                 continue;
139             if (line.charAt(0) == '#')
140                 continue;
141             if (line.length() >= 2 && line.charAt(0) == '-' && line.charAt(1) == '-' )
142                 continue;
143             if (!lastCharacterIsStatementSeparator(line, statementSeparator)) {
144                 stmtBuffer.append(" ").append(line).append(" ");
145                 continue;
146             }
147             if (!dropStatementSeparator) {
148                 stmtBuffer.append(" ").append(line).append(" ");
149             }
150             Statement stmt = conn.createStatement();
151             String JavaDoc statement = "";
152             try {
153                 statement = stmtBuffer.toString().trim();
154                 statement = statement.replaceAll("'current-date-and-time'", dbSpecifics.getCurrentDateTimeFunction());
155                 stmt.execute(statement);
156                 System.out.print( '.' );
157             } catch (SQLException e) {
158                 System.out.println();
159                 System.out.println(e.getMessage());
160                 System.out.print( "Error in Line: " + lineno + ": " + statement );
161                 System.out.println();
162             } finally {
163                 stmt.close();
164             }
165             stmtBuffer.setLength(0);
166         }
167         System.out.println();
168     }
169
170     private boolean lastCharacterIsStatementSeparator(String JavaDoc buffer, char statementSeparator) {
171         for (int i = buffer.length() - 1; i >=0; i--) {
172             char c = buffer.charAt(i);
173             if (!Character.isWhitespace(c))
174                 return c == statementSeparator;
175         }
176         return false;
177     }
178
179     public static String JavaDoc hashPassword(String JavaDoc password) {
180         if (password == null)
181             return null;
182         try {
183             byte[] data = password.getBytes("UTF-8");
184             MessageDigest JavaDoc digest = MessageDigest.getInstance("SHA-1");
185             digest.update(data);
186             byte[] result = digest.digest();
187             return toHexString(result);
188         } catch (Exception JavaDoc e) {
189             throw new RuntimeException JavaDoc("Problem calculating password hash.", e);
190         }
191     }
192
193     public static String JavaDoc toHexString(byte[] b) {
194         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(b.length * 2);
195         for (int i = 0; i < b.length; i++) {
196             sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
197             sb.append(hexChar[b[i] & 0x0f]);
198         }
199         return sb.toString();
200     }
201
202     static char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
203
204 }
205
Popular Tags