Java 类javax.sql.DataSource 实例源码

项目:My-Blog    文件:TaleUtils.java   
/**
 * 获取新的数据源
 *
 * @return
 */
public static DataSource getNewDataSource() {
    if (newDataSource == null) synchronized (TaleUtils.class) {
        if (newDataSource == null) {
            Properties properties = TaleUtils.getPropFromFile("application-default.properties");
            if (properties.size() == 0) {
                return newDataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            newDataSource = managerDataSource;
        }
    }
    return newDataSource;
}
项目:simple-openid-provider    文件:JdbcClientRepositoryIntegrationTests.java   
@Bean
DataSource dataSource() {
    // @formatter:off
    return new EmbeddedDatabaseBuilder()
            .generateUniqueName(true)
            .setType(EmbeddedDatabaseType.H2)
            .addScript("schema-clients.sql")
            .build();
    // @formatter:on
}
项目:org.ops4j.pax.transx    文件:HsqlTest.java   
@Test
public void testConnectionsWithTx() throws Exception {
    DataSource ds = wrap(createHsqlDataSource());

    Transaction tx = tm.begin();
    try {
        try (Connection con = ds.getConnection()) {
            try (Connection con2 = ds.getConnection()) {
                assertNotSame(con, con2);
            }
        }
        tx.commit();
    } catch (Throwable t) {
        tx.rollback();
        throw t;
    }
}
项目:uavstack    文件:MybatisHookProxy.java   
@Override
protected void collectDBPoolMetrics(MonitorElement clientElem) {

    if (this.datasources.size() == 0) {
        return;
    }

    for (DataSource cp : this.datasources) {
        String jdbcURL = (String) ReflectionHelper.invoke(cp.getClass().getName(), cp, "getUrl", null, null,
                cp.getClass().getClassLoader());

        MonitorElementInstance inst = this.matchElemInstance(clientElem, jdbcURL);

        if (inst == null) {
            continue;
        }

        collectDataSourceStat(inst, cp, webapploaderForMybatis);
    }
}
项目:otter-G    文件:DataSourceCreator.java   
/**
 * 扩展功能,可以自定义一些自己实现的 dataSource
 */
private DataSource preCreate(Long pipelineId, DbMediaSource dbMediaSource) {

    if (CollectionUtils.isEmpty(dataSourceHandlers)) {
        return null;
    }

    DataSource dataSource = null;
    for (DataSourceHanlder handler : dataSourceHandlers) {
        if (handler.support(dbMediaSource)) {
            dataSource = handler.create(pipelineId, dbMediaSource);
            if (dataSource != null) {
                return dataSource;
            }
        }
    }
    return null;
}
项目:DHIS2-fhir-lab-app    文件:FhirServerConfigDstu3.java   
/**
 * The following bean configures the database connection. The 'url' property value of "jdbc:derby:directory:jpaserver_derby_files;create=true" indicates that the server should save resources in a
 * directory called "jpaserver_derby_files".
 * 
 * A URL to a remote database could also be placed here, along with login credentials and other properties supported by BasicDataSource.
 */
@Bean(destroyMethod = "close")
public DataSource dataSource() {
    BasicDataSource retVal = new BasicDataSource();
    /*
    retVal.setDriver(new org.apache.derby.jdbc.EmbeddedDriver());
    retVal.setUrl("jdbc:derby:directory:target/jpaserver_derby_files;create=true");
    retVal.setUsername("");
    retVal.setPassword("");
    * */


    try
    {
        retVal.setDriver(new com.mysql.jdbc.Driver());
    }
    catch (Exception exc)
    {
        exc.printStackTrace();
    }
    retVal.setUrl("jdbc:mysql://localhost:3306/dhis2_fhir");
    retVal.setUsername("root");
    retVal.setPassword("");
    return retVal;
}
项目:SpringBoot-Study    文件:ClusterDruidDataSourceConfig.java   
/**
 * SqlSessionFactory配置
 *
 * @return
 * @throws Exception
 */
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(
        @Qualifier("clusterDataSource") DataSource dataSource
) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    //配置mapper文件位置
    sqlSessionFactoryBean.setMapperLocations(resolver.getResources(clusterMapperLocations));

    //配置分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //设置插件
    sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
    return sqlSessionFactoryBean.getObject();
}
项目:xm-ms-balance    文件:DatabaseConfiguration.java   
@Bean
@DependsOn("liquibase")
public MultiTenantSpringLiquibase multiTenantLiquibase(
    DataSource dataSource,
    LiquibaseProperties liquibaseProperties) {
    MultiTenantSpringLiquibase liquibase = new XmMultiTenantSpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog(CHANGE_LOG_PATH);
    liquibase.setContexts(liquibaseProperties.getContexts());
    liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
    liquibase.setDropFirst(liquibaseProperties.isDropFirst());
    liquibase.setSchemas(getSchemas());
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) {
        liquibase.setShouldRun(false);
    } else {
        liquibase.setShouldRun(liquibaseProperties.isEnabled());
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
项目:lams    文件:DataSourceUtils.java   
/**
 * Actually close the given Connection, obtained from the given DataSource.
 * Same as {@link #releaseConnection}, but throwing the original SQLException.
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param con the Connection to close if necessary
 * (if this is {@code null}, the call will be ignored)
 * @param dataSource the DataSource that the Connection was obtained from
 * (may be {@code null})
 * @throws SQLException if thrown by JDBC methods
 * @see #doGetConnection
 */
public static void doReleaseConnection(Connection con, DataSource dataSource) throws SQLException {
    if (con == null) {
        return;
    }
    if (dataSource != null) {
        ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
        if (conHolder != null && connectionEquals(conHolder, con)) {
            // It's the transactional Connection: Don't close it.
            conHolder.released();
            return;
        }
    }
    logger.debug("Returning JDBC Connection to DataSource");
    doCloseConnection(con, dataSource);
}
项目:angit    文件:DatasourceConfig.java   
/**
 * Dynamic sql session factory sql session factory.
 *
 * @param dynamicDataSource the dynamic data source
 * @param properties        the properties
 * @return the sql session factory
 */
@Bean
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public SqlSessionFactory dynamicSqlSessionFactory(
        @Qualifier("dynamicDataSource") DataSource dynamicDataSource,
        MybatisProperties properties) {
    final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dynamicDataSource);
    sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(properties.getConfigLocation()));
    sessionFactory.setMapperLocations(properties.resolveMapperLocations());
    try {
        return sessionFactory.getObject();
    } catch (Exception e) {
        throw new SystemException(e);
    }
}
项目:Spring-Security-Third-Edition    文件:DataSourceConfig.java   
/**
 * Embedded H2 database
 * Connect to running database with the following details:
 *
 * URL: jdbc:h2:mem:dataSource
 * Driver Class: org.h2.Driver
 * Username: sa
 * Password: [blank]
 *
 * @return
 */
@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    database = builder.setType(EmbeddedDatabaseType.H2)
            .setName("dataSource")
            .ignoreFailedDrops(true)
            .continueOnError(false)
            .addScript("classpath:database/h2/calendar-schema.sql")
            .addScript("classpath:database/h2/calendar-data.sql")
            .build();
    return database;
}
项目:springboot-copy    文件:MasterDataSourceConfig.java   
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    return dataSource;
}
项目:holon-datastore-jpa    文件:ExampleJpaDatastoreSpring.java   
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    emf.setPackagesToScan("com.exmaple.test.entities");
    return emf;
}
项目:EasyTransaction    文件:DefaultTransStatusLoggerImpl.java   
@Override
public Boolean checkTransactionStatus(String appId, String busCode, String trxId) {

    DataSource dataSource = selctor.selectDataSource(appId, busCode, trxId);
    JdbcTemplate jdbcTemplate = getJdbcTemplate(dataSource);

    //select * for update
    List<Integer> statusList = jdbcTemplate.queryForList("select status from executed_trans where app_id = ? and bus_code = ? and trx_id = ? for update;", new Object[]{appId,busCode,trxId}, Integer.class);

    if(statusList == null || statusList.size() == 0) {
        return false;
    } else {
        //it can only be 1 record,because it's search by primary key
        int status = statusList.get(0);

        switch(status){
        case TransactionStatus.UNKNOWN:
            //parent transaction status unknown
            return null;
        case TransactionStatus.COMMITTED:
            //success
            return true;
        case TransactionStatus.ROLLBACKED:
            return false;
        default:
            throw new IllegalArgumentException("unknown transaction status:" + status);
        }
    }
}
项目:plugin-bt-jira    文件:JiraExportPluginResource.java   
/**
 * Return a simple export data without any computation.
 * 
 * @param subscription
 *            The subscription identifier.
 * @return the SLA configuration
 */
protected JiraSimpleExport getSimpleData(final int subscription) {

    // Find the project corresponding to the given JIRA project
    final long start = System.currentTimeMillis();
    final Map<String, String> parameters = subscriptionResource.getParameters(subscription);
    final int jira = Integer.parseInt(parameters.get(JiraBaseResource.PARAMETER_PROJECT));
    final String pkey = parameters.get(JiraBaseResource.PARAMETER_PKEY);
    final DataSource dataSource = getDataSource(parameters);

    // Get issues of this project
    log.info("Get issues of {}({})", pkey, jira);
    final List<JiraIssueRow> issues = jiraDao.getIssues(dataSource, jira, pkey);
    log.info("Retrieved changes : {}", issues.size());

    final Map<Integer, String> statusText = jiraDao.getStatuses(dataSource);
    final Map<Integer, String> priorityText = jiraDao.getPriorities(dataSource);
    final Map<Integer, String> resolutionText = jiraDao.getResolutions(dataSource);
    final Map<Integer, String> typeText = jiraDao.getTypes(dataSource, jira);
    log.info("Fetch done of {} for {} issues, {} status, {} priorities, {} types, {} resolutions", subscription,
            issues.size(), statusText.size(), priorityText.size(), typeText.size(), resolutionText.size());

    final JiraSimpleExport jiraComputations = new JiraSimpleExport();
    jiraComputations.setIssues(issues);
    jiraComputations.setStatusText(statusText);
    jiraComputations.setPriorityText(priorityText);
    jiraComputations.setResolutionText(resolutionText);
    jiraComputations.setTypeText(typeText);
    log.info("End of simple export, took {}",
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));
    return jiraComputations;
}
项目:druid-spring-boot    文件:DruidDataSourceInitializer.java   
private void runScripts(List<Resource> resources, String username, String password) {
    if (resources.isEmpty()) {
        return;
    }
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(this.properties.isContinueOnError());
    populator.setSeparator(this.properties.getSeparator());
    if (this.properties.getSqlScriptEncoding() != null) {
        populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
    }
    for (Resource resource : resources) {
        populator.addScript(resource);
    }
    DataSource dataSource = this.dataSource;
    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
                .driverClassName(this.properties.determineDriverClassName())
                .url(this.properties.determineUrl()).username(username)
                .password(password).build();
    }
    DatabasePopulatorUtils.execute(populator, dataSource);
}
项目:microservices-tcc-alfa    文件:AuthorizationServerConfiguration.java   
@Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
    DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    initializer.setDatabasePopulator(databasePopulator());
    return initializer;
}
项目:SpringMvcLoginSecureExample    文件:SpringConfig.java   
@Bean
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));
    dataSource.setPassword(env.getProperty("spring.datasource.password"));
    return dataSource;
}
项目:spring-i18n-support    文件:WebappConfig.java   
@Bean
public DataSource dataSource() {
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2)
                                 .addScript("/jdbc/schema.sql")
                                 .addScript("/jdbc/data.sql")
                                 .build();
    return db;
}
项目:xm-ms-entity    文件:DatabaseConfiguration.java   
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
                                                                   MultiTenantConnectionProvider multiTenantConnectionProviderImpl,
                                                                   CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl,
                                                                   LocalValidatorFactoryBean localValidatorFactoryBean) {
    Map<String, Object> properties = new HashMap<>();
    properties.putAll(jpaProperties.getHibernateProperties(dataSource));
    properties.put(org.hibernate.cfg.Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
    properties
        .put(org.hibernate.cfg.Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl);
    properties
        .put(org.hibernate.cfg.Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl);

    properties.put(JPA_VALIDATION_FACTORY, localValidatorFactoryBean);

    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan(JPA_PACKAGES);
    em.setJpaVendorAdapter(jpaVendorAdapter());
    em.setJpaPropertyMap(properties);
    return em;
}
项目:lams    文件:DataSourceUtils.java   
/**
 * Determine the connection synchronization order to use for the given
 * DataSource. Decreased for every level of nesting that a DataSource
 * has, checked through the level of DelegatingDataSource nesting.
 * @param dataSource the DataSource to check
 * @return the connection synchronization order to use
 * @see #CONNECTION_SYNCHRONIZATION_ORDER
 */
private static int getConnectionSynchronizationOrder(DataSource dataSource) {
    int order = CONNECTION_SYNCHRONIZATION_ORDER;
    DataSource currDs = dataSource;
    while (currDs instanceof DelegatingDataSource) {
        order--;
        currDs = ((DelegatingDataSource) currDs).getTargetDataSource();
    }
    return order;
}
项目:monarch    文件:BlockingTimeOutJUnitTest.java   
private static void createTable(String tableName) throws Exception {
  Context ctx = cache.getJNDIContext();
  DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
  String sql = "create table " + tableName
      + " (id integer NOT NULL, name varchar(50), CONSTRAINT the_key PRIMARY KEY(id))";
  logger.debug(sql);
  Connection conn = ds.getConnection();
  Statement sm = conn.createStatement();
  sm.execute(sql);
  sm.close();
  sm = conn.createStatement();
  for (int i = 1; i <= 10; i++) {
    sql = "insert into " + tableName + " values (" + i + ",'name" + i + "')";
    sm.addBatch(sql);
    logger.debug(sql);
  }
  sm.executeBatch();
  conn.close();
}
项目:springuni-particles    文件:AbstractJpaRepositoryConfiguration.java   
/**
 * Creates the entity manager factory.
 *
 * @param dataSource the data source to use
 * @return entity manager factory
 */
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
  LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
      new LocalContainerEntityManagerFactoryBean();

  entityManagerFactoryBean.setDataSource(dataSource);

  JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter();
  entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);

  Map<String, String> jpaPropertyMap = getJpaPropertyMap();
  entityManagerFactoryBean.setJpaPropertyMap(jpaPropertyMap);

  getMappingResources().ifPresent(entityManagerFactoryBean::setMappingResources);
  getPackagesToScan().ifPresent(entityManagerFactoryBean::setPackagesToScan);

  // https://hibernate.atlassian.net/browse/HHH-5303#comment-44439
  entityManagerFactoryBean.setSharedCacheMode(ENABLE_SELECTIVE);

  customizeEntityManagerFactoryBean(entityManagerFactoryBean);

  return entityManagerFactoryBean;
}
项目:bean-searcher    文件:SearchPlugin.java   
@Override
public boolean start() {
    if (scanPackage == null) {
        throw new RuntimeException("SearchPlugin: scanPackage 不能为 空!");
    }
    DataSource dataSource = dataSourceProvider.getDataSource();
    if (dataSource == null) {
        throw new RuntimeException("Can not get DataSource from IDataSourceProvider, "
                + "please confirm IDataSourceProvider is in front of SearchPlugin");
    }
    Ioc.add(Searcher.class, SearcherBuilder.builder()
            .configSearchSqlExecutor(new MainSearchSqlExecutor(dataSource))
            .build());
    if (scanJar != null) {
        return starter.start(scanJar, scanPackage);
    } else {
        return starter.start(scanPackage);
    }
}
项目:OftenPorter    文件:MyBatisBridge.java   
/**
 * @param dataSourceClass {@linkplain DataSource}实现类.
 * @param properties
 * @return
 */
public static DataSource buildDataSource(String dataSourceClass, Properties properties)
{
    try
    {
        Class<?> clazz = PackageUtil.newClass(dataSourceClass, null);
        DataSource dataSource = (DataSource) WPTool.newObject(clazz);
        DataSourceFactory factory = new TempFactory(dataSource);
        factory.setProperties(properties);
        return factory.getDataSource();
    } catch (Exception e)
    {
        throw new DBException(e);
    }
}
项目:springboot    文件:ClusterDataSourceConfig.java   
@Bean(name = "clusterDataSource")
public DataSource ClusterDataSource(){
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(url);
    datasource.setUsername(user);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClass);
    return datasource;
}
项目:Spring-Security-Third-Edition    文件:DataSourceConfig.java   
/**
 * Embedded H2 database
 * Connect to running database with the following details:
 *
 * URL: jdbc:h2:mem:dataSource
 * Driver Class: org.h2.Driver
 * Username: sa
 * Password: [blank]
 *
 * @return
 */
@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    database = builder.setType(EmbeddedDatabaseType.H2)
            .setName("dataSource")
            .ignoreFailedDrops(true)
            .continueOnError(false)
            .addScript("classpath:database/h2/calendar-schema.sql")
            .addScript("classpath:database/h2/calendar-data.sql")
            .build();
    return database;
}
项目:org.ops4j.pax.transx    文件:ManagedDataSourceBuilder.java   
private static AbstractJdbcManagedConnectionFactory<?, ?, ?> create(CommonDataSource dataSource) {
    if (dataSource instanceof XADataSource) {
        return new XADataSourceMCF((XADataSource) dataSource);
    }
    else if (dataSource instanceof ConnectionPoolDataSource) {
        return new ConnectionPoolDataSourceMCF((ConnectionPoolDataSource) dataSource);
    }
    else if (dataSource instanceof DataSource) {
        return new LocalDataSourceMCF((DataSource) dataSource);
    }
    else {
        throw new UnsupportedOperationException();
    }
}
项目:Agent-Benchmarks    文件:DataSourceConfiguration.java   
@Bean
@Primary
public DataSource getDataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName("com.mysql.jdbc.Driver");
    config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    config.setUsername("root");
    config.setPassword("root");
    config.setMaximumPoolSize(500);
    config.setMinimumIdle(10);
    return new HikariDataSource(config);
}
项目:monarch    文件:TransactionTimeOutJUnitTest.java   
@Test
public void test7Commit() throws Exception {
  Context ctx = cache.getJNDIContext();
  DataSource ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
  ds2.getConnection();
  GemFireTransactionDataSource ds =
      (GemFireTransactionDataSource) ctx.lookup("java:/XAPooledDataSource");
  UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
  utx.begin();
  Connection conn = ds.getConnection();
  String sql = "create table newTable1 (id integer)";
  Statement sm = conn.createStatement();
  sm.execute(sql);
  utx.setTransactionTimeout(30);
  Thread.sleep(5000);
  utx.setTransactionTimeout(20);
  utx.setTransactionTimeout(10);
  sql = "insert into newTable1  values (1)";
  sm.execute(sql);
  utx.commit();
  sql = "select * from newTable1 where id = 1";
  ResultSet rs = sm.executeQuery(sql);
  if (!rs.next()) {
    fail("Transaction not committed");
  }
  sql = "drop table newTable1";
  sm.execute(sql);
  sm.close();
  conn.close();
}
项目:traccar-service    文件:WebServer.java   
public WebServer(Config config, DataSource dataSource) {
    this.config = config;
    this.dataSource = dataSource;

    sessionManager = new HashSessionManager();
    int sessionTimeout = config.getInteger("web.sessionTimeout");
    if (sessionTimeout != 0) {
        sessionManager.setMaxInactiveInterval(sessionTimeout);
    }

    initServer();
    initApi();
    if (config.getBoolean("web.console")) {
        initConsole();
    }
    switch (config.getString("web.type", "new")) {
        case "old":
            initOldWebApp();
            break;
        default:
            initWebApp();
            break;
    }
    initClientProxy();
    server.setHandler(handlers);

    server.addBean(new ErrorHandler() {
        @Override
        protected void handleErrorPage(
                HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>"
                    + code + " - " + HttpStatus.getMessage(code) + "</body></html>");
        }
    }, false);
}
项目:rjb-blog-multitenancy    文件:MultiTenantDataSourceConfig.java   
@Bean
public DataSource dataSource() {
    MultiTenantDataSource returnVal = new MultiTenantDataSource(contextConfig.tenantResolver());
    Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
    targetDataSources.putAll(propertiesConfig.getTenantJndiDataSourceMappings());
    returnVal.setTargetDataSources(targetDataSources);
    returnVal.setLenientFallback(false);
    return returnVal;
}
项目:otus_java_2017_10    文件:MainAnnotationsExample.java   
private DataSource getH2DataSource() {
    PooledDataSource ds = new PooledDataSource();

    ds.setDriver("org.h2.Driver");
    ds.setUrl("jdbc:h2:mem:test");
    ds.setUsername("sa");

    return ds;
}
项目:spring-cloud-dashboard    文件:DataflowRdbmsInitializer.java   
private String getDatabaseType(DataSource dataSource) {
    try {
        return DatabaseType.fromMetaData(dataSource).toString().toLowerCase();
    }
    catch (MetaDataAccessException ex) {
        throw new IllegalStateException("Unable to detect database type", ex);
    }
}
项目:spring-boot-data-source-decorator    文件:ProxyDataSourceConfigurationTests.java   
@Test
public void testRegisterLogAndSlowQueryLogUsingSlf4j() throws Exception {
    EnvironmentTestUtils.addEnvironment(context,
            "decorator.datasource.datasource-proxy.logging:slf4j");
    context.register(DataSourceAutoConfiguration.class,
            DataSourceDecoratorAutoConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class);
    context.refresh();

    DataSource dataSource = context.getBean(DataSource.class);
    ProxyDataSource proxyDataSource = (ProxyDataSource) ((DecoratedDataSource) dataSource).getDecoratedDataSource();
    ChainListener chainListener = proxyDataSource.getProxyConfig().getQueryListener();
    assertThat(chainListener.getListeners()).extracting("class").contains(SLF4JSlowQueryListener.class);
    assertThat(chainListener.getListeners()).extracting("class").contains(SLF4JQueryLoggingListener.class);
}
项目:elastic-job-example    文件:JavaMain.java   
private static DataSource setUpEventTraceDataSource() {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(EVENT_RDB_STORAGE_DRIVER);
    result.setUrl(EVENT_RDB_STORAGE_URL);
    result.setUsername(EVENT_RDB_STORAGE_USERNAME);
    result.setPassword(EVENT_RDB_STORAGE_PASSWORD);
    return result;
}
项目:lams    文件:LocalSessionFactoryBean.java   
/**
 * Execute schema update script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaUpdate class, for automatically executing schema update scripts
 * on application startup. Can also be invoked manually.
 * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}.
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws DataAccessException in case of script execution errors
 * @see #setSchemaUpdate
 * @see org.hibernate.cfg.Configuration#generateSchemaUpdateScript
 * @see org.hibernate.tool.hbm2ddl.SchemaUpdate
 */
public void updateDatabaseSchema() throws DataAccessException {
    logger.info("Updating database schema for Hibernate SessionFactory");
    DataSource dataSource = getDataSource();
    if (dataSource != null) {
        // Make given DataSource available for the schema update.
        configTimeDataSourceHolder.set(dataSource);
    }
    try {
        SessionFactory sessionFactory = getSessionFactory();
        final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
        HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
        hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
        hibernateTemplate.execute(
            new HibernateCallback<Object>() {
                @Override
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    @SuppressWarnings("deprecation")
                    Connection con = session.connection();
                    DatabaseMetadata metadata = new DatabaseMetadata(con, dialect);
                    String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata);
                    executeSchemaScript(con, sql);
                    return null;
                }
            }
        );
    }
    finally {
        if (dataSource != null) {
            configTimeDataSourceHolder.remove();
        }
    }
}
项目:curiostack    文件:DatabaseModule.java   
@Provides
@Singleton
static DataSource dataSource(DatabaseConfig config) {
  HikariConfig hikari = new HikariConfig();
  hikari.setJdbcUrl(config.getJdbcUrl());
  hikari.setUsername(config.getUsername());
  hikari.setPassword(config.getPassword());
  hikari.addDataSourceProperty("cachePrepStmts", "true");
  hikari.addDataSourceProperty(
      "statementInterceptors", "brave.mysql.TracingStatementInterceptor");
  hikari.addDataSourceProperty("useUnicode", "yes");
  hikari.setMetricsTrackerFactory(new PrometheusMetricsTrackerFactory());
  return new HikariDataSource(hikari);
}
项目:spring-data-examples    文件:OrderConfig.java   
@Bean
DataSource orderDataSource() {

    return new EmbeddedDatabaseBuilder().//
            setType(EmbeddedDatabaseType.HSQL).//
            setName("orders").//
            build();
}
项目:spring-boot-data-source-decorator    文件:FlexyPoolConfigurationTests.java   
@SuppressWarnings("unchecked")
private <T extends DataSource> FlexyPoolDataSource<T> assertDataSourceOfType(DataSource dataSource, Class<T> realDataSourceClass) {
    assertThat(dataSource).isInstanceOf(DecoratedDataSource.class);
    DataSource decoratedDataSource = ((DecoratedDataSource) dataSource).getDecoratedDataSource();
    assertThat(decoratedDataSource).isInstanceOf(FlexyPoolDataSource.class);
    Field field = ReflectionUtils.findField(FlexyPoolDataSource.class, "targetDataSource");
    ReflectionUtils.makeAccessible(field);
    Object targetDataSource = ReflectionUtils.getField(field, decoratedDataSource);
    assertThat(targetDataSource).isInstanceOf(realDataSourceClass);
    return (FlexyPoolDataSource<T>) decoratedDataSource;
}