1 22 package org.jboss.jdbc; 23 24 import java.sql.Connection ; 25 import java.sql.DriverManager ; 26 import java.sql.SQLException ; 27 28 import javax.management.MBeanRegistration ; 29 import javax.management.MBeanServer ; 30 import javax.management.MalformedObjectNameException ; 31 import javax.management.ObjectName ; 32 33 import org.jboss.system.ServiceMBeanSupport; 34 35 46 public class DerbyDatabase 47 extends ServiceMBeanSupport 48 implements DerbyDatabaseMBean, MBeanRegistration 49 { 50 53 private static final String DEFAULT_PASSWORD = ""; 54 55 58 private static final String DEFAULT_USER = "sa"; 59 60 63 private static final String JDBC_DRIVER_CLASS = "org.apache.derby.jdbc.EmbeddedDriver"; 64 65 68 private static final String JDBC_URL_PREFIX = "jdbc:derby:"; 69 70 73 private static final String DERBY_DATA_DIR = "derby"; 74 75 78 private static final String DEFAULT_DATABASE_NAME = "default"; 79 80 83 String name = DEFAULT_DATABASE_NAME; 84 85 88 private String user = DEFAULT_USER; 89 90 93 private String password = DEFAULT_PASSWORD; 94 95 98 private Connection connection; 99 100 105 public void setDatabase(String name) 106 { 107 if (name == null) 108 { 109 name = DEFAULT_DATABASE_NAME; 110 } 111 112 this.name = name; 113 } 114 115 120 public String getDatabase() 121 { 122 return name; 123 } 124 125 130 public String getPassword() 131 { 132 return password; 133 } 134 135 140 public String getUser() 141 { 142 return user; 143 } 144 145 150 public void setPassword(String password) 151 { 152 if (password == null) 153 { 154 password = DEFAULT_PASSWORD; 155 } 156 157 this.password = password; 158 } 159 160 165 public void setUser(String user) 166 { 167 if (user == null) 168 { 169 user = DEFAULT_USER; 170 } 171 172 this.user = user; 173 } 174 175 protected ObjectName getObjectName(MBeanServer server, ObjectName name) 176 throws MalformedObjectNameException 177 { 178 return name == null ? OBJECT_NAME : name; 179 } 180 181 protected void startService() throws Exception 182 { 183 String dbURL = JDBC_URL_PREFIX + System.getProperty("jboss.server.data.dir") + 184 '/' + DerbyDatabase.DERBY_DATA_DIR + 185 '/' + name + ";create=true"; 186 log.info("starting derby " + dbURL); 187 188 connection = getConnection(dbURL); 190 } 191 192 protected void stopService() throws Exception 193 { 194 try 195 { 196 getConnection("jdbc:derby:;shutdown=true"); 197 log.error("According to the docs, should have caught an exception!"); 198 } 199 catch(SQLException e) 200 { 201 log.info("Derby shutdown successfully.", e); 202 } 203 204 connection = null; 205 } 206 207 216 private synchronized Connection getConnection(String dbURL) throws Exception 217 { 218 if (connection == null) 219 { 220 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 221 222 Class.forName(JDBC_DRIVER_CLASS, true, cl).newInstance(); 223 224 connection = DriverManager.getConnection(dbURL, user, password); 225 } 226 227 return connection; 228 } 229 } 230 | Popular Tags |