Java 类io.dropwizard.db.DataSourceFactory 实例源码

项目:dropwizard-vavr    文件:VavrDBIFactoryTest.java   
@Before
public void setupTests() throws IOException {
    final DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setDriverClass("org.h2.Driver");
    dataSourceFactory.setUrl("jdbc:h2:mem:test-" + System.currentTimeMillis() + "?user=sa");
    dataSourceFactory.setInitialSize(1);
    final DBI dbi = new VavrDBIFactory().build(env, dataSourceFactory, "test");
    try (Handle h = dbi.open()) {
        h.execute("CREATE TABLE tasks (" +
                "id INT PRIMARY KEY, " +
                "assignee VARCHAR(255) NOT NULL, " +
                "start_date TIMESTAMP, " +
                "end_date TIMESTAMP, " +
                "comments VARCHAR(1024) " +
                ")");
    }
    dao = dbi.onDemand(TaskDao.class);

    dao.insert(100, Option.some("Name 1"), LocalDate.parse("2017-08-24"), Option.none(), Option.none());
    dao.insert(200, Option.some("Name 2"), LocalDate.parse("2017-08-25"), Option.none(), Option.some("To be done"));
}
项目:jdbishard    文件:JDBIManager.java   
/**
 * @param shardService Your shard service.
 * @param shardRegistry Your shard registry.
 * @param dbiRegistry Your DBI registry.
 * @param daoRegistry Your DAO registry.
 * @param dropwizardDbiFactory Your dropwizard application's DBI Factory.
 * @param dropwizardEnvironment Your dropwizard application's environment.
 * @param dropwizardDSFactory Your dropwizard application's datasource factory.
 * @param DBIInitializer We call your initializer immediately after dropwizardDbiFactory builds your
 *                        DBI. @see jdbishard.jdbi.NoOpDBIInitializer.
 * @param humanFriendlyShardNamer We register metrics for each shard connection given the human
 *                                friendly name. @see jdbishard.sharding.IdOnlyShardNamer.
 */
@Inject
public JDBIManager(
        ShardService<ShardIdT, KeyT> shardService,
        ShardRegistry<ShardIdT, KeyT> shardRegistry,
        DBIRegistry<ShardIdT> dbiRegistry,
        DAORegistry<ShardIdT> daoRegistry,
        DBIFactory dropwizardDbiFactory,
        Environment dropwizardEnvironment,
        DataSourceFactory dropwizardDSFactory,
        DBIInitializer DBIInitializer,
        HumanFriendlyShardNamer humanFriendlyShardNamer)
{
    this.shardService = shardService;
    this.shardRegistry = shardRegistry;
    this.dbiRegistry = dbiRegistry;
    this.daoRegistry = daoRegistry;
    this.dropwizardDbiFactory = dropwizardDbiFactory;
    this.dropwizardEnvironment = dropwizardEnvironment;
    this.dropwizardDSFactory = dropwizardDSFactory;
    this.DBIInitializer = DBIInitializer;
    this.humanFriendlyShardNamer = humanFriendlyShardNamer;
}
项目:dropwizard-mybatis    文件:MyBatisFactory.java   
/**
 * 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;
}
项目:dropwizard-jdbi3    文件:JdbiTest.java   
@Before
public void setUp() throws Exception {
    environment = new Environment("test", new ObjectMapper(), Validators.newValidator(),
            metricRegistry, ClassLoader.getSystemClassLoader());

    DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setUrl("jdbc:h2:mem:jdbi3-test");
    dataSourceFactory.setUser("sa");
    dataSourceFactory.setDriverClass("org.h2.Driver");
    dataSourceFactory.asSingleConnectionPool();

    dbi = new JdbiFactory(new TimedAnnotationNameStrategy()).build(environment, dataSourceFactory, "h2");
    dbi.useTransaction(h -> {
        h.createScript(Resources.toString(Resources.getResource("schema.sql"), Charsets.UTF_8)).execute();
        h.createScript(Resources.toString(Resources.getResource("data.sql"), Charsets.UTF_8)).execute();
    });
    dao = dbi.onDemand(GameDao.class);
    for (LifeCycle lc : environment.lifecycle().getManagedObjects()) {
        lc.start();
    }
}
项目:pay-adminusers    文件:AdminUsersApp.java   
@Override
public void initialize(Bootstrap<AdminUsersConfig> bootstrap) {
    bootstrap.setConfigurationSourceProvider(
            new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
                    new EnvironmentVariableSubstitutor(NON_STRICT_VARIABLE_SUBSTITUTOR)
            )
    );

    bootstrap.addBundle(new MigrationsBundle<AdminUsersConfig>() {
        @Override
        public DataSourceFactory getDataSourceFactory(AdminUsersConfig configuration) {
            return configuration.getDataSourceFactory();
        }
    });

    bootstrap.addCommand(new DependentResourceWaitCommand());
    bootstrap.addCommand(new MigrateToInitialDbState());
}
项目:pay-adminusers    文件:DropwizardAppWithPostgresRule.java   
@Override
public Statement apply(Statement base, Description description) {
    return rules.apply(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            logger.info("Clearing database.");
            app.getApplication().run("db", "drop-all", "--confirm-delete-everything", configFilePath);
            app.getApplication().run("migrateToInitialDbState", configFilePath);
            doSecondaryDatabaseMigration();
            restoreDropwizardsLogging();

            DataSourceFactory dataSourceFactory = app.getConfiguration().getDataSourceFactory();
            databaseTestHelper = new DatabaseTestHelper(new DBI(dataSourceFactory.getUrl(), dataSourceFactory.getUser(), dataSourceFactory.getPassword()));

            base.evaluate();
        }
    }, description);
}
项目:CredentialStorageService-dw-hibernate    文件:HibernateBundleTest.java   
@Test
@SuppressWarnings("unchecked")
public void registersACustomNameOfHealthCheckAndDBPoolMetrics() throws Exception {
    final HibernateBundle<Configuration> customBundle = new HibernateBundle<Configuration>(entities, factory) {
        @Override
        public DataSourceFactory getDataSourceFactory(Configuration configuration) {
            return dbConfig;
        }

        @Override
        protected String name() {
            return "custom-hibernate";
        }
    };
    when(factory.build(eq(customBundle),
            any(Environment.class),
            any(DataSourceFactory.class),
            anyList(),
            eq("custom-hibernate"))).thenReturn(sessionFactory);

    customBundle.run(configuration, environment);

    final ArgumentCaptor<SessionFactoryHealthCheck> captor =
            ArgumentCaptor.forClass(SessionFactoryHealthCheck.class);
    verify(healthChecks).register(eq("custom-hibernate"), captor.capture());
}
项目:cassandra-reaper    文件:ReaperApplication.java   
private void initDatabase(ReaperApplicationConfiguration config) throws ReaperException {
  Flyway flyway = new Flyway();
  DataSourceFactory dsfactory = config.getDataSourceFactory();
  flyway.setDataSource(
      dsfactory.getUrl(),
      dsfactory.getUser(),
      dsfactory.getPassword());

  if ("database".equals(config.getStorageType())) {
    LOG.warn("!!!!!!!!!!    USAGE 'database' AS STORAGE TYPE IS NOW DEPRECATED   !!!!!!!!!!!!!!");
    LOG.warn("!!!!!!!!!!    PLEASE USE EITHER 'postgres' OR 'h2' FROM NOW ON     !!!!!!!!!!!!!!");
    if (config.getDataSourceFactory().getUrl().contains("h2")) {
      flyway.setLocations("/db/h2");
    } else {
      flyway.setLocations("/db/postgres");
    }
  } else {
    flyway.setLocations("/db/".concat(config.getStorageType().toLowerCase()));
  }
  flyway.setBaselineOnMigrate(true);
  flyway.repair();
  flyway.migrate();
}
项目:cassandra-reaper    文件:ReaperApplicationConfigurationTest.java   
@Before
public void setUp() {
  //create a valid config
  DataSourceFactory dataSourceFactory = new DataSourceFactory();
  dataSourceFactory.setDriverClass("org.postgresql.Driver");
  dataSourceFactory.setUrl("jdbc:postgresql://db.example.com/db-prod");
  dataSourceFactory.setUser("user");
  CassandraFactory cassandraFactory = new CassandraFactory();
  cassandraFactory.setContactPoints(new String[]{"127.0.0.1"});
  config.setCassandraFactory(cassandraFactory);
  config.setPostgresDataSourceFactory(dataSourceFactory);
  config.setHangingRepairTimeoutMins(1);
  config.setRepairParallelism(RepairParallelism.DATACENTER_AWARE);
  config.setRepairRunThreadCount(1);
  config.setSegmentCount(1);
  config.setScheduleDaysBetween(7);
  config.setStorageType("foo");
  config.setIncrementalRepair(false);
}
项目:pay-publicauth    文件:PublicAuthApp.java   
@Override
public void initialize(Bootstrap<PublicAuthConfiguration> bootstrap) {
    bootstrap.setConfigurationSourceProvider(
            new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
                    new EnvironmentVariableSubstitutor(false)
            )
    );

    bootstrap.addBundle(new DBIExceptionsBundle());

    bootstrap.addBundle(new MigrationsBundle<PublicAuthConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(PublicAuthConfiguration configuration) {
            return configuration.getDataSourceFactory();
        }
    });

    bootstrap.addCommand(new DependentResourceWaitCommand());
}
项目:pay-publicauth    文件:PublicAuthApp.java   
@Override
public void run(PublicAuthConfiguration conf, Environment environment) throws Exception {
    DataSourceFactory dataSourceFactory = conf.getDataSourceFactory();

    jdbi = new DBIFactory().build(environment, dataSourceFactory, "postgresql");
    initialiseMetrics(conf, environment);

    TokenService tokenService = new TokenService(conf.getTokensConfiguration());

    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<Token>()
                    .setAuthenticator(new TokenAuthenticator(tokenService))
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Token.class));

    environment.jersey().register(new PublicAuthResource(new AuthTokenDao(jdbi), tokenService));
    environment.jersey().register(new HealthCheckResource(environment));
    environment.jersey().register(new ValidationExceptionMapper());
    environment.jersey().register(new TokenNotFoundExceptionMapper());
    environment.healthChecks().register("database", new DatabaseHealthCheck(conf,environment));

    environment.servlets().addFilter("LoggingFilter", new LoggingFilter())
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1" + "/*");
}
项目:authrite    文件:AuthriteServiceApplication.java   
@Override
public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
    bootstrap.addBundle(new Java8Bundle());

    if (useClasspathAssets) {
        bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
    } else {
        bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
    }

    bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
            return configuration.getDatabase();
        }
    });
}
项目:AugumentedSzczecin_java    文件:AugmentedConfiguration.java   
@JsonCreator
public AugmentedConfiguration(@JsonProperty(value = "dbtype") final DbType dbtype,
                              @JsonProperty(value = "mongodb", required = false) final MongodbConfiguration mongodbConfig,
                              @JsonProperty(value = "rdbms", required = false) final DataSourceFactory rdbmsConfig,
                              @JsonProperty(value = "authCacheSpec", required = false) final String authCacheSpec,
                              @JsonProperty(value = "openDataClient", required = true) final OpenDataClientConfiguration openDataClientConfig,
                              @JsonProperty(value = "resetPasswordToken", required = false) final ResetPasswordTokenConfiguration tokenConfig,
                              @JsonProperty(value = "defaultPageSize", required = false) final Integer defaultPageSize) {
    this.dbtype = dbtype;
    this.mongoConfig = mongodbConfig;
    this.rdbmsConfig = rdbmsConfig;
    this.openDataClientConfig = openDataClientConfig;
    this.defaultPageSize = defaultPageSize != null ? defaultPageSize : DEFAULT_PAGE_SIZE;
    this.authCacheSpec = CacheBuilder.from(authCacheSpec != null ? authCacheSpec : DEFAULT_AUTH_CACHE_SPEC);
    this.tokenConfig = tokenConfig != null ? tokenConfig : new ResetPasswordTokenConfiguration(DEFAULT_TOKEN_TIME);
}
项目:dropwizard-jooq    文件:JooqBundle.java   
@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()));
}
项目:coner-core    文件:ConerCoreApplication.java   
private HibernateBundle<ConerCoreConfiguration> getHibernateBundle() {
    if (hibernateBundle == null) {
        Reflections r = new Reflections("org.coner.core.hibernate.entity");
        Set<Class<? extends HibernateEntity>> hibernateEntityClasses = r.getSubTypesOf(HibernateEntity.class);
        hibernateBundle = new HibernateBundle<ConerCoreConfiguration>(
                ImmutableList.copyOf(hibernateEntityClasses),
                new SessionFactoryFactory()
        ) {
            @Override
            public DataSourceFactory getDataSourceFactory(
                    ConerCoreConfiguration conerCoreConfiguration
            ) {
                return conerCoreConfiguration.getDataSourceFactory();
            }
        };
    }
    return hibernateBundle;
}
项目:soabase    文件:TestJdbiDynamicAttributes.java   
@Before
public void setup() throws Exception
{
    DBIFactory factory = new DBIFactory();
    Environment environment = new Environment("test", new ObjectMapper(), null, new MetricRegistry(), ClassLoader.getSystemClassLoader());
    DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setUrl("jdbc:hsqldb:mem:soa-jdbi;shutdown=true");
    dataSourceFactory.setDriverClass("org.hsqldb.jdbc.JDBCDriver");
    dataSourceFactory.setLogValidationErrors(true);
    dataSourceFactory.setUser("SA");
    dataSourceFactory.setValidationQuery("SELECT * FROM INFORMATION_SCHEMA.SYSTEM_TABLES");
    DBI jdbi = factory.build(environment, dataSourceFactory, "test");
    dynamicAttributes = new JdbiDynamicAttributes(jdbi, Collections.singletonList("test"));

    dynamicAttributes.getDao().createTable();
    dynamicAttributes.start();
}
项目:metadict    文件:DatabaseBundle.java   
private DataSourceFactory configureDataSourceFactory(MappedJsonConfiguration configuration) {
    DataSourceFactory dataSourceFactory = new DataSourceFactory();
    DatabaseType databaseType = configuration.getDatabaseConfiguration().getDbms();
    String connectionString = configuration.getDatabaseConfiguration().getConnection();

    if (!StringUtils.startsWithIgnoreCase(connectionString, databaseType.getConnectionPrefix())) {
        String msg = String.format("Invalid database connection URL: \"%s\" - must start with \"%s\"", connectionString, databaseType.getConnectionPrefix());
        LOGGER.error(msg);
        throw new MetadictRuntimeException(msg);
    }

    dataSourceFactory.setDriverClass(databaseType.getJdbcDriver());
    dataSourceFactory.setUrl(configuration.getDatabaseConfiguration().getConnection());
    dataSourceFactory.setValidationQuery(VALIDATION_QUERY_COMMENT + databaseType.getValidationQuery());

    LOGGER.info("Configured new DataSourceFactory of type {} to {}", databaseType, connectionString);

    return dataSourceFactory;
}
项目:dropwizard-entitymanager    文件:EntityManagerBundleTest.java   
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(environment.jersey()).thenReturn(jerseyEnvironment);
    when(jerseyEnvironment.getResourceConfig()).thenReturn(new DropwizardResourceConfig());
    when(environment.healthChecks()).thenReturn(healthChecks);

    when(factory.build(eq(bundle),
            any(Environment.class),
            any(DataSourceFactory.class),
            anyList(),
            eq("hibernate-entitymanager"))).thenReturn(entityManagerFactory);

    when(sharedEntityManagerFactory.build(any(EntityManagerContext.class)))
            .thenReturn(sharedEntityManager);
}
项目:macrobase    文件:SQLIngester.java   
private void initializeConnection() throws SQLException {
    if (connection == null) {
        DataSourceFactory factory = new DataSourceFactory();

        factory.setDriverClass(getDriverClass());
        factory.setUrl(String.format("%s//%s/%s", getJDBCUrlPrefix(), dbUrl, dbName));
        factory.setProperties(getJDBCProperties());

        if (dbUser != null) {
            factory.setUser(this.dbUser);
        }
        if (dbPassword != null) {
            factory.setPassword(dbPassword);
        }

        source = factory.build(MacroBase.metrics, dbName);
        this.connection = source.getConnection();
    }
}
项目:camunda-bpm-dropwizard    文件:CamundaConfigurationTest.java   
@Test
public void uses_configured_dropwizard_values() {
  final CamundaConfiguration configuration = new CamundaConfiguration();
  final DataSourceFactory database = configuration.getCamunda().getDatabase();
  database.setDriverClass(DRIVER);
  database.setUser(USER);
  database.setPassword(PASSWORD);
  database.setUrl(URL);

  final ProcessEngineConfiguration processEngineConfiguration = configuration.buildProcessEngineConfiguration();

  assertThat(processEngineConfiguration.getJdbcDriver()).isEqualTo(DRIVER);
  assertThat(processEngineConfiguration.getJdbcUsername()).isEqualTo(USER);
  assertThat(processEngineConfiguration.getJdbcPassword()).isEqualTo(PASSWORD);
  assertThat(processEngineConfiguration.getJdbcUrl()).isEqualTo(URL);
}
项目:el-bombillo    文件:ServiceRegistryApplication.java   
@Override
public void run(final ServiceRegistryConfiguration configuration, final Environment environment) throws Exception {
    final DataSourceFactory database = configuration.getDatabase();

    // execute DB migrations
    final Flyway flyway = new Flyway();
    flyway.setDataSource(database.getUrl(), database.getUser(), database.getPassword());
    log.debug("execute database migrations");
    flyway.migrate();
    log.info("database migrations successfully executed");

    // create DBI instance
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, database, "postgresql");

    environment.jersey().register(AuthFactory.binder(new BasicAuthFactory<>(
                    new ServiceRegistryAuthenticator(configuration.getCredentials()), "Realm", ServiceRegistryCaller.class))
    );
    environment.jersey().register(new ServiceResource(jdbi.onDemand(ServiceDAO.class)));
}
项目:dropwizard-jdbi-template    文件:MyApplication.java   
public void run(MyApplicationConfiguration configuration,
                Environment environment) throws ClassNotFoundException {

    // create database connection using JDBI
    final DBIFactory factory = new DBIFactory();
    final DataSourceFactory dataSourceFactory = configuration.getDataSourceFactory();
    final DBI jdbi = factory.build(environment, dataSourceFactory, "derby");

    // add resources
    final UserDAO dao = jdbi.onDemand(UserDAO.class);
    try {
        dao.createUserTable();
        logger.info("User table created");
    } catch (Exception e) {
        // probably the table already exists. Don't worry about it.
        if (e.getCause().getMessage().contains("already exists in Schema")) {
            logger.info("User table already exists.");
        } else {
            logger.log(Level.INFO, "User DB was not created", e);
        }

    }
    environment.jersey().register(new UserResourceImpl(dao));

}
项目:coner-core    文件:ConerCoreApplication.java   
private HibernateBundle<ConerCoreConfiguration> getHibernateBundle() {
    if (hibernateBundle == null) {
        Reflections r = new Reflections("org.coner.core.hibernate.entity");
        Set<Class<? extends HibernateEntity>> hibernateEntityClasses = r.getSubTypesOf(HibernateEntity.class);
        hibernateBundle = new HibernateBundle<ConerCoreConfiguration>(
                ImmutableList.copyOf(hibernateEntityClasses),
                new SessionFactoryFactory()
        ) {
            @Override
            public DataSourceFactory getDataSourceFactory(
                    ConerCoreConfiguration conerCoreConfiguration
            ) {
                return conerCoreConfiguration.getDataSourceFactory();
            }
        };
    }
    return hibernateBundle;
}
项目:budgetapp    文件:BudgetApplication.java   
@Override
public void initialize(Bootstrap<AppConfiguration> bootstrap) {
    MigrationsBundle<AppConfiguration> migrationBundle = new MigrationsBundle<AppConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(AppConfiguration configuration) {
            return configuration.getDataSourceFactory();
        }
    };

    // allow using Environment variable in yaml
    bootstrap.setConfigurationSourceProvider(
            new SubstitutingSourceProvider(
                    bootstrap.getConfigurationSourceProvider(),
                    new EnvironmentVariableSubstitutor(false)
            )
    );

    bootstrap.addBundle(migrationBundle);
    bootstrap.addBundle(hibernate);
    bootstrap.addBundle(new ConfiguredAssetsBundle("/app", "/app", "index.html"));
}
项目:dropwizard-java8    文件:JDBIOptionalInstantTest.java   
@Before
public void setupTests() throws IOException {
    final DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setDriverClass("org.h2.Driver");
    dataSourceFactory.setUrl("jdbc:h2:mem:date-time-optional-" + System.currentTimeMillis() + "?user=sa");
    dataSourceFactory.setInitialSize(1);
    final DBI dbi = new DBIFactory().build(env, dataSourceFactory, "test");
    try (Handle h = dbi.open()) {
        h.execute("CREATE TABLE tasks (" +
                "id INT PRIMARY KEY, " +
                "assignee VARCHAR(255) NOT NULL, " +
                "start_date TIMESTAMP, " +
                "end_date TIMESTAMP, " +
                "comments VARCHAR(1024) " +
                ")");
    }
    dao = dbi.onDemand(TaskDao.class);
}
项目:dropwizard-java8    文件:JDBIOptionalLocalDateTimeTest.java   
@Before
public void setupTests() throws IOException {
    final DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setDriverClass("org.h2.Driver");
    dataSourceFactory.setUrl("jdbc:h2:mem:date-time-optional-" + System.currentTimeMillis() + "?user=sa");
    dataSourceFactory.setInitialSize(1);
    final DBI dbi = new DBIFactory().build(env, dataSourceFactory, "test");
    try (Handle h = dbi.open()) {
        h.execute("CREATE TABLE tasks (" +
                "id INT PRIMARY KEY, " +
                "assignee VARCHAR(255) NOT NULL, " +
                "start_date TIMESTAMP, " +
                "end_date TIMESTAMP, " +
                "comments VARCHAR(1024) " +
                ")");
    }
    dao = dbi.onDemand(TaskDao.class);
}
项目:dropwizard-java8    文件:JDBIOptionalLocalDateTest.java   
@Before
public void setupTests() throws IOException {
    final DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setDriverClass("org.h2.Driver");
    dataSourceFactory.setUrl("jdbc:h2:mem:date-time-optional-" + System.currentTimeMillis() + "?user=sa");
    dataSourceFactory.setInitialSize(1);
    final DBI dbi = new DBIFactory().build(env, dataSourceFactory, "test");
    try (Handle h = dbi.open()) {
        h.execute("CREATE TABLE tasks (" +
                "id INT PRIMARY KEY, " +
                "assignee VARCHAR(255) NOT NULL, " +
                "start_date TIMESTAMP, " +
                "end_date TIMESTAMP, " +
                "comments VARCHAR(1024) " +
                ")");
    }
    dao = dbi.onDemand(TaskDao.class);
}
项目:Nebula    文件:NebulaService.java   
@Override
public void initialize(Bootstrap<NebulaServiceConfiguration> bootstrap) {
  GuiceBundle<NebulaServiceConfiguration> guiceBundle = GuiceBundle.<NebulaServiceConfiguration>newBuilder()
      .addModule(new NebulaServiceModule())
      .enableAutoConfig(getClass().getPackage().getName())
      .setConfigClass(NebulaServiceConfiguration.class)
      .build(Stage.DEVELOPMENT);

  bootstrap.addBundle(guiceBundle);

  // database migrations
  bootstrap.addBundle(new MigrationsBundle<NebulaServiceConfiguration>() {
    @Override
    public DataSourceFactory getDataSourceFactory(NebulaServiceConfiguration configuration) {
      return configuration.getDatabase();
    }
  });

  bootstrap.getObjectMapper().registerModule(new ProtobufModule());
  bootstrap.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
项目:droptools    文件:JooqBundleTest.java   
@Test
public void providesADefaultJooqFactoryName() throws Exception {
    jooqBundle = new JooqBundle<DropwizardConfig>() {
        @Override
        public JooqFactory getJooqFactory(DropwizardConfig configuration) {
            return jooqFactory;
        }

        @Override
        public DataSourceFactory getDataSourceFactory(DropwizardConfig configuration) {
            return dataSourceFactoryMaster;
        }
    };
    jooqBundle.run(new DropwizardConfig(), environment);
    assertThat(jooqBundle.getConfigurationMap().containsKey(DEFAULT_NAME));
}
项目:dropwizard-experiment    文件:TodoListApplication.java   
@Override
public void initialize(Bootstrap<TodoListConfiguration> bootstrap) {
    ebeanBundle = new EbeanBundle();
    //rabbitMqBundle = new RabbitMQBundle();

    // This outputs xDateTimes as ISO strings rather than an array of numbers in JSON.
    bootstrap.getObjectMapper().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    bootstrap.addBundle(new Java8Bundle());
    bootstrap.addBundle(ebeanBundle);
    //bootstrap.addBundle(rabbitMqBundle);
    bootstrap.addBundle(new OAuth2Bundle(ebeanBundle));
    bootstrap.addBundle(new TodoClientBundle());
    bootstrap.addBundle(new MigrationsBundle<TodoListConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(TodoListConfiguration configuration) {
            return configuration.getDatabaseConfig();
        }
    });

    // The anonymous subclass seems to be needed for the config type to be picked up correctly.
    bootstrap.addCommand(new WorkersCommand<TodoListConfiguration>(TodoListApplication.this) {});
    bootstrap.addCommand(new DbDiffCommand<TodoListConfiguration>() {});
}
项目:dropwizard-experiment    文件:DbDiffCommand.java   
@Override
protected void run(Bootstrap<T> bootstrap, Namespace namespace, T configuration) throws Exception {
    // The existing database with migrations managed by Liquibase.
    DataSourceFactory outdatedDb = configuration.getDatabaseConfig();

    try (CloseableLiquibase outdatedLiquibase = createLiquibase(outdatedDb)) {
        // A temporary database that starts out empty and then gets the autogenerated Ebean table definitions applied.
        DataSourceFactory freshDb = EbeanConfigUtils.clone(outdatedDb);
        String url = outdatedDb.getUrl();
        freshDb.setUrl(url.substring(0, url.lastIndexOf("/")) + "/migrationdiff");

        // Creating the Ebean server makes it apply its table definitions to the database immediately.
        ServerConfig serverConfig = EbeanConfigUtils.createServerConfig(freshDb);
        serverConfig.setDdlGenerate(true);
        serverConfig.setDdlRun(true);
        EbeanServer ebeanServer = EbeanServerFactory.create(serverConfig);

        try (CloseableLiquibase freshLiquibase = createLiquibase(freshDb)) {
            // Create and print the differences between the two databases, i.e. a migration that should be applied to update to the newest Ebean definitions.
            DiffResult diff = outdatedLiquibase.diff(freshLiquibase.getDatabase(), outdatedLiquibase.getDatabase(), CompareControl.STANDARD);
            DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diff, new DiffOutputControl(false, false, true));
            diffToChangeLog.print(System.out);
        }
    }
}
项目:dropwizard-experiment    文件:EbeanBundle.java   
private static void applyMigrations(DataSourceFactory dbConfig, MetricRegistry metrics) throws Exception {
    Stopwatch migrationsTimer = Stopwatch.createStarted();

    // Borrowed from AbstractLiquibaseCommand.
    DataSourceFactory lbConfig = EbeanConfigUtils.clone(dbConfig);
    lbConfig.setMaxSize(1);
    lbConfig.setMinSize(1);
    lbConfig.setInitialSize(1);

    try (CloseableLiquibase liquibase = new CloseableLiquibase(dbConfig.build(metrics, "liquibase"))) {
        log.info("Checking for database migrations.");
        liquibase.update("");

        migrationsTimer.stop();
        metrics.timer(MetricRegistry.name(EbeanBundle.class, "migrations")).update(migrationsTimer.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
        log.info("Database migrations complete in {} ms.", migrationsTimer.elapsed(TimeUnit.MILLISECONDS));
    } catch (ValidationFailedException e) {
        e.printDescriptiveError(System.err);
        throw e;
    }
}
项目:dropwizard-backbone-app    文件:AppService.java   
@Override
public void initialize(Bootstrap<AppConfiguration> bootstrap) {

  ImmutableList<Class<?>> classes = scanForEntities();
  hibernate = new HibernateBundle<AppConfiguration>(classes, new SessionFactoryFactory()) {
@Override
public DataSourceFactory getDataSourceFactory(AppConfiguration configuration) {
    return configuration.getDatabase();
}
  };

  bootstrap.addBundle(hibernate);

  db = new DB();
  bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.htm"));

  devModule = new AppDevModule(db);
  bootstrap.addBundle(GuiceBundle.newBuilder()
                                 .addModule(devModule)
                                 .enableAutoConfig(getClass().getPackage().getName())
                                 .build());
}
项目:dropwizard-routing    文件:RoutingHibernateBundle.java   
@Override
public final void run(T configuration, Environment environment) throws Exception {
    final Map<String, SessionFactory> sessionFactories = new LinkedHashMap<>();
    for (DataSourceRoute route : getDataSourceRoutes(configuration)) {
        final String routeKey = route.getRouteName();
        final DataSourceFactory dbConfig = route.getDatabase();

        final SessionFactory sessionFactory = sessionFactoryFactory.build(this, environment, dbConfig, entities,
                routeKey);

        String validationQuery = "/* Sess Factory Health Check routeKey " + routeKey + " */ " + dbConfig.getValidationQuery();

        environment.healthChecks().register(
                routeKey,
                new SessionFactoryHealthCheck(environment.getHealthCheckExecutorService(),
                        dbConfig.getValidationQueryTimeout().or(Duration.seconds(5)),
                        sessionFactory, validationQuery));
        sessionFactories.put(routeKey, sessionFactory);
    }

    this.sessionFactoryMap = ImmutableMap.copyOf(sessionFactories);
    environment.jersey().register(new RoutingUnitOfWorkApplicationListener(this.sessionFactoryMap));
}
项目:dropwizard-routing    文件:RoutingSessionFactoryFactory.java   
/**
 * Builds a {@link SessionFactory}
 * @param bundle
 *            the bundle
 * @param dbConfig
 *            the dbconfig
 * @param connectionProvider
 *            the connection provider
 * @param properties
 *            the hibernate properties
 * @param entities
 *            the persistent entities
 * @return {@link SessionFactory}
 */
private SessionFactory buildSessionFactory(RoutingHibernateBundle<?> bundle, DataSourceFactory dbConfig,
        ConnectionProvider connectionProvider, Map<String, String> properties, List<Class<?>> entities) {
    final Configuration configuration = new Configuration();
    configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed");
    configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS,
            Boolean.toString(dbConfig.isAutoCommentsEnabled()));
    configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true");
    configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
    configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true");
    configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true");
    configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true");
    configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
    configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
    for (Map.Entry<String, String> property : properties.entrySet()) {
        configuration.setProperty(property.getKey(), property.getValue());
    }

    addAnnotatedClasses(configuration, entities);
    bundle.configure(configuration);

    final ServiceRegistry registry = new StandardServiceRegistryBuilder()
            .addService(ConnectionProvider.class, connectionProvider).applySettings(properties).build();

    return configuration.buildSessionFactory(registry);
}
项目:Ultrastructure    文件:NAVI.java   
@Override
public void initialize(Bootstrap<T> bootstrap) {
    service = new PhantasmBundle();
    bootstrap.addBundle(service);
    jooqBundle = new JooqBundle<PhantasmConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(PhantasmConfiguration configuration) {
            return configuration.getDatabase();
        }

        @Override
        public JooqFactory getJooqFactory(PhantasmConfiguration configuration) {
            return configuration.getJooq();
        }
    };
    bootstrap.addBundle(jooqBundle);
}
项目:skid-road    文件:SkidRoadDropwizardExampleService.java   
@Override
public void initialize(Bootstrap<SkidRoadDropwizardExampleConfiguration> bootstrap) {

    ObjectMapper om = bootstrap.getObjectMapper();
    om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    om.registerModule(new JodaModule());
    om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

    bootstrap.addBundle(new DBIExceptionsBundle());
    bootstrap.addBundle(new MigrationsBundle<SkidRoadDropwizardExampleConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(SkidRoadDropwizardExampleConfiguration configuration) {
            return configuration.getSkidRoad().getDatabaseConfiguration();
        }
    });
    bootstrap.addCommand(new GenerateRandomKey());
}
项目:SAPNetworkMonitor    文件:NiPingMonitorApplication.java   
@Override
public void initialize(Bootstrap<ServerConfiguration> bootstrap) {

    bootstrap.addBundle(new MigrationsBundle<ServerConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(ServerConfiguration configuration) {
            return configuration.getDataSourceFactory();
        }
    });

    bootstrap.addBundle(new AssetsBundle("/com/cloudwise/sap/niping/view/static", "/static", null, "static"));
    bootstrap.addBundle(new AssetsBundle("/com/cloudwise/sap/niping/view/vendor", "/vendor", null, "vendor"));
    bootstrap.addBundle(new ViewBundle<ServerConfiguration>());
}
项目:rufus    文件:RufusApplication.java   
@Override
public void initialize(Bootstrap<RufusConfiguration> bootstrap) {
    bootstrap.addBundle(new AssetsBundle("/app", "/", "index.html"));
    bootstrap.addBundle(new ViewBundle<>());
    bootstrap.addBundle(new MultiPartBundle());
    bootstrap.addBundle(new MigrationsBundle<RufusConfiguration>() {
        @Override
        public DataSourceFactory getDataSourceFactory(RufusConfiguration conf) {
            return conf.getDataSourceFactory();
        }
    });
}
项目:jdbishard    文件:JDBIManager.java   
private PooledDataSourceFactory copyAndReplaceURL(
        DataSourceFactory dsFactory,
        ShardInfo shardInfo) {

    DataSourceFactory copy = new CopiedDataSourceFactory(dsFactory);
    copy.setUrl(shardInfo.url());
    return copy;
}