All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.danidemi.jlubricant.embeddable.h2.H2DatabaseWorking Maven / Gradle / Ivy

There is a newer version: 0.0.15
Show newest version
package com.danidemi.jlubricant.embeddable.h2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.danidemi.jlubricant.embeddable.Database;
import com.danidemi.jlubricant.embeddable.ServerStartException;

public class H2DatabaseWorking implements Database {
	
	private static final Logger log = LoggerFactory.getLogger(H2DatabaseWorking.class);
	
	private H2Dbms master;
	
	static{
		try {
			Class.forName( org.h2.Driver.class.getName() );
		} catch (ClassNotFoundException e) {
			new RuntimeException(e);
		}
	}
	
	private H2DatabaseDescription descriptor;
	
	public void setMaster(H2Dbms master) {
		this.master = master;
	}


	public H2DatabaseWorking(H2DatabaseDescription descriptor, H2Dbms h2Ddms) {
		this.descriptor = descriptor;
		this.master = h2Ddms;
	}
	
	public void postStart() throws SQLException {
		
		// During post start phase, we run an actual connection to the database.
		// This will implicitly set username and pwd.
		String jdbcUrl = visit( new UrlVisitor().keepDbOpen() ).jdbcUrl();
		log.info("Post start initialization to {} {} {}", jdbcUrl, getUsername(), getPassword());
		Connection conn = DriverManager.getConnection(jdbcUrl, getUsername(), getPassword());
		conn.prepareStatement("SELECT 1+1").executeQuery();
		conn.close();
				
	}

	private UrlVisitor visit(UrlVisitor v) {
		descriptor.accept( v );
		master.accept( v );
		master.accept( v );
		return v;
	}
	
	public Connection newConnection() throws SQLException {
		Connection conn = DriverManager.
			    getConnection(getUrl(), descriptor.getUsername(), descriptor.getPassword());
		return conn;
		
	}

	public String getName() {
		return descriptor.getDbName();
	}


	@Override
	public String getUrl() {
		return visit( new UrlVisitor().onlyIfDatabaseExists() ).jdbcUrl();
	}


	@Override
	public String getPassword() {
		return descriptor.getPassword();
	}


	@Override
	public String getDriverClassName() {
		return descriptor.getDriverClassName();
	}


	@Override
	public String getUsername() {
		return descriptor.getUsername();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy