db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Apache Wiki <wikidi...@apache.org>
Subject [Db-derby Wiki] Update of "DatabaseManagerSource" by DonaldMcLean
Date Fri, 28 Apr 2006 20:37:25 GMT
Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Db-derby Wiki" for change notification.

The following page has been changed by DonaldMcLean:
http://wiki.apache.org/db-derby/DatabaseManagerSource

New page:
## Please edit system and help pages ONLY in the moinmaster wiki! For more
## information, please see MoinMaster:MoinPagesEditorGroup.
##master-page:Unknown-Page
##master-date:Unknown-Date
##acl MoinPagesEditorGroup:read,write,delete,revert All:read
#format wiki
#language en
== Template for Help Pages ==
{{{
package your.package.here;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.jdom.Document;
import org.jdom.Element;

import java.sql.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import java.io.File;
import java.io.IOException;

import java.util.HashSet;
import java.util.List;
import java.util.Properties;

/**
 * Created:
 * Date: Sep 5, 2005
 * Time: 1:57:13 AM
 */
public class DatabaseManager
{
    public DatabaseManager(File dbFile)
    {
        connectToDatabase(dbFile);

        Document document = BotUtilities.getXMLResource(getClass());
        Element root = document.getRootElement();

        if (createFlag)
        {
            createTables(root);
        }
        createHibernateSessionFactory(root);

        instance = this;
    }

    public static DatabaseManager getInstance()
    {
        return instance;
    }

    public Connection getConnection()
    {
        return connection;
    }

    public Session getMainSession()
    {
        if (mainSession == null)
        {
            mainSession = (Session)sessions.openSession(connection);
        }

        return mainSession;
    }

    public void close()
    {
        sessions.close();
        try
        {
            connection.close();
        }
        catch (SQLException e)
        {
            System.out.println("[DatabaseManager.close] Unable to close connection.");
        }
    }

    private Connection connection;
    private SessionFactory sessions;
    private Session mainSession = null;
    private boolean createFlag = false;

    private void createTables(Element root)
    {
        Element createElement = root.getChild("createSql");
        List createElements = createElement.getChildren();

        String sql = null;
        try
        {
            Statement statement = connection.createStatement();
            for (int i = 0; i < createElements.size(); i++)
            {
                Element element = (Element) createElements.get(i);
                sql = element.getText();
                statement.execute(sql);
            }
        }
        catch (SQLException e)
        {
            System.out.println("[DatabaseManager.createTables] Failed to execute: '" +
                               sql + "'.");
            e.printStackTrace();
        }
    }

    private void connectToDatabase(File dbFile)
    {
        try
        {
            String url = createURL(dbFile);
            connection = driver.connect(url, null);
        }
        catch (Exception e)
        {
            System.out.println("[ApplicationDatabase : ApplicationDatabase]:" +
                               " unable to create database.");
            e.printStackTrace();
        }
    }

    /**
     * @param dbFile
     * @throws IOException
     */
    private String createURL(File dbFile)
            throws IOException
    {
        String dbURL = "jdbc:derby:" + dbFile.getCanonicalPath();
        if (!dbFile.exists())
        {
            createFlag = true;
            dbURL += ";create=true";
        }

        System.out.println("[ApplicationDatabase.createURL] URL is '" + dbURL + "'.cn");
        return dbURL;
    }

    private void createHibernateSessionFactory(Element root)
    {
        HashSet<Class> classes = collectFeatureClasses(root);

        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
        properties.put("hibernate.show_sql", "true");

        Configuration cfg = new Configuration();
        cfg.addProperties(properties);

        for(Class aClass : classes)
        {
            System.out.println("[ApplicationDatabase.createHibernateSessionFactory]" +
                               " adding class '" + aClass.getName() + "'.");
            cfg.addClass(aClass);
        }

        sessions = cfg.buildSessionFactory();
    }

    private HashSet<Class> collectFeatureClasses(Element root)
    {
        HashSet<Class> result = new HashSet<Class>();

        Element classesElement = root.getChild("Classes");
        List classElements = classesElement.getChildren();

        for (int i = 0; i < classElements.size(); i++)
        {
            Element element = (Element) classElements.get(i);
            result.add(BotUtilities.loadClass(element.getText()));
        }

        return result;
    }

    static private Driver driver;
    static private DatabaseManager instance = null;

    static
    {
        try
        {
            driver = (Driver) Class.forName("org.apache.derby.jdbc.EmbeddedDriver")
                         .newInstance();
            System.out.println("[ApplicationDatabase : static]: driver loaded successfuly.");
        }
        catch (Exception e)
        {
            System.out.println("[ApplicationDatabase : static]: unable to load driver.");
            e.printStackTrace();
        }
    }
}

}}}

Mime
View raw message