Java Code Examples for org.springframework.jdbc.datasource.SingleConnectionDataSource

The following are top voted examples for showing how to use org.springframework.jdbc.datasource.SingleConnectionDataSource. 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: sample-schedule-job-admin   File: JobsRestful.java   Source Code and License 6 votes vote down vote up
private boolean validateSQL(JobVO jobVO) {
	SingleConnectionDataSource ds = new SingleConnectionDataSource();
	try {
		ds.setDriverClassName(jobVO.getDriverClassName());
		ds.setUrl(jobVO.getUrl());
		ds.setUsername(jobVO.getUsername());
		ds.setPassword(jobVO.getPassword());
		JdbcTemplate template = new JdbcTemplate(ds);
		template.execute(jobVO.getSql());
		return true;
	} catch (Throwable t) {
		return false;
	} finally {
		ds.destroy();
	}
}
 
Example 2
Project: spring4-understanding   File: JdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example 3
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 6 votes vote down vote up
public String executeSql(String sql,String code) throws Exception {
   	SingleConnectionDataSource ds = getSingleConnectionDataSource(code);
   	this.setRtJdbcTemplate(ds);
   	String result;
	try {
		result = (String)this.rtJdbcTemplate.queryForObject(sql,null,java.lang.String.class);
		return result;
	} catch (Exception e) {
		log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" + e);
		throw new Exception(e.getMessage());
	}
	finally{
		ds.getConnection().close();
	}
   	
	
}
 
Example 4
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 6 votes vote down vote up
public SingleConnectionDataSource getSingleConnectionDataSource(String code) throws Exception {

      //String sql ="select t2.DRIVER_CLASS as driver,t2.url ,t2.user_name ,t2.password from SYS_DATA_SOURCE t1,sys_db_links t2 where t1.link_id=t2.link_id and t1.code='"+code+"'";
  	String sql ="select t2.DRIVER_CLASS as driver,t2.url ,t2.user_name ,t2.password from SYS_DATA_SOURCE t1,sys_db_links t2 where t1.link_id=t2.link_id and t1.sh_code='"+code+"'";

  	List<Map<String,Object>> list = (List<Map<String,Object>>)this.jdbcTemplate.queryForList(sql);
   	Map<String,Object> map = new HashMap<String,Object>();
  	if(list.size()>0){
         map = list.get(0);
       }
      SingleConnectionDataSource ds = new SingleConnectionDataSource();
  	
      ds.setDriverClassName(ParseUtil.getString(map.get("driver")));
      ds.setUrl(ParseUtil.getString(map.get("url")));
      ds.setUsername(ParseUtil.getString(map.get("user_name")));
      ds.setPassword(ParseUtil.getString(map.get("password")));
	
	return ds;
}
 
Example 5
Project: openid4java   File: JdbcNonceVerifierTest.java   Source Code and License 6 votes vote down vote up
@Override
public NonceVerifier createVerifier(int maxAge) {
	DataSource dataSource = new SingleConnectionDataSource(
			"org.hsqldb.jdbcDriver",
			"jdbc:hsqldb:mem:saasstore_security_client", "sa", "", true);
	SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	jdbcTemplate.getJdbcOperations().execute(
			"DROP TABLE IF EXISTS openid_nonce;");
	jdbcTemplate
			.getJdbcOperations()
			.execute(
					"CREATE TABLE openid_nonce (  "
							+ "opurl varchar(255) NOT NULL,  nonce varchar(25) NOT NULL,  "
							+ "date datetime DEFAULT NULL,  PRIMARY KEY (opurl,nonce))");

	JdbcNonceVerifier jdbcNonceVerifier = new JdbcNonceVerifier(maxAge,
			"openid_nonce");
	jdbcNonceVerifier.setDataSource(dataSource);
	return jdbcNonceVerifier;
}
 
Example 6
Project: javalab   File: UserDaoCodeDITest.java   Source Code and License 6 votes vote down vote up
@Test
@DirtiesContext
public void addAndGet() throws SQLException {
	DataSource dataSource = new SingleConnectionDataSource(
			"jdbc:mysql://54.64.47.206/mykumitestdb","dbuser", "dbuser1*",true);
	jdbcContext.setDataSource(dataSource);
	JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	userDao.setJdbcTemplate(jdbcTemplate);
	
	userDao.deleteAll();
	assertThat(userDao.getCount(), is(0));
	
	User user = new User("u1", "user01", "111111", Level.BASIC,1,0);

	userDao.add(user);
	assertThat(userDao.getCount(), is(1));
	
	User user2 = userDao.get(user.getId());
	
	assertThat(user.getName(), is(user2.getName()));
	assertThat(user.getPassword(), is(user2.getPassword()));
}
 
Example 7
Project: booties   File: PostgreSqlRule.java   Source Code and License 6 votes vote down vote up
private void applyScripts(String url) throws SQLException, IOException {
    log.info("Apply Scripts ...");
    Connection connection = getConnection(url);
    DataSource ds = new SingleConnectionDataSource(connection, false);
    FileSystemScanner scanner = new FileSystemScanner();
    for (String location : builder.locations) {
        File directory = new File(location);
        if (directory.exists() && directory.isDirectory()) {
            Resource[] resources = scanner.scanForResources(location, "", ".sql");
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resources);
            populator.setSeparator(builder.separator);
            populator.execute(ds);
        } else {
            // log not existing directory
        }
    }
    log.info("Scripts applied!");
}
 
Example 8
Project: SimpleFlatMapper   File: Sql2oIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSql2O() throws SQLException, ParseException {
    Connection connection = DbHelper.objectDb();
    try {
        SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
        Sql2o sql2o = new Sql2o(scds);

        Query query = sql2o.open().createQuery(DbHelper.TEST_DB_OBJECT_QUERY);
        query.setAutoDeriveColumnNames(true);
        query.setResultSetHandlerFactoryBuilder(new SfmResultSetHandlerFactoryBuilder());

        List<DbObject> dbObjects = query.executeAndFetch(DbObject.class);

        assertEquals(1, dbObjects.size());
        DbHelper.assertDbObjectMapping(dbObjects.get(0));

    } finally {
        connection.close();
    }
}
 
Example 9
Project: class-guard   File: JdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example 10
Project: class-guard   File: RowMapperTests.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws SQLException {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	preparedStatement = mock(PreparedStatement.class);
	resultSet = mock(ResultSet.class);
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);
	template = new JdbcTemplate();
	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example 11
Project: score   File: SimpleHiloIdentifierGenerator.java   Source Code and License 6 votes vote down vote up
private void updateCurrentChunk() {
    if (logger.isDebugEnabled()) {
        logger.debug("Updating HILO chunk...");
    }

    long t = System.currentTimeMillis();
    try (Connection conn = dataSource.getConnection()) {
        conn.setAutoCommit(false);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(conn, true));

        jdbcTemplate.update(SQL_LOCK);
        currentChunk = jdbcTemplate.queryForObject(SQL_SELECT, Integer.class);
        if (logger.isDebugEnabled())
            logger.debug("Current chunk: " + currentChunk);
        jdbcTemplate.execute(SQL_UPDATE);
        jdbcTemplate.execute("commit");

        if (logger.isDebugEnabled()) {
            logger.debug("Updating HILO chunk done in " + (System.currentTimeMillis() - t) + " ms");
        }
        currentId = 0;
    } catch (SQLException e) {
        logger.error("Unable to update current chunk", e);
        throw new IllegalStateException("Unable to update current chunk");
    }
}
 
Example 12
Project: parkandrideAPI   File: UtilizationDao.java   Source Code and License 6 votes vote down vote up
private Set<Utilization> findLatestUtilizationPostgreSQL(Long[] facilityIds, SingleConnectionDataSource dataSource) {
    NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    return new LinkedHashSet<>(jdbcTemplate.query("" +
                    "SELECT latest.* " +
                    "FROM (" +
                    "  SELECT DISTINCT facility_id, capacity_type, usage " +
                    "  FROM pricing " +
                    (facilityIds.length > 0 ? "  WHERE facility_id IN (:facility_ids) " : "") +
                    ") p " +
                    "JOIN LATERAL ( " +
                    "  SELECT * " +
                    "  FROM facility_utilization " +
                    "  WHERE facility_id = p.facility_id AND capacity_type = p.capacity_type AND usage = p.usage " +
                    "  ORDER BY ts DESC " +
                    "  LIMIT 1 " +
                    ") latest ON TRUE " +
                    "ORDER BY facility_id, capacity_type, usage",
            new MapSqlParameterSource("facility_ids", Arrays.asList(facilityIds)),
            utilizationRowMapper));
}
 
Example 13
Project: spring4-understanding   File: AbstractRowMapperTests.java   Source Code and License 5 votes vote down vote up
public Mock(MockType type)
		throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example 14
Project: spring4-understanding   File: RowMapperTests.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example 15
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceHealthIndicatorTests.java   Source Code and License 5 votes vote down vote up
@Before
public void init() {
	EmbeddedDatabaseConnection db = EmbeddedDatabaseConnection.HSQL;
	this.dataSource = new SingleConnectionDataSource(db.getUrl() + ";shutdown=true",
			"sa", "", false);
	this.dataSource.setDriverClassName(db.getDriverClassName());
}
 
Example 16
Project: spring-boot-concourse   File: DataSourceHealthIndicatorTests.java   Source Code and License 5 votes vote down vote up
@Before
public void init() {
	EmbeddedDatabaseConnection db = EmbeddedDatabaseConnection.HSQL;
	this.dataSource = new SingleConnectionDataSource(db.getUrl() + ";shutdown=true",
			"sa", "", false);
	this.dataSource.setDriverClassName(db.getDriverClassName());
}
 
Example 17
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 5 votes vote down vote up
public String executeSqlForTableDs(Map<String,String> sqlmap) throws Exception{
	String resultSql = sqlmap.get("resultSql");
	
	String trStyleStr = sqlmap.get("trStyleStr");
	
	List<String>  array = ParseUtil.parseTrStyleStr(trStyleStr);
	
	StringBuilder sb = new StringBuilder();
	
	SingleConnectionDataSource ds = getSingleConnectionDataSource(sqlmap.get("code"));
   	this.setRtJdbcTemplate(ds);
   	
	try {
		List<Map<String,Object>> list = (List<Map<String,Object>>)this.rtJdbcTemplate.queryForList(resultSql);
		
		if(list.size()>0){
			for (Map<String, Object> map : list) {
				String newStr =trStyleStr;
				for (String str :array) {
					String v = map.get(str.trim())==null?"":map.get(str.trim()).toString();
					newStr = newStr.replaceAll("\\[&SV,"+str+",&]",v);
				}
				
				sb.append(newStr);
			}
		}
		return sb.toString();
		
	} catch (Exception e) {
		log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" + e);
		throw new Exception(e.getMessage());
	}
	finally{
		ds.getConnection().close();
	}
	
	
}
 
Example 18
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 5 votes vote down vote up
public Map<String,Object> executeSqlForForm(String sql,String code) throws Exception{
   	
		
			if(!ParseUtil.isNotNullforString(sql)){
			throw new Exception("执行executeSqlForForm时sql为空!");
			}
			
			
			SingleConnectionDataSource ds = getSingleConnectionDataSource(code);
	    	this.setRtJdbcTemplate(ds);
	    	
	    	
			try {
				List<Map<String,Object>> list = (List<Map<String,Object>>)this.rtJdbcTemplate.queryForList(sql);
				if(list.size()>0){
					return list.get(0);
				}
				return null;
			} catch (Exception e) {
				log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" +e);
				throw new Exception(e.getMessage());
			}
			finally{
				ds.getConnection().close();
			}
			
		
}
 
Example 19
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 5 votes vote down vote up
/**
 * added by JBJ 根据任务参数设置寻找数据库连接信息
 * 
 * @param taskId
 * @return
 * @throws Exception
 */
public SingleConnectionDataSource getSingleConnectionDataSource(Long taskId)
		throws Exception {

	String sql = "SELECT t.param_value linkName FROM SYS_PARAM_ALL T WHERE SYSDATE BETWEEN T.ENABLE_DATE AND NVL(T.DISABLE_DATE, SYSDATE) AND t.param_name = 'DB_LINK' AND T.TASK_ID = "
			+ taskId;

	List<Map<String, Object>> list = (List<Map<String, Object>>) this.jdbcTemplate
			.queryForList(sql);
	Map<String, Object> map = new HashMap<String, Object>();
	if (list.size() > 0) {
		map = list.get(0);
	}

	String linkCode = ParseUtil.getString(map.get("linkName"));

	sql = "SELECT dl.dRIVER_CLASS as driver,dl.url ,dl.user_name ,dl.password FROM sys_db_links dl WHERE SYSDATE BETWEEN DL.ENABLE_DATE AND NVL(DL.DISABLE_DATE, SYSDATE) AND DL.LINK_CODE = '"
			+ linkCode + "'";

	list = (List<Map<String, Object>>) this.jdbcTemplate.queryForList(sql);
	map = new HashMap<String, Object>();
	if (list.size() > 0) {
		map = list.get(0);
	}

	SingleConnectionDataSource ds = new SingleConnectionDataSource();

	ds.setDriverClassName(ParseUtil.getString(map.get("driver")));
	ds.setUrl(ParseUtil.getString(map.get("url")));
	ds.setUsername(ParseUtil.getString(map.get("user_name")));
	ds.setPassword(ParseUtil.getString(map.get("password")));

	return ds;
}
 
Example 20
Project: parfait   File: ParfaitDataSourceTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws SQLException, ClassNotFoundException {
	Class.forName("org.hsqldb.jdbcDriver");
	Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:parfait", "sa", "");
	DataSource wrapped = new SingleConnectionDataSource(c, false);
	dataSource = new ParfaitDataSource(wrapped);
}
 
Example 21
Project: contestparser   File: DataSourceHealthIndicatorTests.java   Source Code and License 5 votes vote down vote up
@Before
public void init() {
	EmbeddedDatabaseConnection db = EmbeddedDatabaseConnection.HSQL;
	this.dataSource = new SingleConnectionDataSource(db.getUrl() + ";shutdown=true",
			"sa", "", false);
	this.dataSource.setDriverClassName(db.getDriverClassName());
}
 
Example 22
Project: zstack   File: ManagementNodeManagerImpl.java   Source Code and License 5 votes vote down vote up
public HeartBeatDBSource() {
    try {
        conn = dbf.getExtraDataSource().getConnection();
        source = new SingleConnectionDataSource(conn, true);
        jdbc = new JdbcTemplate(source);
    } catch (SQLException e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example 23
Project: firefly   File: JdbcFactory.java   Source Code and License 5 votes vote down vote up
/**
 * return a DataSource with a single underlying connection.
 * this allow a user to perform multiple tasks on one connection.
 * this implementation is not thread-safe.
 * @param dbInstance
 * @return
 */
public static DataSource getSingleConnectionDS(DbInstance dbInstance) {
    try {
        return new SingleConnectionDataSource(getDataSource(dbInstance).getConnection(), false);
    } catch (SQLException e) {
        logger.error(e);
    }
    return null;
}
 
Example 24
Project: SimpleFlatMapper   File: JdbcTemplateCrudTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	Connection dbConnection;

	try {
		dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.MYSQL);
		dbConnection.createStatement().executeQuery("SELECT 1");
	} catch(Exception e) {
		dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.HSQLDB);
	}

	template = new JdbcTemplate(new SingleConnectionDataSource(dbConnection, true));
}
 
Example 25
Project: class-guard   File: AbstractRowMapperTests.java   Source Code and License 5 votes vote down vote up
public Mock(MockType type)
		throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example 26
Project: parkandrideAPI   File: UtilizationDao.java   Source Code and License 5 votes vote down vote up
@TransactionalRead
@Override
public Set<Utilization> findLatestUtilization(Long... facilityIds) {
    Connection connection = queryFactory.getConnection();
    if (isPostgreSQL(connection)) {
        return findLatestUtilizationPostgreSQL(facilityIds, new SingleConnectionDataSource(connection, true));
    } else {
        return findLatestUtilizationH2(facilityIds);
    }
}
 
Example 27
Project: ddth-id   File: JdbcIdGenerator.java   Source Code and License 5 votes vote down vote up
protected JdbcTemplate createJdbcTemplate(Connection conn) {
    try {
        return new JdbcTemplate(new SingleConnectionDataSource(conn, true));
    } catch (Exception e) {
        throw e instanceof IdException ? (IdException) e : new IdException(e);
    }
}
 
Example 28
Project: MOCHA   File: IntegrationTestCase.java   Source Code and License 5 votes vote down vote up
/**
 * Read properties and instantiate ApplicationContext
 */
protected void initialize() {
    try {
        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILE));

        this.localContextFactory = properties.getProperty("local.context.factory");
        this.localHost = properties.getProperty("local.host");
        this.localPort = Integer.parseInt(properties.getProperty("local.port"));
        this.localProviderUrl = properties.getProperty("local.provider.url");

        this.fdbDifJdbcUrl = properties.getProperty("local.fdb.dif.jdbc.url");
        this.fdbDifUser = properties.getProperty("local.fdb.dif.user");
        this.fdbDifPassword = properties.getProperty("local.fdb.dif.password");
        this.fdbDifDriver = properties.getProperty("local.fdb.dif.driver");

        this.datupJdbcUrl = properties.getProperty("national.datup.jdbc.url");
        this.datupUser = properties.getProperty("national.datup.user");
        this.datupPassword = properties.getProperty("national.datup.password");
        this.datupDriver = properties.getProperty("national.datup.driver");

        // Register the JDBC driver and load the data source
        Class.forName(getFdbDifDriver()).newInstance();
        this.fdbDifDataSource = new SingleConnectionDataSource(getFdbDifJdbcUrl(), getFdbDifUser(), getFdbDifPassword(),
            true);
        this.fdbDifJdbcTemplate = new JdbcTemplate(fdbDifDataSource);

        Class.forName(getDatupDriver()).newInstance();
        this.datupDataSource = new SingleConnectionDataSource(getDatupJdbcUrl(), getDatupUser(), getDatupPassword(),
            true);
        this.datupJdbcTemplate = new JdbcTemplate(datupDataSource);

        national.providerUrl = properties.getProperty("national.provider.url");
        national.contextFactory = properties.getProperty("national.context.factory");
    }
    catch (Exception e) {
        throw new RuntimeException(e); // NOPMD - we're in a test case anyway
    }
}
 
Example 29
Project: ormlite-tests   File: CommandLine.java   Source Code and License 5 votes vote down vote up
public void doMain(String argv[]) throws Exception {
	String url = "jdbc:derby:target/x;create=true";
	Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

	DataSource dataSource = new SingleConnectionDataSource(url, null, null, false);
	Connection connection = null;
	try {
		connection = dataSource.getConnection();
		readCommands(connection);
	} finally {
		if (connection != null) {
			connection.close();
		}
	}
}
 
Example 30
Project: spring-jdbc-oracle   File: SingleConnectionDataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
  SingleConnectionDataSource ds = new SingleConnectionDataSource(
      this.env.getProperty("db.url"),
      this.env.getProperty("db.username"),
      this.env.getProperty("db.password"),
      this.env.getProperty("db.defaultAutoCommit", Boolean.class));

  ds.setAutoCommit(false);
  return ds;
}
 
Example 31
Project: ureport   File: DatasourceServletAction.java   Source Code and License 4 votes vote down vote up
public void buildFields(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String sql=req.getParameter("sql");
	String parameters=req.getParameter("parameters");
	Connection conn=null;
	final List<Field> fields=new ArrayList<Field>();
	try{
		conn=buildConnection(req);
		Map<String, Object> map = buildParameters(parameters);
		sql=parseSql(sql, map);
		if(ProcedureUtils.isProcedure(sql)){
			List<Field> fieldsList = ProcedureUtils.procedureColumnsQuery(sql, map, conn);
			fields.addAll(fieldsList);
		}else{
			DataSource dataSource=new SingleConnectionDataSource(conn,false);
			NamedParameterJdbcTemplate jdbc=new NamedParameterJdbcTemplate(dataSource);
			PreparedStatementCreator statementCreator=getPreparedStatementCreator(sql,new MapSqlParameterSource(map));
			jdbc.getJdbcOperations().execute(statementCreator, new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
					ResultSet rs = null;
					try {
						rs = ps.executeQuery();
						ResultSetMetaData metadata=rs.getMetaData();
						int columnCount=metadata.getColumnCount();
						for(int i=0;i<columnCount;i++){
							String columnName=metadata.getColumnLabel(i+1);
							fields.add(new Field(columnName));
						}
						return null;
					}finally {
						JdbcUtils.closeResultSet(rs);
					}
				}
			});
		}
		writeObjectToJson(resp, fields);
	}catch(Exception ex){
		throw new ReportDesignException(ex);
	}finally{
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 32
Project: ureport   File: DatasourceServletAction.java   Source Code and License 4 votes vote down vote up
public void previewData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String sql=req.getParameter("sql");
	String parameters=req.getParameter("parameters");
	Map<String, Object> map = buildParameters(parameters);
	sql=parseSql(sql, map);
	Connection conn=null;
	try{
		conn=buildConnection(req);
		List<Map<String,Object>> list=null;
		if(ProcedureUtils.isProcedure(sql)){
			list=ProcedureUtils.procedureQuery(sql, map, conn);
		}else{
			DataSource dataSource=new SingleConnectionDataSource(conn,false);
			NamedParameterJdbcTemplate jdbc=new NamedParameterJdbcTemplate(dataSource);
			list=jdbc.queryForList(sql, map);				
		}
		int size=list.size();
		int currentTotal=size;
		if(currentTotal>500){
			currentTotal=500;
		}
		List<Map<String,Object>> ls=new ArrayList<Map<String,Object>>();
		for(int i=0;i<currentTotal;i++){
			ls.add(list.get(i));
		}
		DataResult result=new DataResult();
		List<String> fields=new ArrayList<String>();
		if(size>0){
			Map<String,Object> item=list.get(0);
			for(String name:item.keySet()){
				fields.add(name);
			}
		}
		result.setFields(fields);
		result.setCurrentTotal(currentTotal);
		result.setData(ls);
		result.setTotal(size);
		writeObjectToJson(resp, result);
	}catch(Exception ex){
		throw new ServletException(ex);
	}finally{
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example 33
Project: jql   File: Utils.java   Source Code and License 4 votes vote down vote up
public static SingleConnectionDataSource getDataSourceFrom(String databaseFile) {
    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();
    dataSource.setDriverClassName("org.sqlite.JDBC");
    dataSource.setUrl("jdbc:sqlite:" + databaseFile);
    return dataSource;
}
 
Example 34
Project: jql   File: Utils.java   Source Code and License 4 votes vote down vote up
public static SingleConnectionDataSource getDataSourceFrom(File directory) {
    return getDataSourceFrom(getDatabasePath(directory));
}
 
Example 35
Project: FitNesseLauncher   File: JdbcSlimRunner.java   Source Code and License 4 votes vote down vote up
public JdbcSlimRunner(final String driverClassname, final String url, final String username, final String password, final String sql)
        throws ClassNotFoundException {
	Class.forName(driverClassname);
	this.template = new JdbcTemplate(new SingleConnectionDataSource(url, username, password, false));
	this.sql = sql;
}
 
Example 36
Project: spring-data-jpa-entity-graph   File: DataRepositoryConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public DataSource dataSource() {
  return new SingleConnectionDataSource("jdbc:hsqldb:mem:.", "sa", "", true);
}
 
Example 37
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 4 votes vote down vote up
public void setRtJdbcTemplate(SingleConnectionDataSource ds) {
	this.rtJdbcTemplate = new JdbcTemplate(ds);
}
 
Example 38
Project: TaskExcute   File: ReportTemplateService.java   Source Code and License 4 votes vote down vote up
public List<ImageDefData> executeSqlForImgdefDs(Map<String,String> sqlmap)throws Exception{
       String resultSql = sqlmap.get("resultSql");
	
	String showViewStr = sqlmap.get("showViewStr");
	
	List<ImageDefData> returnList = new ArrayList<ImageDefData>();
	
	SingleConnectionDataSource ds = getSingleConnectionDataSource(sqlmap.get("code"));
   	this.setRtJdbcTemplate(ds);
   	
   	
	try {
		List<Map<String,Object>> list = (List<Map<String,Object>>)this.rtJdbcTemplate.queryForList(resultSql);
		if(list.size()>0){
			for (Map<String, Object> map : list) 
			{
				ImageDefData imageDefData = new ImageDefData();
				String [] array = showViewStr.split("&");
				for (String str : array) 
				{
					String [] arrP =str.split("=");
					if(arrP.length==1)
					{
						imageDefData = this.getImageDefData(imageDefData, arrP[0], "");
					}
					else
					{
						imageDefData = this.getImageDefData(imageDefData, arrP[0], ParseUtil.getString(map.get(arrP[1])));
							
					}
             	    }
				returnList.add(imageDefData);
			}
		}
		return returnList;
	} catch (Exception e) {
		log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" +e);
		throw new Exception(e.getMessage());
	}
	finally{
		ds.getConnection().close();
	}
	
   	
}
 
Example 39
Project: FitNesseLauncher   File: JdbcSlimRunner.java   Source Code and License 4 votes vote down vote up
public JdbcSlimRunner(final String driverClassname, final String url, final String username, final String password, final String sql)
        throws ClassNotFoundException {
	Class.forName(driverClassname);
	this.template = new JdbcTemplate(new SingleConnectionDataSource(url, username, password, false));
	this.sql = sql;
}
 
Example 40
Project: celerio   File: MysqlExtension.java   Source Code and License 4 votes vote down vote up
protected JdbcTemplate getJdbcTemplate(Connection connection) {
    DataSource dataSource = new SingleConnectionDataSource(connection, true);
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    return jdbcTemplate;
}
 
Example 41
Project: celerio   File: H2Extension.java   Source Code and License 4 votes vote down vote up
private JdbcTemplate getJdbcTemplate(Connection connection) {
    DataSource dataSource = new SingleConnectionDataSource(connection, true);
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    return jdbcTemplate;
}
 
Example 42
Project: celerio   File: MySqlEnumExtractorTest.java   Source Code and License 4 votes vote down vote up
private JdbcTemplate jdbcTemplate() {
    return new JdbcTemplate(new SingleConnectionDataSource("jdbc:mysql://localhost/sakila", "root", "root", true));
}
 
Example 43
Project: ddth-dao   File: QndResultSetStreaming.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourceMysql() throws SQLException {
    Connection conn = getConnectionMysql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 44
Project: ddth-dao   File: QndResultSetStreaming.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourcePgsql() throws SQLException {
    Connection conn = getConnectionPgsql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 45
Project: ddth-dao   File: QndResultSetStreaming.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourceMssql() throws SQLException {
    Connection conn = getConnectionMssql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 46
Project: ddth-dao   File: QndDdthJdbcHelperINClause.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourceMysql() throws SQLException {
    Connection conn = getConnectionMysql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 47
Project: ddth-dao   File: QndPreOpenConnection.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSource() throws SQLException {
    Connection conn = getConnection();
    return new SingleConnectionDataSource(conn, false);
}
 
Example 48
Project: ddth-dao   File: QndSQLExceptionTranslator.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourceMysql() throws SQLException {
    Connection conn = getConnectionMysql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 49
Project: ddth-dao   File: QndSQLExceptionTranslator.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourcePgsql() throws SQLException {
    Connection conn = getConnectionPgsql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 50
Project: ddth-dao   File: QndDuplidatedPKorUnique.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourceMysql() throws SQLException {
    Connection conn = getConnectionMysql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 51
Project: ddth-dao   File: QndDuplidatedPKorUnique.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourcePgsql() throws SQLException {
    Connection conn = getConnectionPgsql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 52
Project: ddth-dao   File: QndDuplidatedPKorUnique.java   Source Code and License 4 votes vote down vote up
private static DataSource getDataSourceMssql() throws SQLException {
    Connection conn = getConnectionMssql();
    return new SingleConnectionDataSource(conn, true);
}
 
Example 53
Project: SimpleFlatMapper   File: JdbcTemplateMapperFactoryTest.java   Source Code and License 4 votes vote down vote up
@Before
public void setUp() throws SQLException {
	template = new JdbcTemplate(new SingleConnectionDataSource(DbHelper.objectDb(), true));
}
 
Example 54
Project: SimpleFlatMapper   File: MappingSqlQueryTest.java   Source Code and License 4 votes vote down vote up
@Before
public void setUp() throws SQLException {
    Connection dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.HSQLDB);
    dataSource = new SingleConnectionDataSource(dbConnection, true);
}
 
Example 55
Project: jOOQ-s-Java-8-Goodies   File: SQLGoodies.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Class.forName("org.h2.Driver");
        try (Connection c = getConnection("jdbc:h2:~/test", "sa", "")) {
            String sql = "select schema_name, is_default from information_schema.schemata order by schema_name";

            System.out.println("Fetching data into a with JDBC / Java 7 syntax");
            System.out.println("----------------------------------------------");
            try (PreparedStatement stmt = c.prepareStatement(sql);
                 ResultSet rs = stmt.executeQuery()) {

                while (rs.next()) {
                    System.out.println(
                        new Schema(rs.getString("SCHEMA_NAME"),
                                   rs.getBoolean("IS_DEFAULT"))
                    );
                }
            }

            System.out.println();
            System.out.println("Fetching data into a lambda expression with jOOQ");
            System.out.println("------------------------------------------------");
            DSL.using(c)
               .fetch(sql)
               .map(r -> new Schema(
                       r.getValue("SCHEMA_NAME", String.class),
                       r.getValue("IS_DEFAULT", boolean.class)
               ))
            // could also be written as
            // .into(Schema.class)
               .forEach(System.out::println);

            System.out.println();
            System.out.println("Fetching data into a lambda expression with Spring JDBC");
            System.out.println("-------------------------------------------------------");
            new JdbcTemplate(new SingleConnectionDataSource(c, true))
                .query(sql,
                    (rs, rowNum) -> new Schema(
                        rs.getString("SCHEMA_NAME"),
                        rs.getBoolean("IS_DEFAULT")
                    ))
                .forEach(System.out::println);

            System.out.println();
            System.out.println("Fetching data into a lambda expression with Apache DbUtils");
            System.out.println("-------------------------------------------------------");
            new QueryRunner()
                .query(c, sql,
                    new ArrayListHandler())
                .stream()
                .map(array -> new Schema(
                    (String) array[0],
                    (Boolean) array[1]
                ))
                .forEach(System.out::println);
        }
    }
 
Example 56
Project: queue-server   File: JdbcQueueApi.java   Source Code and License 2 votes vote down vote up
/**
 * Constructs a {@link JdbcTemplate} from a connection.
 * 
 * @param conn
 * @return
 */
protected JdbcTemplate jdbcTemplate(Connection conn) {
    DataSource ds = new SingleConnectionDataSource(conn, true);
    return new JdbcTemplate(ds);
}
 
Example 57
Project: ddth-dao   File: JdbcTemplateJdbcHelper.java   Source Code and License 2 votes vote down vote up
/**
 * Get {@link JdbcTemplate} instance for a given {@link Connection}.
 * 
 * Note: the returned {@link JdbcTemplate} will not automatically close the
 * {@link Connection}.
 * 
 * @param conn
 * @return
 */
protected JdbcTemplate jdbcTemplate(Connection conn) {
    DataSource ds = new SingleConnectionDataSource(conn, true);
    return new JdbcTemplate(ds);
}
 
Example 58
Project: ddth-dao   File: JdbcTemplateJdbcHelper.java   Source Code and License 2 votes vote down vote up
/**
 * Get {@link NamedParameterJdbcTemplate} instance for a given
 * {@link Connection}.
 * 
 * Note: the returned {@link JdbcTemplate} will not automatically close the
 * {@link Connection}.
 * 
 * @param conn
 * @return
 * @since 0.8.0
 */
protected NamedParameterJdbcTemplate namedParameterJdbcTemplate(Connection conn) {
    DataSource ds = new SingleConnectionDataSource(conn, true);
    return new NamedParameterJdbcTemplate(ds);
}
 
Example 59
Project: MOCHA   File: IntegrationTestCase.java   Source Code and License 2 votes vote down vote up
/**
 * 
 * @return dataSource property
 */
public SingleConnectionDataSource getFdbDifDataSource() {
    return fdbDifDataSource;
}
 
Example 60
Project: MOCHA   File: IntegrationTestCase.java   Source Code and License 2 votes vote down vote up
/**
 * 
 * @return dataSource property
 */
public SingleConnectionDataSource getDatupDataSource() {
    return datupDataSource;
}