KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jbpm > identity > hibernate > IdentitySchema


1 package org.jbpm.identity.hibernate;
2
3 import java.io.*;
4 import java.lang.reflect.*;
5 import java.sql.*;
6 import java.util.*;
7 import java.util.List JavaDoc;
8
9 import org.apache.commons.logging.*;
10 import org.hibernate.cfg.*;
11 import org.hibernate.connection.*;
12 import org.hibernate.dialect.*;
13 import org.hibernate.engine.*;
14 import org.hibernate.mapping.*;
15 import org.hibernate.tool.hbm2ddl.*;
16 import org.hibernate.util.*;
17
18 public class IdentitySchema {
19
20   private static final String JavaDoc IDENTITY_TABLE_PREFIX = "JBPM_ID_";
21   
22   Configuration configuration = null;
23   Properties properties = null;
24   Dialect dialect = null;
25   Mapping mapping = null;
26   String JavaDoc[] createSql = null;
27   String JavaDoc[] dropSql = null;
28   String JavaDoc[] cleanSql = null;
29
30   ConnectionProvider connectionProvider = null;
31   Connection connection = null;
32   Statement statement = null;
33
34   public IdentitySchema(Configuration configuration) {
35     this.configuration = configuration;
36     this.properties = configuration.getProperties();
37     this.dialect = Dialect.getDialect(properties);
38     try {
39       // get the mapping field via reflection :-(
40
Field mappingField = Configuration.class.getDeclaredField("mapping");
41       mappingField.setAccessible(true);
42       this.mapping = (Mapping) mappingField.get(configuration);
43     } catch (Exception JavaDoc e) {
44       throw new RuntimeException JavaDoc("couldn't get the hibernate mapping", e);
45     }
46   }
47
48   // scripts lazy initializations /////////////////////////////////////////////
49

50   public String JavaDoc[] getCreateSql() {
51     if (createSql==null) {
52       createSql = configuration.generateSchemaCreationScript(dialect);
53     }
54     return createSql;
55   }
56   
57   public String JavaDoc[] getDropSql() {
58     if (dropSql==null) {
59       dropSql = configuration.generateDropSchemaScript(dialect);
60     }
61     return dropSql;
62   }
63   
64   public String JavaDoc[] getCleanSql() {
65     if (cleanSql==null) {
66       // loop over all foreign key constraints
67
List JavaDoc dropForeignKeysSql = new ArrayList();
68       List JavaDoc createForeignKeysSql = new ArrayList();
69       Iterator iter = configuration.getTableMappings();
70       while ( iter.hasNext() ) {
71         Table table = ( Table ) iter.next();
72         if ( table.isPhysicalTable() ) {
73           Iterator subIter = table.getForeignKeyIterator();
74           while ( subIter.hasNext() ) {
75             ForeignKey fk = ( ForeignKey ) subIter.next();
76             if ( fk.isPhysicalConstraint() ) {
77               // collect the drop key constraint
78
dropForeignKeysSql.add( fk.sqlDropString(
79                   dialect,
80                   properties.getProperty(Environment.DEFAULT_CATALOG),
81                   properties.getProperty(Environment.DEFAULT_SCHEMA) ) );
82               createForeignKeysSql.add( fk.sqlCreateString(
83                   dialect,
84                   mapping,
85                   properties.getProperty(Environment.DEFAULT_CATALOG),
86                   properties.getProperty(Environment.DEFAULT_SCHEMA) ) );
87             }
88           }
89         }
90       }
91
92       List JavaDoc deleteSql = new ArrayList();
93       iter = configuration.getTableMappings();
94       while (iter.hasNext()) {
95         Table table = (Table) iter.next();
96         deleteSql.add("delete from "+table.getName());
97       }
98
99       List JavaDoc cleanSqlList = new ArrayList();
100       cleanSqlList.addAll(dropForeignKeysSql);
101       cleanSqlList.addAll(deleteSql);
102       cleanSqlList.addAll(createForeignKeysSql);
103       
104       cleanSql = (String JavaDoc[]) cleanSqlList.toArray(new String JavaDoc[cleanSqlList.size()]);
105     }
106     return cleanSql;
107   }
108
109   // runtime table detection //////////////////////////////////////////////////
110

111   public boolean hasIdentityTables() {
112     return (getIdentityTables().size()>0);
113   }
114
115   public List JavaDoc getIdentityTables() {
116     // delete all the data in the jbpm tables
117
List JavaDoc jbpmTableNames = new ArrayList();
118     try {
119       createConnection();
120       ResultSet resultSet = connection.getMetaData().getTables("", "", null, null);
121       while(resultSet.next()) {
122         String JavaDoc tableName = resultSet.getString("TABLE_NAME");
123         if ( (tableName!=null)
124              && (tableName.length()>5)
125              && (IDENTITY_TABLE_PREFIX.equalsIgnoreCase(tableName.substring(0,5))) ) {
126           jbpmTableNames.add(tableName);
127         }
128       }
129     } catch (SQLException e) {
130       throw new RuntimeException JavaDoc("couldn't get the jbpm table names");
131     } finally {
132       closeConnection();
133     }
134     return jbpmTableNames;
135   }
136   
137   // script execution methods /////////////////////////////////////////////////
138

139   public void dropSchema() {
140     execute( getDropSql() );
141   }
142
143   public void createSchema() {
144     execute( getCreateSql() );
145   }
146
147   public void cleanSchema() {
148     execute( getCleanSql() );
149   }
150
151   public void saveSqlScripts(String JavaDoc dir, String JavaDoc prefix) {
152     try {
153       new File(dir).mkdirs();
154       saveSqlScript(dir+"/"+prefix+".drop.sql", getDropSql());
155       saveSqlScript(dir+"/"+prefix+".create.sql", getCreateSql());
156       saveSqlScript(dir+"/"+prefix+".clean.sql", getCleanSql());
157       new SchemaExport(configuration)
158         .setDelimiter(getSqlDelimiter())
159         .setOutputFile(dir+"/"+prefix+".drop.create.sql")
160         .create(true, false);
161     } catch (Exception JavaDoc e) {
162       throw new RuntimeException JavaDoc("couldn't generate scripts", e);
163     }
164   }
165
166   // main /////////////////////////////////////////////////////////////////////
167

168   public static void main(String JavaDoc[] args) {
169     try {
170       if ( (args!=null)
171            && (args.length==1)
172            && ("create".equalsIgnoreCase(args[0])) ) {
173         new IdentitySchema(IdentitySessionFactory.createConfiguration()).createSchema();
174       } else if ( (args!=null)
175               && (args.length==1)
176               && ("drop".equalsIgnoreCase(args[0])) ) {
177         new IdentitySchema(IdentitySessionFactory.createConfiguration()).dropSchema();
178       } else if ( (args!=null)
179               && (args.length==1)
180               && ("clean".equalsIgnoreCase(args[0])) ) {
181         new IdentitySchema(IdentitySessionFactory.createConfiguration()).cleanSchema();
182       } else if ( (args!=null)
183               && (args.length==3)
184               && ("scripts".equalsIgnoreCase(args[0])) ) {
185         new IdentitySchema(IdentitySessionFactory.createConfiguration()).saveSqlScripts(args[1], args[2]);
186       } else {
187         System.err.println("syntax: JbpmSchema create");
188         System.err.println("syntax: JbpmSchema drop");
189         System.err.println("syntax: JbpmSchema clean");
190         System.err.println("syntax: JbpmSchema scripts <dir> <prefix>");
191       }
192     } catch (Exception JavaDoc e) {
193       e.printStackTrace();
194       throw new RuntimeException JavaDoc(e);
195     }
196   }
197   
198   private void saveSqlScript(String JavaDoc fileName, String JavaDoc[] sql) throws FileNotFoundException {
199     FileOutputStream fileOutputStream = new FileOutputStream(fileName);
200     PrintStream printStream = new PrintStream(fileOutputStream);
201     for (int i=0; i<sql.length; i++) {
202       printStream.println(sql[i]+getSqlDelimiter());
203     }
204   }
205   
206   // sql script execution /////////////////////////////////////////////////////
207

208   public void execute(String JavaDoc[] sqls) {
209     String JavaDoc sql = null;
210     String JavaDoc showSqlText = properties.getProperty("hibernate.show_sql");
211     boolean showSql = ("true".equalsIgnoreCase(showSqlText));
212
213     try {
214       createConnection();
215       statement = connection.createStatement();
216       
217       for (int i=0; i<sqls.length; i++) {
218         sql = sqls[i];
219         String JavaDoc delimitedSql = sql+getSqlDelimiter();
220         
221         if (showSql) log.debug(delimitedSql);
222         statement.executeUpdate(delimitedSql);
223       }
224     
225     } catch (SQLException e) {
226       e.printStackTrace();
227       throw new RuntimeException JavaDoc("couldn't execute sql '"+sql+"'", e);
228     } finally {
229       closeConnection();
230     }
231   }
232
233   private void closeConnection() {
234     try {
235       if (statement!=null) statement.close();
236       if (connection!=null) {
237         JDBCExceptionReporter.logWarnings( connection.getWarnings() );
238         connection.clearWarnings();
239         connectionProvider.closeConnection(connection);
240         connectionProvider.close();
241       }
242     }
243     catch(Exception JavaDoc e) {
244       System.err.println( "Could not close connection" );
245       e.printStackTrace();
246     }
247   }
248
249   private void createConnection() throws SQLException {
250     connectionProvider = ConnectionProviderFactory.newConnectionProvider(properties);
251     connection = connectionProvider.getConnection();
252     if ( !connection.getAutoCommit() ) {
253       connection.commit();
254       connection.setAutoCommit(true);
255     }
256   }
257   
258   public Properties getProperties() {
259     return properties;
260   }
261
262   // sql delimiter ////////////////////////////////////////////////////////////
263

264   private static String JavaDoc sqlDelimiter = null;
265   private synchronized String JavaDoc getSqlDelimiter() {
266     if (sqlDelimiter==null) {
267       sqlDelimiter = properties.getProperty("jbpm.sql.delimiter", ";");
268     }
269     return sqlDelimiter;
270   }
271
272   // logger ///////////////////////////////////////////////////////////////////
273

274   private static final Log log = LogFactory.getLog(IdentitySchema.class);
275 }
276
Popular Tags