view artifact-database/src/main/java/de/intevation/artifactdatabase/DBConnection.java @ 24:d5dc2900392f

* Added callback parameter to Artifact.setup() * New namespace context for artifacts. artifacts/trunk@58 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 10 Sep 2009 08:57:09 +0000
parents 1259d192e3c3
children 93edc04f3a10
line wrap: on
line source
package de.intevation.artifactdatabase;

import javax.sql.DataSource;

import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

import java.io.File;

/**
 *  @author Sascha L. Teichmann
 */
public class DBConnection
{
    public static final String DB_DRIVER =
        "/artifacts-database/database/driver/text()";
    public static final String DB_URL =
        "/artifacts-database/database/url/text()";
    public static final String DB_USER =
        "/artifacts-database/database/user/text()";
    public static final String DB_PASSWORD =
        "/artifacts-database/database/password/text()";

    public static final String DEFAULT_DRIVER =
        "org.h2.Driver";

    public static final String DEFAULT_DATABASE_FILE =
        "artifacts.db";

    public static final String DEFAULT_URL = getDefaultURL();

    public static final String DEFAULT_USER     = "";
    public static final String DEFAULT_PASSWORD = "";

    private DBConnection() {
    }

    public static final String getDefaultURL() {
        File configDir = Config.getConfigDirectory();
        File databaseFile = new File(configDir, DEFAULT_DATABASE_FILE);
        return "jdbc:h2:" + databaseFile;
    }

    private static BasicDataSource dataSource;

    private static final void addShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (dataSource != null) {
                    try {
                        dataSource.close();
                    }
                    catch (SQLException sqle) {
                    }
                    dataSource = null;
                }
            }
        });
    }

    public static synchronized DataSource getDataSource() {
        if (dataSource == null) {
            dataSource = new BasicDataSource();

            String driver = Config.getStringXPath(
                DB_DRIVER, DEFAULT_DRIVER);

            String url = Config.getStringXPath(
                DB_URL, DEFAULT_URL);

            String user = Config.getStringXPath(
                DB_USER, DEFAULT_USER);

            String password = Config.getStringXPath(
                DB_PASSWORD, DEFAULT_PASSWORD);

            dataSource.setDriverClassName(driver);
            dataSource.setUsername(user);
            dataSource.setPassword(password);
            dataSource.setUrl(url);
            addShutdownHook();
        }

        return dataSource;
    }
}
//  vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

http://dive4elements.wald.intevation.org