@Override public DBI build(Environment environment, PooledDataSourceFactory configuration, ManagedDataSource dataSource, String name) { final DBI dbi = super.build(environment, configuration, dataSource, name); dbi.registerArgumentFactory(new ValueArgumentFactory(configuration.getDriverClass())); dbi.registerArgumentFactory(new OptionArgumentFactory(configuration.getDriverClass())); dbi.registerContainerFactory(new OptionContainerFactory()); // The order of container factories is important, least specific to most specific dbi.registerContainerFactory(new SeqContainerFactory()); dbi.registerContainerFactory(new IndexedSeqContainerFactory()); dbi.registerContainerFactory(new SetContainerFactory()); dbi.registerContainerFactory(new TreeContainerFactory()); dbi.registerContainerFactory(new ListContainerFactory()); dbi.registerContainerFactory(new ArrayContainerFactory()); dbi.registerContainerFactory(new QueueContainerFactory()); dbi.registerContainerFactory(new StreamContainerFactory()); dbi.registerContainerFactory(new VectorContainerFactory()); return dbi; }
/** {@inheritDoc} */ @Override public ManagedDataSource build(MetricRegistry metricRegistry, String name) throws ClassNotFoundException { ManagedDataSource managedDataSource = super.build(metricRegistry, name); if (isLazy) { if (managedDataSource instanceof ManagedPooledDataSource) { /* of course we can't depend on it by method protocol, but right now * (currently used version of dropwizard 0.7.1 as well as last currently available 0.8.1) * exactly this implementation will be returned by super.build(MetricRegistry mr, String name) method */ ManagedPooledDataSource managedPooledDataSource = (ManagedPooledDataSource) managedDataSource; return new LazyManagedPooledDataSource(managedPooledDataSource.getPoolProperties(), metricRegistry); } throw new AssertionError( "You can't use this DataSourceFactory implementation with your dropwizard version"); } else { return managedDataSource; } }
/** * Create an instance of MyBatis. * * @param environment The dropwizard environment * @param config A Mybatis config object * @param dataSource * @param name The name of this mybatis factory used for metrics * @return An instance of MyBatis. */ public final SqlSessionFactory build(Environment environment, MyBatisConfiguration config, ManagedDataSource dataSource, String name) { SqlSessionFactory sessionFactory = null; // Try to use the mybatis configuration file if it is specified and exists. try (InputStream inputStream = Resources.getResourceAsStream(config.getConfigFile())) { sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException ioe) { // Build session factory from configuration values given in the dropwizard config. TransactionFactory transactionFactory = new JdbcTransactionFactory(); org.apache.ibatis.mapping.Environment myBatisEnvironment = new org.apache.ibatis.mapping.Environment(ENV_NAME, transactionFactory, dataSource); Configuration mybatisConfiguration = new Configuration(myBatisEnvironment); sessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfiguration); } environment.lifecycle().manage(dataSource); environment.healthChecks().register(name, new MyBatisHealthCheck(sessionFactory, config.getConfig().getValidationQuery())); return sessionFactory; }
/** * Create an instance of MyBatis. * * @param environment The dropwizard environment * @param configuration The data source factory/configuration * @param dataSource The datasource you want to use. * @param name The name of this mybatis factory used for metrics * @return An instance of MyBatis. */ public final SqlSessionFactory build(Environment environment, DataSourceFactory configuration, ManagedDataSource dataSource, String name) { // Initialize validation query final String validationQuery = configuration.getValidationQuery(); // Build mybatis session factory TransactionFactory transactionFactory = new JdbcTransactionFactory(); org.apache.ibatis.mapping.Environment myBatisEnvironment = new org.apache.ibatis.mapping.Environment(ENV_NAME, transactionFactory, dataSource); Configuration mybatisConfiguration = new Configuration(myBatisEnvironment); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfiguration); // Setup managed data source and health checks environment.lifecycle().manage(dataSource); environment.healthChecks().register(name, new MyBatisHealthCheck(sessionFactory, validationQuery)); return sessionFactory; }
public Jdbi build(Environment environment, PooledDataSourceFactory configuration, String name) { ManagedDataSource dataSource = configuration.build(environment.metrics(), name); String validationQuery = configuration.getValidationQuery(); Jdbi jdbi = Jdbi.create(dataSource); jdbi.setTimingCollector(new InstrumentedTimingCollector(environment.metrics(), nameStrategy)); jdbi.installPlugins(); environment.lifecycle().manage(dataSource); environment.healthChecks().register(name, new JdbiHealthCheck( environment.getHealthCheckExecutorService(), configuration.getValidationQueryTimeout().orElseGet(() -> Duration.seconds(5)), jdbi, validationQuery)); return jdbi; }
public SessionFactory build(final RemoteCredentialHibernateBundle<?> bundle, final Environment environment, final PooledDataSourceFactory dbConfig, final ManagedDataSource dataSource, final List<Class<?>> entities) { final ConnectionProvider provider = this.buildConnectionProvider(dataSource, dbConfig.getProperties()); final SessionFactory factory = this.buildSessionFactory(bundle, dbConfig, provider, dbConfig.getProperties(), entities); final SessionFactoryManager managedFactory = new SessionFactoryManager(factory, dataSource); environment.lifecycle().manage(managedFactory); return factory; }
@Override public void run(ProductCatalogConfiguration configuration, Environment environment) throws Exception { environment.jersey().setUrlPattern("/api/*"); environment.healthChecks().register("product catalog service", guiceBundle.getInjector().getInstance(ProductCatalogServiceHealthCheck.class)); // run the migrations as part of startup and prepare the db with sample // data ManagedDataSource mds = configuration.getDataSourceFactory().build(environment.metrics(), "migrations"); try (Connection connection = mds.getConnection()) { Liquibase migrator = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), new JdbcConnection(connection)); migrator.dropAll(); migrator.clearCheckSums(); migrator.update(""); } }
@Override public void run(final ProductReviewConfiguration configuration, final Environment environment) throws Exception { environment.jersey().setUrlPattern("/api/*"); environment.healthChecks().register("product review service", guiceBundle.getInjector().getInstance(ProductReviewServiceHealthCheck.class)); // run the migrations as part of startup and prepare the db with sample // data ManagedDataSource mds = configuration.getDataSourceFactory().build(environment.metrics(), "migrations"); try (Connection connection = mds.getConnection()) { Liquibase migrator = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), new JdbcConnection(connection)); migrator.dropAll(); migrator.clearCheckSums(); migrator.update(""); } }
@Override public void run(T dwConfiguration, Environment environment) throws Exception { final DataSourceFactory dbConfig = getDataSourceFactory(dwConfiguration); ManagedDataSource dataSource = dbConfig.build(environment.metrics(), "jooq"); this.configuration = new DefaultConfiguration(); this.configuration.set(new DataSourceConnectionProvider(dataSource)); configure(this.configuration); environment.jersey().register(JooqTransactionalApplicationListener.class); environment.jersey().register( new ConfigurationFactoryProvider.Binder(this.configuration, dataSource, multiTenantConnectionProvider)); environment.lifecycle().manage(dataSource); if (multiTenantConnectionProvider != null) { environment.lifecycle().manage(multiTenantConnectionProvider); } environment.healthChecks().register("jooq", new JooqHealthCheck( DSL.using(this.configuration.derive(new DefaultConnectionProvider(dataSource.getConnection()))), dbConfig.getValidationQuery())); }
@Override public DBI build(Environment environment, PooledDataSourceFactory configuration, ManagedDataSource dataSource, String name) { final DBI dbi = super.build(environment, configuration, dataSource, name); dbi.registerArgumentFactory(new OptionalArgumentFactory(configuration.getDriverClass())); dbi.registerContainerFactory(new OptionalContainerFactory()); dbi.registerArgumentFactory(new LocalDateArgumentFactory()); dbi.registerArgumentFactory(new OptionalLocalDateArgumentFactory()); dbi.registerArgumentFactory(new LocalDateTimeArgumentFactory()); dbi.registerArgumentFactory(new OptionalLocalDateTimeArgumentFactory()); dbi.registerMapper(new LocalDateMapper()); dbi.registerMapper(new LocalDateTimeMapper()); final Optional<TimeZone> tz = Optional.ofNullable(databaseTimeZone().orNull()); dbi.registerArgumentFactory(new InstantArgumentFactory(tz)); dbi.registerArgumentFactory(new OptionalInstantArgumentFactory(tz)); dbi.registerMapper(new InstantMapper(tz)); return dbi; }
@Override public ManagedDataSource build(final MetricRegistry metricRegistry, final String name) { final Properties properties = new Properties(); for (final Map.Entry<String, String> property : this.properties.entrySet()) { properties.setProperty(property.getKey(), property.getValue()); } final HikariConfig config = new HikariConfig(); config.setMetricRegistry(metricRegistry); if (healthCheckRegistry != null) { config.setHealthCheckRegistry(healthCheckRegistry); } config.setAutoCommit(autoCommit); config.setDataSourceProperties(properties); if (datasourceClassName != null) { config.setDataSourceClassName(datasourceClassName); } else { config.setDriverClassName(driverClass); } config.setMaximumPoolSize(maxSize); minSize.ifPresent(config::setMinimumIdle); config.setPoolName(name); config.setUsername(user); config.setPassword(user != null && password == null ? "" : password); return new HikariManagedPooledDataSource(config); }
private EventStore buildJdbcEventStore(EventPublisher publisher, Environment environment) { ManagedDataSource ds = database.build(environment.metrics(), "eventstore"); DBI jdbi = new DBIFactory().build(environment, database, "eventstore"); updateDatabaseSchema(ds); EventStore eventStore = new JdbcEventStore(jdbi, environment.getObjectMapper(), publisher); return eventStore; }
public SessionFactory build(final RemoteCredentialHibernateBundle<?> bundle, final Environment environment, final PooledDataSourceFactory dbConfig, final List<Class<?>> entities, final String name) { final ManagedDataSource dataSource = dbConfig.build(environment.metrics(), name); return this.build(bundle, environment, dbConfig, dataSource, entities); }
@Provides @Singleton @Readonly ManagedDataSource readonlyDataSource(Environment environment, KeywhizConfig config) { DataSourceFactory dataSourceFactory = config.getReadonlyDataSourceFactory(); ManagedDataSource dataSource = dataSourceFactory.build(environment.metrics(), "db-readonly"); environment.lifecycle().manage(dataSource); environment.healthChecks().register("db-readonly-health", new JooqHealthCheck(dataSource, RETURN_UNHEALTHY)); return dataSource; }
@Provides @Singleton @Readonly DSLContext readonlyJooqContext(@Readonly ManagedDataSource dataSource) throws SQLException { DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource); org.jooq.Configuration configuration = dslContext.configuration(); // Disable support for nested transactions via savepoints (required for MySQL) // See: https://groups.google.com/forum/#!topic/jooq-user/zG0U6CkxI5o configuration.set(new DefaultTransactionProvider(configuration.connectionProvider(), false)); return dslContext; }
@Override public Connection acquire(String tenantIdentifier) { ManagedDataSource dataSource = dataSources.get(tenantIdentifier); if (dataSource == null) { dataSourceFactory.setUrl(url); dataSource = dataSourceFactory.build(metricRegistry, "dataSource-" + tenantIdentifier); dataSources.put(tenantIdentifier, dataSource); } try { return dataSource.getConnection(); } catch (SQLException e) { throw new DataAccessException("An error occurred while getting a connection.", e); } }
EntityManagerFactory build(EntityManagerBundle<?> bundle, Environment environment, PooledDataSourceFactory dbConfig, List<Class<?>> entities, String name) { final ManagedDataSource dataSource = dbConfig.build(environment.metrics(), name); return build(bundle, environment, dbConfig, dataSource, entities); }
EntityManagerFactory build(EntityManagerBundle<?> bundle, Environment environment, PooledDataSourceFactory dbConfig, ManagedDataSource dataSource, List<Class<?>> entities) { final EntityManagerFactory factory = buildSessionFactory(bundle, dbConfig, dataSource, dbConfig.getProperties(), entities); final EntityManagerFactoryManager managedFactory = new EntityManagerFactoryManager(factory, dataSource); environment.lifecycle().manage(managedFactory); return factory; }
private EntityManagerFactory buildSessionFactory(EntityManagerBundle<?> bundle, PooledDataSourceFactory dbConfig, ManagedDataSource dataSource, Map<String, String> properties, List<Class<?>> entities) { PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl(bundle.name(), dataSource); persistenceUnitInfo.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed"); persistenceUnitInfo.setProperty(AvailableSettings.USE_SQL_COMMENTS, Boolean.toString(dbConfig.isAutoCommentsEnabled())); persistenceUnitInfo.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true"); persistenceUnitInfo.setProperty(AvailableSettings.GENERATE_STATISTICS, "true"); persistenceUnitInfo.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true"); persistenceUnitInfo.setProperty(AvailableSettings.ORDER_UPDATES, "true"); persistenceUnitInfo.setProperty(AvailableSettings.ORDER_INSERTS, "true"); persistenceUnitInfo.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); persistenceUnitInfo.setProperty("jadira.usertype.autoRegisterUserTypes", "true"); for (Map.Entry<String, String> property : properties.entrySet()) { persistenceUnitInfo.setProperty(property.getKey(), property.getValue()); } addAnnotatedClasses(persistenceUnitInfo, entities); bundle.configure(persistenceUnitInfo); configure(persistenceUnitInfo); return new HibernatePersistenceProvider().createContainerEntityManagerFactory(persistenceUnitInfo, null); }
@Override public void start() throws Exception { LOGGER.info("begin migration"); final ManagedDataSource dataSource = dataSourceFactory.build(new MetricRegistry(), "liquibase"); try(CloseableLiquibase liquibase = new CloseableLiquibaseWithClassPathMigrationsFile(dataSource, "migrations.xml")) { liquibase.update("migrations"); } LOGGER.info("finish migration"); }
public RestWarsModule(UniverseConfiguration universeConfiguration, ManagedDataSource managedDataSource, int passwordIterations, CacheBuilderSpec credentialsCache, MetricRegistry metricRegistry, String securityRealm) { this.securityRealm = Preconditions.checkNotNull(securityRealm, "securityRealm"); this.metricRegistry = Preconditions.checkNotNull(metricRegistry, "metricRegistry"); this.credentialsCache = Preconditions.checkNotNull(credentialsCache, "credentialsCache"); this.managedDataSource = Preconditions.checkNotNull(managedDataSource, "managedDataSource"); this.universeConfiguration = Preconditions.checkNotNull(universeConfiguration, "universeConfiguration"); this.passwordIterations = passwordIterations; }
public Configuration build(Environment environment, PooledDataSourceFactory factory, String name) throws ClassNotFoundException { final Settings settings = buildSettings(); final ManagedDataSource dataSource = factory.build(environment.metrics(), name); final SQLDialect dialect = determineDialect(factory, dataSource); final ConnectionProvider connectionProvider = new DataSourceConnectionProvider(dataSource); final Configuration config = new DefaultConfiguration() .set(settings) .set(dialect) .set(connectionProvider); environment.lifecycle().manage(dataSource); return config; }
private SQLDialect determineDialect(PooledDataSourceFactory dataSourceFactory, ManagedDataSource dataSource) { // If a dialect was specified, great! if (getDialect().isPresent()) { return dialect.get(); } return JDBCUtils.dialect(dataSourceFactory.getUrl()); }
CloseableLiquibase openLiquibase(DataSourceFactory dataSourceFactory, Namespace namespace) throws ClassNotFoundException, SQLException, LiquibaseException { final ManagedDataSource dataSource = dataSourceFactory.build(new MetricRegistry(), "liquibase"); final String migrationsFile = (String) namespace.get("migrations-file"); if (migrationsFile == null) { return new CloseableLiquibase(dataSource); } LOGGER.warn("Open Liquibase with migrations-file: {}", migrationsFile ); return new CloseableLiquibase(dataSource, migrationsFile); }
public SessionFactoryManager(final SessionFactory factory, final ManagedDataSource dataSource) { this.factory = factory; this.dataSource = dataSource; }
@VisibleForTesting ManagedDataSource getDataSource() { return this.dataSource; }
public ManagedDataSource getDataSource() { return dataSource; }
@Override public ManagedDataSource build(MetricRegistry metricRegistry, String name) { setPassword(getPassword()); return super.build(metricRegistry, name); }
@Provides @Singleton DSLContext jooqContext(ManagedDataSource dataSource) throws SQLException { return DSLContexts.databaseAgnostic(dataSource); }
@Override public void stop() throws Exception { for (ManagedDataSource managedDataSource : dataSources.values()) { managedDataSource.stop(); } }
@Test public void managesDataSource() throws Exception { bundle.run(configuration, environment); verify(lifecycleEnvironment).manage(any(ManagedDataSource.class)); }
EntityManagerFactoryManager(EntityManagerFactory factory, ManagedDataSource dataSource) { this.factory = factory; this.dataSource = dataSource; }
@VisibleForTesting ManagedDataSource getDataSource() { return dataSource; }
@Override public void run(RestwarsConfiguration configuration, Environment environment) throws Exception { // Write datetimes as ISO8601 environment.getObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Start connection pool ManagedDataSource dataSource = configuration.getDatabase().build(environment.metrics(), "datasource"); environment.lifecycle().manage(dataSource); DebugOptions debugOptions = configuration.getDebugOptions(); UniverseConfiguration universeConfiguration = new UniverseConfiguration( configuration.getGalaxies(), configuration.getSolarSystems(), configuration.getPlanets(), new Resources(1000L, 200L, 200L), configuration.getRoundTime(), debugOptions.isSpeedUpFlights(), debugOptions.isSpeedUpResearches(), debugOptions.isSpeedUpBuildingConstructions(), debugOptions.isSpeedUpShipConstructions(), debugOptions.isFreeShips(), debugOptions.isFreeResearches(), debugOptions.isFreeBuildings(), debugOptions.isFreeFlights(), debugOptions.isNoBuildingPrerequisites(), debugOptions.isNoShipPrerequisites(), debugOptions.isNoResearchPrerequisites(), configuration.getCalculatePointsEvery() ); ObjectGraph objectGraph = ObjectGraph.create(new RestWarsModule(universeConfiguration, dataSource, configuration.getPasswordIterations(), CacheBuilderSpec.parse(configuration.getPasswordCache()), environment.metrics(), REALM)); CompositionRoot compositionRoot = objectGraph.get(CompositionRoot.class); registerJerseyHooks(environment, compositionRoot); environment.jersey().register(compositionRoot.getBasicAuthProvider()); environment.jersey().register(compositionRoot.getRootResource()); environment.jersey().register(compositionRoot.getSystemResource()); environment.jersey().register(compositionRoot.getPlayerResource()); environment.jersey().register(compositionRoot.getPlanetResource()); environment.jersey().register(compositionRoot.getTechnologyResource()); environment.jersey().register(compositionRoot.getEventResource()); environment.jersey().register(compositionRoot.getFightResource()); environment.jersey().register(compositionRoot.getFlightResource()); environment.jersey().register(compositionRoot.getMetadataResource()); // Initialize swagger documentation registerSwagger(environment, configuration); registerCorsFilter(environment); Clock clock = compositionRoot.getClock(); registerAtmosphere(environment, clock); environment.lifecycle().manage(clock); }
@BeforeMethod public void setUp() throws Exception { managedDataSource = mock(ManagedDataSource.class); jooqUnitOfWorkFactory = mock(JooqUnitOfWorkFactory.class); sut = new JooqUnitOfWorkService(managedDataSource, jooqUnitOfWorkFactory); }
@Bean(name = "jdbcTemplate") public JdbcTemplate getJdbcTemplate(ManagedDataSource dataSource) { return new JdbcTemplate(dataSource); }
@Bean(name = "namedParameterJdbcTemplate") public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(ManagedDataSource dataSource) { return new NamedParameterJdbcTemplate(dataSource); }
@Bean(name = "txManager") public PlatformTransactionManager txManager(ManagedDataSource dataSource) { return new DataSourceTransactionManager(dataSource); }
private static CloseableLiquibase createLiquibase(DataSourceFactory dbConfig) throws SQLException, LiquibaseException { ManagedDataSource dataSource = dbConfig.build(new MetricRegistry(), "liquibase"); return new CloseableLiquibase(dataSource); }
/** * Create an instance of MyBatis. * * @param environment The dropwizard environment * @param config A Mybatis config object * @param name The name of this mybatis factory used for metrics * @return An instance of MyBatis. * @throws ClassNotFoundException */ public final SqlSessionFactory build(Environment environment, MyBatisConfiguration config, String name) throws ClassNotFoundException { final ManagedDataSource dataSource = config.getConfig().build(environment.metrics(), name); return build(environment, config, dataSource, name); }