diff flys-aft/src/main/java/de/intevation/db/ConnectionBuilder.java @ 4072:88f801888d85

load configuration an setup db connections. flys-aft/trunk@3401 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Tue, 13 Dec 2011 12:33:36 +0000
parents
children 2c70fae83d0c
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-aft/src/main/java/de/intevation/db/ConnectionBuilder.java	Tue Dec 13 12:33:36 2011 +0000
@@ -0,0 +1,72 @@
+package de.intevation.db;
+
+import de.intevation.utils.XML;
+
+import java.util.HashMap;
+
+import org.w3c.dom.Document;
+
+import javax.xml.xpath.XPathConstants;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.DriverManager;
+
+import org.apache.log4j.Logger;
+
+public class ConnectionBuilder
+{
+    private static Logger log = Logger.getLogger(ConnectionBuilder.class);
+
+    public static final String XPATH_DRIVER   = "/sync/side[@name=$type]/db/driver/text()";
+    public static final String XPATH_USER     = "/sync/side[@name=$type]/db/user/text()";
+    public static final String XPATH_PASSWORD = "/sync/side[@name=$type]/db/password/text()";
+    public static final String XPATH_URL      = "/sync/side[@name=$type]/db/url/text()";
+
+    protected String type;
+    protected String driver;
+    protected String user;
+    protected String password;
+    protected String url;
+
+    public ConnectionBuilder(String type, Document document) {
+        this.type = type;
+        extractCredentials(document);
+    }
+
+    protected void extractCredentials(Document document) {
+        HashMap<String, String> map = new HashMap<String, String>();
+        map.put("type", type);
+
+        driver = (String)XML.xpath(
+            document, XPATH_DRIVER, XPathConstants.STRING, null, map);
+        user = (String)XML.xpath(
+            document, XPATH_USER, XPathConstants.STRING, null, map);
+        password = (String)XML.xpath(
+            document, XPATH_PASSWORD, XPathConstants.STRING, null, map);
+        url = (String)XML.xpath(
+            document, XPATH_URL, XPathConstants.STRING, null, map);
+
+        if (log.isDebugEnabled()) {
+            log.debug("driver: " + driver);
+            log.debug("user: " + user);
+            log.debug("password: *******");
+            log.debug("url: " + url);
+        }
+    }
+
+    public Connection getConnection() throws SQLException {
+
+        if (driver != null && driver.length() > 0) {
+            try {
+                Class.forName(driver);
+            }
+            catch (ClassNotFoundException cnfe) {
+                throw new SQLException(cnfe);
+            }
+        }
+
+        return DriverManager.getConnection(url, user, password);
+    }
+}
+// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org