use of javax.sql.DataSource in project archaius by Netflix.
the class JDBCConfigurationSourceTest method testSimpleInMemoryJDBCDynamicPropertySource.
@Test
public void testSimpleInMemoryJDBCDynamicPropertySource() throws Throwable {
final String dbName = "MySiteConfiguration";
DataSource ds = createDataConfigSource(dbName);
try {
JDBCConfigurationSource source = new JDBCConfigurationSource(ds, "select distinct property_key, property_value from MySiteProperties", "property_key", "property_value");
FixedDelayPollingScheduler scheduler = new FixedDelayPollingScheduler(0, 10, false);
DynamicConfiguration configuration = new DynamicConfiguration(source, scheduler);
DynamicPropertyFactory.initWithConfigurationSource(configuration);
DynamicStringProperty defaultProp = DynamicPropertyFactory.getInstance().getStringProperty("this.prop.does.not.exist.use.default", "default");
assertEquals("default", defaultProp.get());
DynamicStringProperty prop1 = DynamicPropertyFactory.getInstance().getStringProperty("prop1", "default");
assertEquals("value1", prop1.get());
} finally {
//Clean up the data files generated by the embedded DB.
FileUtils.deleteDirectory(new File(".", dbName));
}
}
use of javax.sql.DataSource in project qi4j-sdk by Qi4j.
the class SQLTestHelper method setUpTest.
public static void setUpTest(Module module) {
Connection connection = null;
try {
DataSource ds = module.findService(DataSource.class).get();
connection = ds.getConnection();
Assume.assumeNotNull(connection);
} catch (Throwable t) {
t.printStackTrace();
Assume.assumeNoException(t);
} finally {
SQLUtil.closeQuietly(connection);
}
}
use of javax.sql.DataSource in project qi4j-sdk by Qi4j.
the class LiquibaseServiceTest method testLiquibase.
@Test
public void testLiquibase() throws SQLException, IOException, ActivationException, AssemblyException {
final SingletonAssembler assembler = new SingletonAssembler() {
@Override
public void assemble(ModuleAssembly module) throws AssemblyException {
ModuleAssembly configModule = module;
// Create in-memory store for configurations
new EntityTestAssembler().assemble(configModule);
new C3P0DataSourceServiceAssembler().identifiedBy("datasource-service").withConfig(configModule, Visibility.layer).assemble(module);
new DataSourceAssembler().withDataSourceServiceIdentity("datasource-service").identifiedBy("testds-liquibase").withCircuitBreaker().assemble(module);
module.values(SomeValue.class);
// Set up Liquibase service that will create the tables
// START SNIPPET: assembly
new LiquibaseAssembler().withConfig(configModule, Visibility.layer).assemble(module);
// END SNIPPET: assembly
module.forMixin(LiquibaseConfiguration.class).declareDefaults().enabled().set(true);
module.forMixin(LiquibaseConfiguration.class).declareDefaults().changeLog().set("changelog.xml");
}
@Override
public void beforeActivation(Application application) {
application.registerActivationEventListener(new ActivationEventListener() {
@Override
public void onEvent(ActivationEvent event) {
System.out.println(event);
}
});
}
};
Module module = assembler.module();
// START SNIPPET: io
// Look up the DataSource
DataSource ds = module.findService(DataSource.class).get();
// Instanciate Databases helper
Databases database = new Databases(ds);
// Assert that insertion works
assertTrue(database.update("insert into test values ('someid', 'bar')") == 1);
// END SNIPPET: io
database.query("select * from test", new Databases.ResultSetVisitor() {
@Override
public boolean visit(ResultSet visited) throws SQLException {
assertThat(visited.getString("id"), equalTo("someid"));
assertThat(visited.getString("foo"), equalTo("bar"));
return true;
}
});
Function<ResultSet, SomeValue> toValue = new Function<ResultSet, SomeValue>() {
@Override
public SomeValue map(ResultSet resultSet) {
ValueBuilder<SomeValue> builder = assembler.module().newValueBuilder(SomeValue.class);
try {
builder.prototype().id().set(resultSet.getString("id"));
builder.prototype().foo().set(resultSet.getString("foo"));
} catch (SQLException e) {
throw new IllegalArgumentException("Could not convert to SomeValue", e);
}
return builder.newInstance();
}
};
// START SNIPPET: io
// Select rows and load them in a List
List<SomeValue> rows = new ArrayList<SomeValue>();
database.query("select * from test").transferTo(map(toValue, collection(rows)));
// Transfer all rows to System.out
Inputs.iterable(rows).transferTo(Outputs.systemOut());
// END SNIPPET: io
}
use of javax.sql.DataSource in project qi4j-sdk by Qi4j.
the class AbstractDataSourceServiceImporterMixin method importService.
@Override
public final synchronized DataSource importService(final ImportedServiceDescriptor importedServiceDescriptor) throws ServiceImporterException {
PooledDataSourceType pool = pools.get(importedServiceDescriptor.identity());
if (pool == null) {
try {
DataSourceConfigurationValue config = getConfiguration(importedServiceDescriptor.identity());
if (!config.enabled().get()) {
// Not started
throw new ServiceImporterException("DataSource not enabled");
}
// Instantiate pool
pool = setupDataSourcePool(config);
pools.put(importedServiceDescriptor.identity(), pool);
LOGGER.info("Starting up DataSource '" + importedServiceDescriptor.identity() + "' for: {}@{}", config.username().get(), config.url().get());
} catch (Exception e) {
throw new ServiceImporterException(e);
}
// Test the pool
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(null);
try {
pool.getConnection().close();
LOGGER.info("Database for DataSource is up!");
} catch (SQLException e) {
LOGGER.warn("Database for DataSource " + importedServiceDescriptor.identity() + " is not currently available");
throw new ServiceImporterException("Database for DataSource " + importedServiceDescriptor.identity() + " is not currently available", e);
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
// Check if circuitbreaker is used
final CircuitBreaker circuitBreaker = importedServiceDescriptor.metaInfo(CircuitBreaker.class);
if (circuitBreaker != null) {
DataSource wrappedDataSource = DataSources.wrapWithCircuitBreaker(importedServiceDescriptor.identity(), pool, circuitBreaker);
circuitBreakers.put(pool, circuitBreaker);
return wrappedDataSource;
} else {
return pool;
}
}
use of javax.sql.DataSource in project qi4j-sdk by Qi4j.
the class DataSources method wrapWithCircuitBreaker.
public static DataSource wrapWithCircuitBreaker(final String dataSourceIdentity, final DataSource pool, final CircuitBreaker circuitBreaker) {
// Create wrapper
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!circuitBreaker.isOn()) {
Throwable throwable = circuitBreaker.lastThrowable();
if (throwable != null) {
throw throwable;
} else {
throw new ServiceImporterException("Circuit breaker for DataSource " + dataSourceIdentity + " is not on");
}
}
try {
Object result = method.invoke(pool, args);
circuitBreaker.success();
return result;
} catch (IllegalAccessException e) {
circuitBreaker.throwable(e);
throw e;
} catch (IllegalArgumentException e) {
circuitBreaker.throwable(e);
throw e;
} catch (InvocationTargetException e) {
circuitBreaker.throwable(e.getCause());
throw e.getCause();
}
}
};
// Create proxy with circuit breaker
return (DataSource) Proxy.newProxyInstance(DataSource.class.getClassLoader(), new Class[] { DataSource.class }, handler);
}
Aggregations