1
2
3
4
5
6
7
8
9
10
11 package org.mule.transport.jdbc.util;
12
13 import org.mule.util.ClassUtils;
14 import org.mule.util.FileUtils;
15
16 import java.io.File;
17 import java.io.IOException;
18 import java.lang.reflect.Method;
19 import java.net.URL;
20 import java.sql.Driver;
21 import java.sql.DriverManager;
22 import java.sql.SQLException;
23 import java.util.Properties;
24
25 public class MuleDerbyUtils
26 {
27 private static final String DERBY_DRIVER_CLASS = "org.apache.derby.jdbc.EmbeddedDriver";
28
29
30 private MuleDerbyUtils()
31 {
32 super();
33 }
34
35
36 public static String setDerbyHome()
37 {
38 return setDerbyHome("target");
39 }
40
41 public static String setDerbyHome(String path)
42 {
43 File derbySystemHome = new File(System.getProperty("user.dir"), path);
44 System.setProperty("derby.system.home", derbySystemHome.getAbsolutePath());
45 return derbySystemHome.getAbsolutePath();
46 }
47
48
49
50
51
52
53
54 public static void stopDatabase() throws SQLException
55 {
56 try
57 {
58
59
60 ClassUtils.instanciateClass(DERBY_DRIVER_CLASS, new Object[0]);
61
62 DriverManager.getConnection("jdbc:derby:;shutdown=true");
63 }
64 catch (SQLException sqlex)
65 {
66
67 if (!"XJ015".equals(sqlex.getSQLState()))
68 {
69 throw sqlex;
70 }
71 }
72 catch (Exception ex)
73 {
74
75
76 throw new RuntimeException(ex);
77 }
78 }
79
80 public static void cleanupDerbyDb(String derbySystemHome, String databaseName) throws IOException, SQLException
81 {
82 stopDatabase();
83 FileUtils.deleteTree(new File(derbySystemHome + File.separator + databaseName));
84 }
85
86 public static void createDataBase(String databaseName) throws SQLException
87 {
88
89
90 try
91 {
92 Driver derbyDriver = (Driver) ClassUtils.instanciateClass(DERBY_DRIVER_CLASS, new Object[0]);
93
94 Method connectMethod = derbyDriver.getClass().getMethod("connect",
95 new Class[] { String.class, Properties.class });
96
97 String connectionName = "jdbc:derby:" + databaseName + ";create=true";
98 connectMethod.invoke(derbyDriver, new Object[] { connectionName, null });
99 }
100 catch (Exception ex)
101 {
102 throw new RuntimeException("Error creating the database " + databaseName, ex);
103 }
104 }
105
106 public static String loadDatabaseName(String propertiesLocation, String propertyName) throws IOException
107 {
108 Properties derbyProperties = new Properties();
109 URL resource = ClassUtils.getResource(propertiesLocation, MuleDerbyUtils.class);
110 derbyProperties.load(resource.openStream());
111 return derbyProperties.getProperty(propertyName);
112 }
113
114 public static void defaultDerbyCleanAndInit(String propertiesLocation, String propertyName) throws IOException, SQLException
115 {
116 String derbyHome = setDerbyHome();
117 String dbName = loadDatabaseName(propertiesLocation, propertyName);
118 cleanupDerbyDb(derbyHome, dbName);
119 createDataBase(dbName);
120 }
121 }
122
123