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