Java 类io.dropwizard.jdbi.DBIFactory 实例源码

项目:BloopServer    文件:BloopServerApplication.java   
@Override
public void run(final BloopServerConfiguration configuration,
                final Environment environment) {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "postgresql");
    final FlagDAO flagDAO = jdbi.onDemand(FlagDAO.class);
    final NearbyFlagDAO nearbyFlagDAO = jdbi.onDemand(NearbyFlagDAO.class);
    final PlayerDAO playerDAO = jdbi.onDemand(PlayerDAO.class);

    final Client client = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration())
            .build(getName());
    final String firebaseKey = configuration.getFirebaseKey();

    environment.jersey().register(new FlagResource(flagDAO, nearbyFlagDAO, playerDAO, client, firebaseKey));
    environment.jersey().register(new PlayerResource(playerDAO, flagDAO));
}
项目: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;
}
项目:jdbishard    文件:TestApp.java   
@Override
public void run(TestAppConfig configuration, Environment environment) throws Exception {

    final ShardRegistry<String, UUID> shardRegistry = new ShardRegistry<>();
    final DAORegistry<String> daoRegistry = new DAORegistry<>();
    final DBIFactory dbiFactory = new DBIFactory();

    jdbiManager = new JDBIManager<>(
            new StaticShardService(),
            shardRegistry,
            new DBIRegistry<>(),
            daoRegistry,
            dbiFactory,
            environment,
            configuration.getDataSourceFactory(),
            new NoOpDBIInitializer(),
            new IdOnlyShardNamer());

    clientDAO = new ClientDAO(shardRegistry, daoRegistry);

    daoRegistry.registerType(ClientShardDAO.class);

    jdbiManager.updateObjects();
}
项目:irontest    文件:IronTestApplication.java   
private void createSampleResources(IronTestConfiguration configuration, Environment environment) {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getSampleDatabase(), "sampleDatabase");

    //  create DAO objects
    final ArticleDAO articleDAO = jdbi.onDemand(ArticleDAO.class);

    //  create database tables
    articleDAO.createTableIfNotExists();

    //  register APIs
    environment.jersey().register(new ArticleResource(articleDAO));

    //  register SOAP web services
    jaxWsBundle.publishEndpoint(new EndpointBuilder("/article", new ArticleSOAP(articleDAO)));
}
项目:cassandra-reaper    文件:ReaperApplication.java   
private IStorage initializeStorage(ReaperApplicationConfiguration config, Environment environment)
    throws ReaperException {
  IStorage storage;

  if ("memory".equalsIgnoreCase(config.getStorageType())) {
    storage = new MemoryStorage();
  } else if ("cassandra".equalsIgnoreCase(config.getStorageType())) {
    storage = new CassandraStorage(config, environment);
  } else if ("postgres".equalsIgnoreCase(config.getStorageType())
      || "h2".equalsIgnoreCase(config.getStorageType())
      || "database".equalsIgnoreCase(config.getStorageType())) {
    // create DBI instance
    final DBIFactory factory = new DBIFactory();

    // instanciate store
    storage = new PostgresStorage(factory.build(environment, config.getDataSourceFactory(), "postgresql"));
    initDatabase(config);
  } else {
    LOG.error("invalid storageType: {}", config.getStorageType());
    throw new ReaperException("invalid storage type: " + config.getStorageType());
  }
  Preconditions.checkState(storage.isStorageConnected(), "Failed to connect storage");
  return storage;
}
项目: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" + "/*");
}
项目:service-hml    文件:HmlJdbiApplication.java   
@Override
public void runService(final HmlJdbiConfiguration configuration, final Environment environment) throws Exception {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "mysql");
    final HmlDao hmlDao = jdbi.onDemand(HmlDao.class);

    Injector injector = Guice.createInjector(new JdbiHmlServiceModule(), new AbstractModule() {
            @Override
            protected void configure() {
                bind(HmlDao.class).toInstance(hmlDao);
            }
        });

    environment.healthChecks().register("database", new DBIHealthCheck(jdbi, "select 1"));

    environment.jersey().register(injector.getInstance(HmlResource.class));
    environment.jersey().register(new HmlExceptionMapper());
    environment.jersey().register(new HmlMessageBodyReader());

    environment.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
}
项目: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();
}
项目: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)));
}
项目:hexagonal-sentimental    文件:SentimentalApplication.java   
@Override
public void run(SentimentalConfiguration configuration, Environment environment) {
    final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);

    // SPI Lexicon
    final Lexicon lexicon = new FileBasedLexicon(configuration.getLexiconFileName());

    // SPI Trend
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "postgresql");
    final AuditDAO auditDao = jdbi.onDemand(AuditDAO.class);
    final Trend audit = new TrendRepository(auditDao);

    // Domain Model
    final SentimentAnalysis service = new SentimentAnalysis(lexicon, audit);

    // API RESTful
    final SentimentalResource resource = new SentimentalResource(service);
    environment.jersey().register(resource);

    // API Twitter
    final TwitterAdapter twitterAdapter = new TwitterAdapter(service, new SamplePlayer());
    twitterAdapter.subscribe("devoxx, #memepasmal, @cyriux, @tpierrain, arolla");
    // start
}
项目:service-feature    文件:FeatureJdbiApplication.java   
@Override
public void runService(final FeatureJdbiConfiguration configuration, final Environment environment) throws Exception {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "mysql");
    final FeatureDao featureDao = jdbi.onDemand(FeatureDao.class);

    Injector injector = Guice.createInjector(new JdbiFeatureServiceModule(), new ExceptionMapperModule(),
        new AbstractModule() {
            @Override
            protected void configure() {
                bind(FeatureDao.class).toInstance(featureDao);
            }
        });

    environment.healthChecks().register("database", new DBIHealthCheck(jdbi, "select 1"));

    environment.jersey().register(injector.getInstance(FeatureResource.class));
    environment.jersey().register(injector.getInstance(UserInputExceptionMapper.class));

    environment.getObjectMapper()
        .enable(SerializationFeature.INDENT_OUTPUT)
        .addMixInAnnotations(Feature.class, FeatureMixIn.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));

}
项目:DGH2    文件:HelloApplication.java   
@Override
public void run(HelloConfiguration configuration, Environment environment) throws ClassNotFoundException {
    final DBI dbi = new DBIFactory().build(environment, configuration.getDataSourceFactory(), "h2");
    final NameDAO nameDAO = dbi.onDemand(NameDAO.class);
    final ObjectGraph objectGraph = ObjectGraph.create(new HelloModule(configuration, nameDAO));

    initializeDatabase(dbi);
    /*
    * API:
    * GET -> String    /hello
    * GET -> String    /hello?name={name}
    * GET -> JSON      /hello/all
    * GET -> JSON      /hello/{id}
    * POST -> JSON     /hello/add
    */
    environment.jersey().register(objectGraph.get(NameResource.class));
}
项目:ethmmyrss    文件:ThmmyRssApplication.java   
@Override
public void run(ThmmyRssConfiguration configuration, Environment env)
        throws Exception {
    client = new JerseyClientBuilder(env).using(configuration.getJerseyClientConfiguration()).using(env)
            .withProperty("PROPERTY_CHUNKED_ENCODING_SIZE", 0).build("jersey-client");
    DBIFactory factory = new DBIFactory();
    DBI jdbi = factory.build(env, configuration.getDatabase(), "announcement-db");
    announcementDAO = jdbi.onDemand(AnnouncementDAO.class);

    tryCreateAnnouncementTable();
    AnnouncementFetcher announcementFetcher = new AnnouncementFetcher(client, configuration);
    env.healthChecks().register("announcement-fetcher-health", new AnnouncementFetcherHealthCheck(configuration, announcementFetcher));
    this.announcementService = new AnnouncementServiceImpl(announcementDAO, announcementFetcher, configuration);
    env.jersey().register(new FeedResource(announcementService, configuration));
    env.jersey().register(new IndexResource(configuration));
}
项目:skid-road    文件:ListStatesCommand.java   
@Override
protected void run(Environment env, Namespace namespace, T configuration) throws Exception {
    CliConveniences.quietLogging("ifar", "hsqldb.db");

    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(env, getSkidRoadReadOnlyConfiguration(configuration).getDatabaseConfiguration(), "logfile");
    JDBILogFileDAO dao = jdbi.onDemand(DefaultJDBILogFileDAO.class);
    List<CountByState> counts = dao.countLogFilesByState();
    if (!counts.isEmpty()) {
        System.out.println(String.format("%-20s | %-10s", "STATE", "COUNT"));
        System.out.println(String.format("%s_|_%s", StringUtils.repeat("_", 20), StringUtils.repeat("_", 10)));
    }
    for (CountByState cbs : counts) {
        System.out.println(String.format("%-20s | %-10d", cbs.getState(), cbs.getCount()));
    }
}
项目:soren-subscriber    文件:SorenSubscriberApplication.java   
@Override
public void run(final SorenSubscriberConfiguration configuration, final Environment environment) {
    // Registering DAOs and creating Guice
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            DBIFactory factory = new DBIFactory();
            DBI dbi = factory.build(environment, configuration.getDataSourceFactory(), DATABASE_TYPE.value);
            SorenSubscriberDAO sorenSubscriberDAO = dbi.onDemand(SorenSubscriberDAO.class);
            bind(SorenSubscriberDAO.class).toInstance(sorenSubscriberDAO);
        }
    });

    // Swagger doc endpoint
    environment.jersey().register(new ApiListingResource());

    // Health Check registration
    environment.jersey().register(injector.getInstance(SubscriberHealthCheck.class));

    // Resources registration
    environment.jersey().register(injector.getInstance(SubscriberResource.class));

    environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

    BeanConfig config = new BeanConfig();
    config.setTitle("Swagger sample app");
    config.setVersion("1.0.0");
    config.setResourcePackage("org.vahid.resources");
    config.setScan(true);
}
项目:oacc-example-securetodo    文件:SecureTodoApplication.java   
@Override
public void run(final SecureTodoConfiguration configuration,
                final Environment environment) {
   final DBIFactory dbiFactory = new DBIFactory();
   final DBI todoJdbi = dbiFactory.build(environment, configuration.getTodoDbDataSourceFactory(), "todoDb");
   final TodoUserDAO todoUserDao = todoJdbi.onDemand(TodoUserDAO.class);
   final TodoItemDAO todoItemDao = todoJdbi.onDemand(TodoItemDAO.class);

   final AccessControlContextFactory accessControlContextFactory = configuration.getAccessControlContextFactory();
   accessControlContextFactory.initialize(environment, configuration.getOaccDbDataSourceFactory(), "oacc");

   environment.jersey().register(new TodoUserResource(new TodoUserService(todoUserDao, accessControlContextFactory)));
   environment.jersey().register(new TodoItemResource(new TodoItemService(todoItemDao)));

   environment.jersey().register(new AuthDynamicFeature(
         new BasicCredentialAuthFilter.Builder<OaccPrincipal>()
               .setAuthenticator(new OaccBasicAuthenticator(accessControlContextFactory))
               .setRealm("OACC Basic Authentication")
               .buildAuthFilter()));
   // to use @Auth to inject a custom Principal type into a resource:
   environment.jersey().register(new AuthValueFactoryProvider.Binder<>(OaccPrincipal.class));

   environment.jersey().register(new AuthorizationExceptionMapper(environment.metrics()));
   environment.jersey().register(new IllegalArgumentExceptionMapper(environment.metrics()));
   environment.jersey().register(new InvalidCredentialsExceptionMapper(environment.metrics()));
   environment.jersey().register(new NotAuthenticatedExceptionMapper(environment.metrics()));
}
项目:dropwizard-hikaricp-benchmark    文件:BenchApplication.java   
@Override
public void run(final BenchConfiguration config,
                final Environment environment) {
    final DBIFactory factory = new DBIFactory();
    final Optional<PooledDataSourceFactory> tomcatFactory = config.getTomcatFactory().map(x -> x);

    config.getHikariFactory().ifPresent(x -> x.setHealthCheckRegistry(environment.healthChecks()));
    final Optional<PooledDataSourceFactory> hikariFactory = config.getHikariFactory().map(x -> x);
    final PooledDataSourceFactory datasource = tomcatFactory.orElse(hikariFactory.orElse(null));
    final DBI jdbi = factory.build(environment, datasource, "postgresql");
    jdbi.registerMapper(new QuestionMapper());
    final QuestionQuery dao = jdbi.onDemand(QuestionQuery.class);
    environment.jersey().register(new QuestionResource(dao));
}
项目:trackerserver    文件:TrackerServerApplication.java   
@Override
public void run(final TrackerServerConfiguration config,
                final Environment environment) {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, config.getDataSourceFactory(), "postgresql");
    final UserDAO dao = jdbi.onDemand(UserDAO.class);
    environment.jersey().register(new MainResource(config, dao));
}
项目:cqrs-eventsourcing-kafka    文件:EventStoreFactory.java   
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;
}
项目:openregister-java    文件:DatabaseManager.java   
public DatabaseManager(DatabaseConfiguration databaseConfiguration, Environment environment, DBIFactory dbiFactory, Boolean isRunningOnCloudFoundry) throws IOException {
    this.database = databaseConfiguration.getDatabase();
    this.database.getProperties().put("ApplicationName", "openregister_java");

    if (isRunningOnCloudFoundry) {
        this.database.setUrl(getCloudFoundryDatabaseServiceJDBCUrl());
    }

    // dbiFactory.build() will ensure that this dataSource is correctly shut down
    // it will also be shared with flyway
    this.dataSource = database.build(environment.metrics(), "openregister_java");
    this.dbi = dbiFactory.build(environment, database, dataSource, "openregister_java");
}
项目:openregister-java    文件:PostgresRegisterTransactionalFunctionalTest.java   
@Before
public void setUp() throws Exception {
    final DBIFactory factory = new DBIFactory();
    Environment env = new Environment("test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null);
    dbi = factory.build(env, getDataSourceFactory(), "database");
    handle = dbi.open();
    testItemDAO = handle.attach(TestItemCommandDAO.class);
    testEntryDAO = handle.attach(TestEntryDAO.class);
    derivationRecordIndex = mock(DerivationRecordIndex.class);
}
项目:clouseau    文件:ClouseauApplication.java   
@Override
public void run(ClouseauConfiguration config, Environment env) throws Exception {
    ObjectMapper mapper = env.getObjectMapper();
    config.configureObjectMapper(mapper);
    DBIFactory factory = new DBIFactory();
    DBI dbi = factory.build(env, config.getDataSourceFactory(), "sessionDB");
    SessionStore sessionStore = config.getSessionStore(dbi);
    ObjectGraphService objectGraphService = config.getObjectGraphService();
    env.jersey().register(new SessionResource(sessionStore, objectGraphService));
    env.jersey().setUrlPattern("/api/*");
}
项目:species-population    文件:TileServerApplication.java   
@Override
public final void run(TileServerConfiguration configuration, Environment environment) {

  final DBIFactory factory = new DBIFactory();
  final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "MySQL");
  final DataDAO dataDao = jdbi.onDemand(DataDAO.class);
  final DataService dataService = new DataService(dataDao);
  environment.jersey().register(new TileResource(dataService));
}
项目:dropwizard-microservices-example    文件:ProductCatalogModule.java   
@Provides
public DBI prepareJdbi(Environment environment, ProductCatalogConfiguration configuration)
        throws ClassNotFoundException {
    // setup DB access including DAOs
    // implementing a singleton pattern here but avoiding
    // Guice to initialize DB connection too early
    if (jdbi == null) {
        final DBIFactory factory = new DBIFactory();
        jdbi = factory.build(environment, configuration.getDataSourceFactory(), "h2");
    }
    return jdbi;
}
项目:dropwizard-microservices-example    文件:ProductReviewModule.java   
@Provides
public DBI prepareJdbi(Environment environment, ProductReviewConfiguration configuration)
        throws ClassNotFoundException {
    // setup DB access including DAOs
    // implementing a singleton pattern here but avoiding
    // Guice to initialize DB connection too early
    if (jdbi == null) {
        final DBIFactory factory = new DBIFactory();
        jdbi = factory.build(environment, configuration.getDataSourceFactory(), "h2");
    }
    return jdbi;
}
项目:log-dropwizard-eureka-mongo-sample    文件:H2Test.java   
@Before
public void setupH2Test() throws Exception {
    liquibase = new CloseableLiquibase(hsqlConfig
            .getDataSourceFactory()
            .build(new MetricRegistry(), "liquibase"));
    liquibase.update("");
    database = new DBIFactory().build(environment(), hsqlConfig.getDataSourceFactory(), "h2test");
    database.registerArgumentFactory(new DependencyIdArgumentFactory());
    database.registerArgumentFactory(new ServiceIdArgumentFactory());
    database.registerArgumentFactory(new TenacityConfigurationArgumentFactory(Jackson.newObjectMapper()));
    database.registerArgumentFactory(new DateTimeArgumentFactory());
}
项目:el-bombillo    文件:AccountServiceApplication.java   
@Override
public void run(final AccountServiceConfiguration configuration, final Environment environment) throws Exception {
    final DataSourceFactory database = configuration.getDatabase();
    this.executeDatabaseMigrations(database);

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

    // create a HTTP client
    final Client client = new JerseyClientBuilder(environment).using(configuration.getHttpClient()).build("httpClient");

    // setup listener which will register this service within the service registry
    final AccountServiceLifecycleListener accountServiceLifecycleListener = new AccountServiceLifecycleListener(configuration.getServiceInformation(), configuration.getRegistryService(), client);
    environment.lifecycle().addServerLifecycleListener(accountServiceLifecycleListener);
    environment.healthChecks().register("registry", new ServiceRegistryHealthCheck(accountServiceLifecycleListener));
    environment.admin().addTask(new ServiceRegistryTask(accountServiceLifecycleListener));

    // enable the linking feature of jersey
    environment.jersey().getResourceConfig().packages(getClass().getPackage().getName()).register(DeclarativeLinkingFeature.class);

    // register authenticator
    environment.jersey().register(AuthFactory.binder(new BasicAuthFactory<>(
                    new AccountServiceAuthenticator(configuration.getServiceInformation()), "Realm", AccountServiceCaller.class))
    );

    // register REST resources
    environment.jersey().register(new AccountResource(jdbi.onDemand(AccountDAO.class)));
}
项目:monasca-persister    文件:DBIProvider.java   
@Override
public DBI get() {
  try {
    return new DBIFactory().build(environment, configuration.getDataSourceFactory(), "vertica");
  } catch (ClassNotFoundException e) {
    throw new ProvisionException("Failed to provision DBI", e);
  }
}
项目:symbiot    文件:ServerApplication.java   
@Override
public void run(ServerConfiguration conf, Environment env) throws ClassNotFoundException {

    // health checks
    env.healthChecks().register("ping", new PingHealthCheck());

    // configure object mapper
    env.getObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    // init JDBI
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(env, conf.getDataSourceFactory(), "derby");
    final StreamDao streamDao = jdbi.onDemand(StreamDao.class);
    final BindingDao bindingDao = new BindingDao(jdbi);
    final DriverDao driverDao = new DriverDao(env.getObjectMapper());
    final InputDao inputDao = new InputDao(jdbi);
    final OutputDao outputDao = new OutputDao(jdbi);

    // register resources
    env.jersey().register(new PingResource(conf.getEcho()));
    env.jersey().register(new StreamResource(bindingDao, driverDao, inputDao, outputDao, streamDao));
    env.jersey().register(new BindingResource(bindingDao, driverDao, inputDao, outputDao, streamDao));
    env.jersey().register(new DriverResource(driverDao));
    env.jersey().register(new InputResource(driverDao, inputDao, outputDao, streamDao, bindingDao, env.getObjectMapper()));
    env.jersey().register(new OutputResource(driverDao, outputDao, streamDao));

    // upon server startup, load streams
    env.lifecycle().addServerLifecycleListener(new StreamLoader());
}
项目:monasca-api    文件:MonApiModule.java   
@Provides
@Singleton
@Named("mysql")
public DBI getMySqlDBI() {
  try {
    return new DBIFactory().build(environment, config.mysql, "mysql");
  } catch (ClassNotFoundException e) {
    throw new ProvisionException("Failed to provision MySQL DBI", e);
  }
}
项目:monasca-api    文件:MonApiModule.java   
@Provides
@Singleton
@Named("vertica")
public DBI getVerticaDBI() {
  try {
    return new DBIFactory().build(environment, config.vertica, "vertica");
  } catch (ClassNotFoundException e) {
    throw new ProvisionException("Failed to provision Vertica DBI", e);
  }
}
项目:Nebula    文件:NebulaServiceModule.java   
@Provides
@Singleton
public DBI providesDBI(Environment environment, NebulaServiceConfiguration configuration) throws ClassNotFoundException {
  final DBIFactory factory = new DBIFactory();

  return factory.build(environment, configuration.getDatabase(), "db");
}
项目:breakerbox    文件:H2Test.java   
@Before
public void setupH2Test() throws Exception {
    liquibase = new CloseableLiquibaseWithClassPathMigrationsFile(hsqlConfig
            .getDataSourceFactory()
            .build(new MetricRegistry(), "liquibase"), JdbiStore.MIGRATIONS_FILENAME);
    liquibase.update("");
    database = new DBIFactory().build(environment(), hsqlConfig.getDataSourceFactory(), "h2test");
    database.registerArgumentFactory(new DependencyIdArgumentFactory());
    database.registerArgumentFactory(new ServiceIdArgumentFactory());
    database.registerArgumentFactory(new TenacityConfigurationArgumentFactory(Jackson.newObjectMapper()));
    database.registerArgumentFactory(new DateTimeArgumentFactory());
}
项目:monasca-common    文件:DatabaseModule.java   
@Override
protected void configure() {
  bind(DataSourceFactory.class).toInstance(config);
  bind(DBI.class).toProvider(new Provider<DBI>() {
    @Override
    public DBI get() {
      try {
        return new DBIFactory().build(environment, config, "platform");
      } catch (ClassNotFoundException e) {
        throw new ProvisionException("Failed to provision DBI", e);
      }
    }
  }).in(Scopes.SINGLETON);
}
项目:airpal    文件:AirpalModule.java   
@Singleton
@Provides
public DBI provideDBI(ObjectMapper objectMapper)
        throws ClassNotFoundException
{
    final DBIFactory factory = new DBIFactory();
    final DBI dbi = factory.build(environment, config.getDataSourceFactory(), provideDbType().name());
    dbi.registerMapper(new TableRow.TableRowMapper(objectMapper));
    dbi.registerMapper(new QueryStoreMapper(objectMapper));
    dbi.registerArgumentFactory(new UUIDArgumentFactory());
    dbi.registerArgumentFactory(new URIArgumentFactory());

    return dbi;
}
项目:skid-road    文件:ListOwnersCommand.java   
@Override
protected void run(Environment env, Namespace namespace, T configuration) throws Exception {
    CliConveniences.quietLogging("ifar");

    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(env, getSkidRoadReadOnlyConfiguration(configuration).getDatabaseConfiguration(), "logfile");
    JDBILogFileDAO dao = jdbi.onDemand(DefaultJDBILogFileDAO.class);
    try (ResultIterator<String> ownerUris = dao.listOwnerUris()) {
        while (ownerUris.hasNext()) {
            System.out.println(ownerUris.next());
        }
    }

}
项目:skid-road    文件:InjectLogCommand.java   
@Override
protected void run(Environment env, Namespace namespace, T configuration) throws Exception {
    CliConveniences.quietLogging("ifar", "hsqldb.db");
    DateTime startTime = ISODateTimeFormat.dateOptionalTimeParser().withZoneUTC().parseDateTime(namespace.getString(START_DATE));
    String inFile = namespace.getString(FILE);

    String owner = namespace.getString(OWNER) == null ?
            getSkidRoadConfiguration(configuration).getNodeId() :
            namespace.getString(OWNER);

    SkidRoadConfiguration skidRoadConfiguration = getSkidRoadConfiguration(configuration);

    DBIFactory factory = new DBIFactory();
    DBI jdbi = factory.build(env, skidRoadConfiguration.getDatabaseConfiguration(), "logfile");
    jdbi.registerArgumentFactory(new JodaArgumentFactory());

    FileRollingScheme scheme = ManagedWritingWorkerManager.getFileRollingScheme(skidRoadConfiguration.getRequestLogWriterConfiguration());
    String rollingCohort = scheme.getRepresentation(startTime);

    JDBILogFileDAO dao = jdbi.onDemand(DefaultJDBILogFileDAO.class);

    int serial;
    while (true) {
        serial = dao.determineNextSerial(rollingCohort) + 1;
        int rows = dao.claimIndex(rollingCohort, serial, new Timestamp(startTime.getMillis()), Paths.get(inFile).toUri().toString(), owner, new Timestamp(System.currentTimeMillis()));
        if (rows == 1) {
            System.out.println(String.format("Created database record for %s serial %d.", rollingCohort, serial));
            break;
        } else {
            System.out.println(String.format("Another instance claimed %s serial %d. Will retry.", rollingCohort, serial));
        }
    }

    dao.updateSize(rollingCohort, serial, Files.size(Paths.get(inFile)), owner, new Timestamp(System.currentTimeMillis()));
    dao.updateState(rollingCohort, serial, LogFileState.WRITTEN.toString(), owner, new Timestamp(System.currentTimeMillis()));

    System.out.println("Database record marked as WRITTEN. File must remain available at provided path until it has been uploaded.");

    System.out.println("[DONE]");
}
项目:SAPNetworkMonitor    文件:NiPingMonitorApplication.java   
@Override
public void run(ServerConfiguration configuration, Environment environment) throws Exception {

    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "sapData");

    ObjectMapper objectMapper = environment.getObjectMapper();
    SapConfiguration sapConfiguration = configuration.getSapConfig();
    JobConfiguration jobConfiguration = configuration.getJobConfig();
    NiPingServiceBinder niPingServiceBinder = new NiPingServiceBinder(jdbi, objectMapper, sapConfiguration, jobConfiguration);

    ServiceLocator serviceLocator = ServiceLocatorUtilities.bind(niPingServiceBinder);
    SapBasicAuthenticator sapBasicAuthenticator = ServiceLocatorUtilities.getService(serviceLocator, SapBasicAuthenticator.class
            .getName());
    SapOAuthenticator sapOAuthenticator = ServiceLocatorUtilities.getService(serviceLocator, SapOAuthenticator.class.getName());

    final BasicCredentialAuthFilter basicAuthFilter = new BasicCredentialAuthFilter.Builder<BasicAuthUser>()
            .setAuthenticator(sapBasicAuthenticator)
            .buildAuthFilter();
    final AuthFilter oAuthFilter = new OAuthCredentialAuthFilter.Builder<OAuthUser>()
            .setAuthenticator(sapOAuthenticator)
            .setPrefix("Bearer")
            .buildAuthFilter();

    final PolymorphicAuthDynamicFeature feature = new PolymorphicAuthDynamicFeature<UserPrincipal>(ImmutableMap.of(BasicAuthUser
            .class, basicAuthFilter, OAuthUser.class, oAuthFilter));
    final AbstractBinder binder = new PolymorphicAuthValueFactoryProvider.Binder<>(ImmutableSet.of(BasicAuthUser.class, OAuthUser
            .class));
    environment.jersey().register(new AuthFilterDynamicBinding());
    environment.jersey().register(feature);
    environment.jersey().register(binder);

    environment.jersey().register(niPingServiceBinder);
    environment.jersey().packages("com.cloudwise.sap.niping.auth");
    environment.jersey().packages("com.cloudwise.sap.niping.service");
    environment.jersey().packages("com.cloudwise.sap.niping.dao");
    environment.jersey().packages("com.cloudwise.sap.niping.common.vo.converter");
    environment.jersey().packages("com.cloudwise.sap.niping.resource");

    environment.jersey().register(SessionFactoryProvider.class);
    environment.servlets().setSessionHandler(new SessionHandler());
}