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

org.iworkz.habitat.dao.ContextAccess Maven / Gradle / Ivy

There is a newer version: 1.0.30
Show newest version
package org.iworkz.habitat.dao;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.sql.DataSource;


@Singleton
public class ContextAccess {
	
	private final ThreadLocal context = new ThreadLocal() {	
	    @Override 
	    protected Context initialValue() {
	    		return createContext();
	    }
	};
	
	@Inject
	protected DataSourceProvider dataSourceProvider;
	
	public Context getContext() {
		return context.get();
	}
	
	public void startContext() {
		getContext().start();
	}
	
	/**
	 * Start the context with a custom dataSource
	 * @param dataSource
	 */
	public void startContext(DataSource dataSource) {
		Context contextToStart = getContext();
		contextToStart.setDataSource(dataSource);
		contextToStart.start();
	}
	
	public void closeContext() {
		try {
			getContext().close();
		} finally {
			context.remove();
		}
	}
	
	protected Context createContext() {
		return new Context(dataSourceProvider.getDataSource());
	}

//	/**
//	 * Intended to be used in standalone mode when the dataSourceProvider is
//	 * not injected.
//	 * 
//	 * @param dataSource
//	 */
//	protected void setDataSource(final DataSource dataSource) {
//		this.dataSourceProvider = new AbstractDataSourceProvider(null) {
//			@Override
//			protected DataSource createDataSource(Object options) {
//				return dataSource;
//			}
//		};
//	}
//	
	protected DataSource getDataSource() {
		return dataSourceProvider.getDataSource();
	}



}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy