Java Code Examples for javax.sql.DataSource

The following are top voted examples for showing how to use javax.sql.DataSource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SpringBoot-Study   File: ClusterDruidDataSourceConfig.java   Source Code and License 7 votes vote down vote up
/**
 * 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();
}
 
Example 2
Project: org.ops4j.pax.transx   File: HsqlTest.java   Source Code and License 6 votes vote down vote up
@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;
    }
}
 
Example 3
Project: uavstack   File: MybatisHookProxy.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 4
Project: otter-G   File: DataSourceCreator.java   Source Code and License 6 votes vote down vote up
/**
 * 扩展功能,可以自定义一些自己实现的 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;
}
 
Example 5
Project: DHIS2-fhir-lab-app   File: FhirServerConfigDstu3.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: lams   File: LocalSessionFactoryBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
		}
	}
}
 
Example 7
Project: xm-ms-balance   File: DatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 8
Project: lams   File: DataSourceUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 9
Project: angit   File: DatasourceConfig.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 10
Project: My-Blog   File: TaleUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 获取新的数据源
 *
 * @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;
}
 
Example 11
Project: Spring-Security-Third-Edition   File: DataSourceConfig.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: springboot-copy   File: MasterDataSourceConfig.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 13
Project: holon-datastore-jpa   File: ExampleJpaDatastoreSpring.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 14
Project: EasyTransaction   File: DefaultTransStatusLoggerImpl.java   Source Code and License 5 votes vote down vote up
@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);
		}
	}
}
 
Example 15
Project: plugin-bt-jira   File: JiraExportPluginResource.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: druid-spring-boot   File: DruidDataSourceInitializer.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 17
Project: microservices-tcc-alfa   File: AuthorizationServerConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
	DataSourceInitializer initializer = new DataSourceInitializer();
	initializer.setDataSource(dataSource);
	initializer.setDatabasePopulator(databasePopulator());
	return initializer;
}
 
Example 18
Project: SpringMvcLoginSecureExample   File: SpringConfig.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 19
Project: spring-i18n-support   File: WebappConfig.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 20
Project: xm-ms-entity   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 21
Project: lams   File: DataSourceUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: monarch   File: BlockingTimeOutJUnitTest.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 23
Project: springuni-particles   File: AbstractJpaRepositoryConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 24
Project: bean-searcher   File: SearchPlugin.java   Source Code and License 5 votes vote down vote up
@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);
	}
}
 
Example 25
Project: OftenPorter   File: MyBatisBridge.java   Source Code and License 5 votes vote down vote up
/**
 * @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);
    }
}
 
Example 26
Project: simple-openid-provider   File: JdbcClientRepositoryIntegrationTests.java   Source Code and License 5 votes vote down vote up
@Bean
DataSource dataSource() {
	// @formatter:off
	return new EmbeddedDatabaseBuilder()
			.generateUniqueName(true)
			.setType(EmbeddedDatabaseType.H2)
			.addScript("schema-clients.sql")
			.build();
	// @formatter:on
}
 
Example 27
Project: springboot   File: ClusterDataSourceConfig.java   Source Code and License 5 votes vote down vote up
@Bean(name = "clusterDataSource")
public DataSource ClusterDataSource(){
	DruidDataSource datasource = new DruidDataSource();
	datasource.setUrl(url);
	datasource.setUsername(user);
	datasource.setPassword(password);
	datasource.setDriverClassName(driverClass);
	return datasource;
}
 
Example 28
Project: Spring-Security-Third-Edition   File: DataSourceConfig.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Project: org.ops4j.pax.transx   File: ManagedDataSourceBuilder.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 30
Project: Agent-Benchmarks   File: DataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 31
Project: monarch   File: TransactionTimeOutJUnitTest.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 32
Project: traccar-service   File: WebServer.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 33
Project: rjb-blog-multitenancy   File: MultiTenantDataSourceConfig.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 34
Project: otus_java_2017_10   File: MainAnnotationsExample.java   Source Code and License 5 votes vote down vote up
private DataSource getH2DataSource() {
    PooledDataSource ds = new PooledDataSource();

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

    return ds;
}
 
Example 35
Project: spring-cloud-dashboard   File: DataflowRdbmsInitializer.java   Source Code and License 5 votes vote down vote up
private String getDatabaseType(DataSource dataSource) {
	try {
		return DatabaseType.fromMetaData(dataSource).toString().toLowerCase();
	}
	catch (MetaDataAccessException ex) {
		throw new IllegalStateException("Unable to detect database type", ex);
	}
}
 
Example 36
Project: spring-boot-data-source-decorator   File: ProxyDataSourceConfigurationTests.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 37
Project: elastic-job-example   File: JavaMain.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 38
Project: curiostack   File: DatabaseModule.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 39
Project: spring-data-examples   File: OrderConfig.java   Source Code and License 5 votes vote down vote up
@Bean
DataSource orderDataSource() {

	return new EmbeddedDatabaseBuilder().//
			setType(EmbeddedDatabaseType.HSQL).//
			setName("orders").//
			build();
}
 
Example 40
Project: spring-boot-data-source-decorator   File: FlexyPoolConfigurationTests.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 41
Project: shoucang   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 42
Project: bnade-server   File: DBUtils.java   Source Code and License 5 votes vote down vote up
public static DataSource getDataSource() {
	if (dataSource == null) {
		try {
			dataSource = DruidDataSourceFactory.createDataSource(loadPropertyFile(configFile));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	return dataSource;
}
 
Example 43
Project: lams   File: SqlScriptMigrationTaskTest.java   Source Code and License 5 votes vote down vote up
/**
    * Test that sybase database patches are committed when illegal multi
    * statement transaction commands are used.
    * 
    * @throws IOException
    *                 if an unexpected error occurs
    * @throws MigrationException
    *                 if an unexpected error occurs
    * @throws SQLException
    *                 if an unexpected error occurs
    */
   public void testSybasePatchesCommitsOnEveryStatement() throws IOException,
    MigrationException, SQLException
   {
InputStream is = getClass().getResourceAsStream("test/sybase_tsql.sql");
assertNotNull(is);
task = new SqlScriptMigrationTask("sybase_tsql.sql", 1, is);

MockDatabaseType dbType = new MockDatabaseType("sybase");
dbType.setMultipleStatementsSupported(false);
context.setDatabaseType(dbType);
int numStatements = task.getSqlStatements(context).size();

// setup mocks to verify commits are called
MockControl dataSourceControl = MockControl
	.createControl(DataSource.class);
DataSource dataSource = (DataSource) dataSourceControl.getMock();
context.setDataSource(dataSource);

MockControl connectionControl = MockControl
	.createControl(Connection.class);
Connection connection = (Connection) connectionControl.getMock();

dataSourceControl.expectAndReturn(dataSource.getConnection(),
	connection);

MockControl statementControl = MockControl
	.createControl(Statement.class);
Statement statement = (Statement) statementControl.getMock();
statement.execute("");
statementControl.setMatcher(MockControl.ALWAYS_MATCHER);
statementControl.setReturnValue(true, MockControl.ONE_OR_MORE);
statementControl.expectAndReturn(statement.isClosed(), false, MockControl.ONE_OR_MORE);
statement.close();
statementControl.setVoidCallable(MockControl.ONE_OR_MORE);

connectionControl.expectAndReturn(connection.isClosed(), false,
	MockControl.ONE_OR_MORE);
connectionControl.expectAndReturn(connection.createStatement(),
	statement, numStatements);
connectionControl.expectAndReturn(connection.getAutoCommit(), false,
	MockControl.ONE_OR_MORE);
connection.commit();
/*
 * Magic Number 4 derived from the assumption that the fixture sql
 * contains only one statement that is not allowed in a multi statement
 * transaction: commit at beginning of migrate method commit prior to
 * running the command not allowed in multi statement transaction to
 * clear the transaction state. commit after running the multi statement
 * transaction to clear transaction state for upcoming statements.
 * commit at end of migrate method once all statements executed.
 * 
 * Therefore, if you add more illegal statements to the fixture, add 2
 * more commit call's for each illegal statement.
 */
connectionControl.setVoidCallable(4);

dataSourceControl.replay();
connectionControl.replay();
statementControl.replay();

// run tests
task.migrate(context);
dataSourceControl.verify();
connectionControl.verify();
   }
 
Example 44
Project: drinkwater-java   File: JndiSqlDataStore.java   Source Code and License 5 votes vote down vote up
@Override
public void configure() throws Exception {
    Context jndiContext = new InitialContext();
    if(migrationJndiLookupName == null){
        migrationJndiLookupName = jndiLookupName;
    }
    migrationDataSource = (DataSource)jndiContext.lookup(migrationJndiLookupName);
    dataSource = (DataSource)jndiContext.lookup(jndiLookupName);
}
 
Example 45
Project: beadledom   File: ThreadLocalJooqModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure() {
  requireBinding(DataSource.class);
  requireBinding(SQLDialect.class);

  bind(DSLContextProviderImpl.class).in(Singleton.class);
  bind(DSLContextProvider.class).to(DSLContextProviderImpl.class);
  bind(UnitOfWork.class).to(DSLContextProviderImpl.class);

  final JooqTxnInterceptor txnInterceptor = new JooqTxnInterceptor();
  requestInjection(txnInterceptor);

  bindInterceptor(any(), annotatedWith(JooqTransactional.class), txnInterceptor);
  bindInterceptor(annotatedWith(JooqTransactional.class), any(), txnInterceptor);
}
 
Example 46
Project: springboot-multi-datasource   File: DataSource2Config.java   Source Code and License 4 votes vote down vote up
@Bean(name = "test2DataSource")
@ConfigurationProperties(prefix = "test2")
public DataSource testDataSource() {
    return DataSourceBuilder.create().build();
}
 
Example 47
Project: bean-searcher   File: MainSearchSqlExecutor.java   Source Code and License 4 votes vote down vote up
public MainSearchSqlExecutor(DataSource dataSource) {
	this.dataSource = dataSource;
}
 
Example 48
Project: org.ops4j.pax.transx   File: H2Test.java   Source Code and License 4 votes vote down vote up
private DataSource wrap(XADataSource xaDs) throws Exception {
    return wrap(xaDs, 0);
}
 
Example 49
Project: spring-boot-oauth2-demo   File: DatasourceConfig.java   Source Code and License 4 votes vote down vote up
@Bean(name = "datasourceTest")
@ConfigurationProperties(prefix = "datasource.test")
public DataSource dataSourceTest() {
    return DataSourceBuilder.create().build();
}
 
Example 50
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@Primary
public DataSource dataSource(@Qualifier("dataSourceProperties") DataSourceProperties properties) {
	return properties.initializeDataSourceBuilder().build();
}
 
Example 51
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T createDataSource(DataSourceProperties properties,
		Class<? extends DataSource> type) {
	return (T) properties.initializeDataSourceBuilder().type(type).build();
}
 
Example 52
Project: amanda   File: RootContextConfiguration.java   Source Code and License 4 votes vote down vote up
public DataSource getDataSource() {
    return dataSource;
}
 
Example 53
Project: FCat   File: MybatisConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}
 
Example 54
Project: EasyTransaction   File: EasyTransTestConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public JdbcTemplate buySthJdbcTemplate(DataSource buySth){
	return new JdbcTemplate(buySth);
}
 
Example 55
Project: obevo   File: SimpleCatoDatabaseProperties.java   Source Code and License 4 votes vote down vote up
public void setCompareConnSource(DataSource compareConnSource) {
    this.compareConnSource = compareConnSource;
}
 
Example 56
Project: taboola-cronyx   File: QuartzDirectDBAccessService.java   Source Code and License 4 votes vote down vote up
public QuartzDirectDBAccessService(DataSource dataSource, SchedulingService scheduler, String schedulerName) {
    this.dataSource = dataSource;
    this.scheduler = scheduler;
    this.schedulerName = schedulerName;
}
 
Example 57
Project: SpringBootCRUD   File: DatabaseConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public AbstractEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.mrpehlivan").build();
}
 
Example 58
Project: data-migration   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@Qualifier("mybatisReadDataSource01")
@ConfigurationProperties(prefix = "mybatis.datasource.read01")
public DataSource createMybatisReadDataSource() {
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example 59
Project: bdf2   File: EntityPR.java   Source Code and License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Expose
public Collection<ColumnDef> buildSQLFields(Map<String,Object> map) throws Exception{
	String querySql=(String)map.get("querySql");
	querySql=parseQuerySql(querySql,map);
	final String tableName=(String)map.get("tableName");
	Collection<Map<String,Object>> parameters=(Collection<Map<String,Object>>)map.get("parameters");
	MapSqlParameterSource sqlParameters=new MapSqlParameterSource();
	if(parameters!=null){
		for(Map<String,Object> pmap:parameters){
			sqlParameters.addValue((String)pmap.get("name"), pmap.get("value"));
		}
	}
	final List<String> primaryKeyList=this.loadTablePrimaryKeys(tableName);
	
	DataSource ds=this.getJdbcTemplate().getDataSource();
	Connection con = DataSourceUtils.getConnection(ds);
	Collection<ColumnDef> columns=null;
	try{
		final DatabaseMetaData databaseMetaData=con.getMetaData();
		columns=this.getNamedParameterJdbcTemplate().query(querySql, sqlParameters, new ResultSetExtractor<Collection<ColumnDef>>(){
			public Collection<ColumnDef> extractData(ResultSet rs) throws SQLException,DataAccessException {
				Collection<ColumnDef> result=new ArrayList<ColumnDef>();
				ResultSetMetaData rsmd = rs.getMetaData();
				int count = rsmd.getColumnCount();
				for (int i = 1; i <= count; i++) {
					ColumnDef col=new ColumnDef();
					col.setTableName(rsmd.getTableName(i));
					col.setName(rsmd.getColumnName(i));
					int columnType=rsmd.getColumnType(i);
					String type="String";
					if(columnType==Types.INTEGER || columnType ==Types.BIGINT || columnType==Types.SMALLINT || columnType==Types.TINYINT){
						type="int";
					}else if(columnType==Types.BOOLEAN){
						type="Boolean";
					}else if(columnType==Types.DATE){
						type="Date";
					}else if(columnType==Types.TIMESTAMP){
						type="DateTime";
					}else if(columnType==Types.TIME){
						type="Time";
					}else if(columnType==Types.DECIMAL || columnType==Types.NUMERIC){
						type="BigDecimal";
					}else if(columnType==Types.FLOAT){
						type="Float";
					}else if(columnType==Types.DOUBLE){
						type="double";
					}
					col.setLabel(getColumnRemarks(col.getTableName(),col.getName(),databaseMetaData));
					setPrimaryKey(col,tableName,primaryKeyList);
					col.setType(type);
					result.add(col);
				}
				return result;
			}
		});
		
	}finally{
		JdbcUtils.closeConnection(con);	
	}
	return columns;
}
 
Example 60
Project: vertx-jpa   File: DefaultPersistenceUnitInfoImpl.java   Source Code and License 4 votes vote down vote up
public void setNonJtaDataSource(DataSource nonJtaDataSource) {
  this.nonJtaDataSource = nonJtaDataSource;
}