01: // $Id: ConnectionHelper.java 7 2007-08-17 19:32:18Z jcamaia $
02:
03: package net.sf.persist.tests.framework;
04:
05: import java.io.IOException;
06: import java.io.InputStream;
07: import java.sql.Connection;
08: import java.sql.DriverManager;
09: import java.sql.SQLException;
10: import java.util.Properties;
11:
12: public class ConnectionHelper {
13:
14: /**
15: * Reads a properties file from the classpath and instantiates a java.sql.Connection with the given parameters.
16: */
17: public static Connection getConnection(String propertiesFilePath) {
18:
19: Properties properties = new Properties();
20: InputStream is = Thread.currentThread().getContextClassLoader()
21: .getResourceAsStream(propertiesFilePath);
22: try {
23: properties.load(is);
24: } catch (IOException e) {
25: throw new RuntimeException("Could not load "
26: + propertiesFilePath + " from the classpath");
27: }
28:
29: String driver = properties.getProperty("driver");
30: String url = properties.getProperty("url");
31: String user = properties.getProperty("user");
32: String password = properties.getProperty("password");
33:
34: if (driver == null || driver.trim().equals(""))
35: throw new RuntimeException("driver not specified in "
36: + propertiesFilePath);
37: if (url == null || url.trim().equals(""))
38: throw new RuntimeException("url not specified in "
39: + propertiesFilePath);
40: if (user == null || user.trim().equals(""))
41: throw new RuntimeException("user not specified in "
42: + propertiesFilePath);
43: if (password == null || password.trim().equals(""))
44: throw new RuntimeException("password not specified in "
45: + propertiesFilePath);
46:
47: try {
48: Class.forName(driver);
49: } catch (ClassNotFoundException e) {
50: throw new RuntimeException(e);
51: }
52:
53: Connection connection = null;
54:
55: try {
56: connection = DriverManager.getConnection(url, user,
57: password);
58: } catch (SQLException e) {
59: throw new RuntimeException(e);
60: }
61:
62: return connection;
63: }
64:
65: }
|