Java Code Examples for org.h2.jdbcx.JdbcDataSource

The following are top voted examples for showing how to use org.h2.jdbcx.JdbcDataSource. 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: goodees   File: JdbcTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void initDb() throws SQLException {
    ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:estest;DB_CLOSE_DELAY=-1;MVCC=true");
    ds.setUser("sa");
    try (Connection con = ds.getConnection()) {
        executeSql(
            con,
            "create table event (ID varchar, VERSION int, TIMESTAMP timestamp, TYPE varchar, PAYLOAD_VERSION int, PAYLOAD clob, primary key (ID, VERSION))",
            " create table version (ID varchar, VERSION int)",
            " create table snapshot(ID varchar primary key, VERSION int, TIMESTAMP timestamp, PAYLOAD_VERSION int, PAYLOAD clob)",
            // we will not use primary key check to escalate optimistic lock exception in very last step
            "create table event_collision (ID varchar, VERSION int, TIMESTAMP timestamp, TYPE varchar, PAYLOAD_VERSION int, PAYLOAD clob)");
    }
    template = new JdbcTemplate(ds);
}
 
Example 2
Project: syndesis   File: JsonDBTest.java   Source Code and License 6 votes vote down vote up
@Before
public void before() {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL");
    DBI dbi = new DBI(ds);

    this.jsondb = new SqlJsonDB(dbi, null,
        Arrays.asList(new Index("/pair", "key"))
    );

    try {
        this.jsondb.dropTables();
    } catch (Exception e) {
    }
    this.jsondb.createTables();
}
 
Example 3
Project: uroborosql   File: UroboroSQLTest.java   Source Code and License 6 votes vote down vote up
@Test
public void builderWithDataSource() throws Exception {
	JdbcDataSource ds = new JdbcDataSource();
	ds.setURL("jdbc:h2:mem:SqlAgentTest");

	SqlConfig config = UroboroSQL.builder(ds).build();
	try (SqlAgent agent = config.agent()) {
		String[] sqls = new String(Files.readAllBytes(Paths.get("src/test/resources/sql/ddl/create_tables.sql")),
				StandardCharsets.UTF_8).split(";");
		for (String sql : sqls) {
			if (StringUtils.isNotBlank(sql)) {
				agent.updateWith(sql.trim()).count();
			}
		}

		insert(agent, Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));
		agent.rollback();
	}

	assertEquals(new H2Dialect().getName(), config.getDialect().getName());
}
 
Example 4
Project: neo-java   File: BlockDbH2Impl.java   Source Code and License 6 votes vote down vote up
/**
 * the constructor.
 *
 * @param config
 *            the configuration to use.
 */
public BlockDbH2Impl(final JSONObject config) {
	try (InputStream resourceAsStream = BlockDbH2Impl.class.getResourceAsStream(SQL_CACHE_XML);) {
		final String jsonStr = IOUtils.toString(resourceAsStream, "UTF-8");
		sqlCache = XML.toJSONObject(jsonStr, true).getJSONObject("BlockDbImpl");
	} catch (final IOException | NullPointerException e) {
		throw new RuntimeException("error reading resource\"" + SQL_CACHE_XML + "\" ", e);
	}

	fileSizeDir = new File(config.getString(ConfigurationUtil.FILE_SIZE_DIR));

	ds = new JdbcDataSource();
	ds.setUrl(config.getString(ConfigurationUtil.URL));

	final JdbcTemplate t = new JdbcTemplate(ds);

	executeSqlGroup(t, "create");
}
 
Example 5
Project: ThriftyPaxos   File: OsgiDataSourceFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a basic data source.
 *
 * @param properties the properties for the data source.
 * @throws SQLException if unsupported properties are supplied, or if data
 *             source can not be created.
 * @return a new data source.
 */
@Override
public DataSource createDataSource(Properties properties)
        throws SQLException {
    // Make copy of properties
    Properties propertiesCopy = new Properties();
    if (properties != null) {
        propertiesCopy.putAll(properties);
    }

    // Verify that no unsupported standard options are used
    rejectUnsupportedOptions(propertiesCopy);

    // Standard pool properties in OSGi not applicable here
    rejectPoolingOptions(propertiesCopy);

    JdbcDataSource dataSource = new JdbcDataSource();

    setupH2DataSource(dataSource, propertiesCopy);

    return dataSource;
}
 
Example 6
Project: ThriftyPaxos   File: OsgiDataSourceFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a pooled data source.
 *
 * @param properties the properties for the data source.
 * @throws SQLException if unsupported properties are supplied, or if data
 *             source can not be created.
 * @return a new data source.
 */
@Override
public ConnectionPoolDataSource createConnectionPoolDataSource(
        Properties properties) throws SQLException {
    // Make copy of properties
    Properties propertiesCopy = new Properties();
    if (properties != null) {
        propertiesCopy.putAll(properties);
    }

    // Verify that no unsupported standard options are used
    rejectUnsupportedOptions(propertiesCopy);

    // The integrated connection pool is H2 is not configurable
    rejectPoolingOptions(propertiesCopy);

    JdbcDataSource dataSource = new JdbcDataSource();

    setupH2DataSource(dataSource, propertiesCopy);

    return dataSource;
}
 
Example 7
Project: ThriftyPaxos   File: OsgiDataSourceFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a pooled XA data source.
 *
 * @param properties the properties for the data source.
 * @throws SQLException if unsupported properties are supplied, or if data
 *             source can not be created.
 * @return a new data source.
 */
@Override
public XADataSource createXADataSource(Properties properties)
        throws SQLException {
    // Make copy of properties
    Properties propertiesCopy = new Properties();
    if (properties != null) {
        propertiesCopy.putAll(properties);
    }

    // Verify that no unsupported standard options are used
    rejectUnsupportedOptions(propertiesCopy);

    // The integrated connection pool is H2 is not configurable
    rejectPoolingOptions(propertiesCopy);

    JdbcDataSource dataSource = new JdbcDataSource();

    setupH2DataSource(dataSource, propertiesCopy);

    return dataSource;
}
 
Example 8
Project: ThriftyPaxos   File: TestXA.java   Source Code and License 6 votes vote down vote up
private void testMixedXaNormal() throws Exception {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test");
    ds.setUser("sa");
    ds.setPassword("");
    XAConnection xa = ds.getXAConnection();
    Connection c = xa.getConnection();
    assertTrue(c.getAutoCommit());
    MyXid xid = new MyXid();
    XAResource res = xa.getXAResource();

    res.start(xid, XAResource.TMNOFLAGS);
    assertTrue(!c.getAutoCommit());
    res.end(xid, XAResource.TMSUCCESS);
    res.commit(xid, true);
    assertTrue(c.getAutoCommit());

    res.start(xid, XAResource.TMNOFLAGS);
    assertTrue(!c.getAutoCommit());
    res.end(xid, XAResource.TMFAIL);
    res.rollback(xid);
    assertTrue(c.getAutoCommit());

    c.close();
    xa.close();
}
 
Example 9
Project: ThriftyPaxos   File: TestDataSource.java   Source Code and License 6 votes vote down vote up
private void testDataSource() throws SQLException {
    deleteDb("dataSource");
    JdbcDataSource ds = new JdbcDataSource();
    PrintWriter p = new PrintWriter(new StringWriter());
    ds.setLogWriter(p);
    assertTrue(p == ds.getLogWriter());
    ds.setURL(getURL("dataSource", true));
    ds.setUser(getUser());
    ds.setPassword(getPassword());
    Connection conn;
    conn = ds.getConnection();
    Statement stat;
    stat = conn.createStatement();
    stat.execute("SELECT * FROM DUAL");
    conn.close();
    conn = ds.getConnection(getUser(), getPassword());
    stat = conn.createStatement();
    stat.execute("SELECT * FROM DUAL");
}
 
Example 10
Project: DigitalMediaServer   File: DLNAMediaDatabase.java   Source Code and License 6 votes vote down vote up
public DLNAMediaDatabase(String name) {
	dbName = name;
	File profileFolder = new File(configuration.getProfileFolder());
	dbDir = new File(profileFolder.isDirectory() ? profileFolder : null, "database").getAbsolutePath();
	boolean logDB = configuration.getDatabaseLogging();
	url = Constants.START_URL + dbDir + File.separator + dbName + (logDB ? ";TRACE_LEVEL_FILE=4" : "");
	LOGGER.debug("Using database URL: {}", url);
	LOGGER.info("Using database located at: \"{}\"", dbDir);
	if (logDB) {
		LOGGER.info("Database logging is enabled");
	} else if (LOGGER.isDebugEnabled()) {
		LOGGER.debug("Database logging is disabled");
	}

	try {
		Class.forName("org.h2.Driver");
	} catch (ClassNotFoundException e) {
		LOGGER.error(null, e);
	}

	JdbcDataSource ds = new JdbcDataSource();
	ds.setURL(url);
	ds.setUser("sa");
	ds.setPassword("");
	cp = JdbcConnectionPool.create(ds);
}
 
Example 11
Project: syndesis-rest   File: SqlFileStoreTest.java   Source Code and License 6 votes vote down vote up
@Parameterized.Parameters
    public static Collection<Object[]> configs() {
        EmbeddedDataSource derbyDs = new EmbeddedDataSource();
        derbyDs.setDatabaseName("test");
        derbyDs.setCreateDatabase("create");

        JdbcDataSource h2Ds = new JdbcDataSource();
        h2Ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL");

        // Tests on postgres disabled

//        PGPoolingDataSource postgresDs = new PGPoolingDataSource();
//        postgresDs.setServerName("localhost");
//        postgresDs.setDatabaseName("syndesis");
//        postgresDs.setUser("postgres");
//        postgresDs.setPassword("password");

        return Arrays.asList(new Object[][]{
            {derbyDs},
//            {postgresDs},
            {h2Ds}
        });
    }
 
Example 12
Project: carbon-device-mgt   File: CertificateAuthenticatorTest.java   Source Code and License 6 votes vote down vote up
/**
 * To create certificate management database.
 *
 * @return Datasource.
 * @throws SQLException SQL Exception.
 */
private DataSource createDatabase() throws SQLException {
    URL resourceURL = ClassLoader.getSystemResource("sql-scripts" + File.separator + "h2.sql");
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:cert;DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("sa");
    final String LOAD_DATA_QUERY = "RUNSCRIPT FROM '" + resourceURL.getPath() + "'";
    Connection conn = null;
    Statement statement = null;
    try {
        conn = dataSource.getConnection();
        statement = conn.createStatement();
        statement.execute(LOAD_DATA_QUERY);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {}
        }
        if (statement != null) {
            statement.close();
        }
    }
    return dataSource;
}
 
Example 13
Project: homework_tester   File: DBServiceImpl.java   Source Code and License 6 votes vote down vote up
private static Connection getH2Connection() {
    try {
        String url = "jdbc:h2:./h2db";
        String name = "tully";
        String pass = "tully";

        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL(url);
        ds.setUser(name);
        ds.setPassword(pass);

        Connection connection = DriverManager.getConnection(url, name, pass);
        return connection;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Project: mats   File: Rule_MatsWithDb.java   Source Code and License 6 votes vote down vote up
@Override
public void before() throws Throwable {
    // Set up JMS from super
    super.before();
    log.info("+++ BEFORE on JUnit Rule '" + id(Rule_MatsWithDb.class) + "', H2 database:");
    log.info("Setting up H2 database using DB URL [" + H2_DATABASE_URL + "], dropping all objects.");
    // Set up H2 Database
    _dataSource = new JdbcDataSource();
    _dataSource.setURL(H2_DATABASE_URL);
    try {
        try (Connection con = _dataSource.getConnection();
                Statement stmt = con.createStatement();) {
            stmt.execute("DROP ALL OBJECTS DELETE FILES");
        }
    }
    catch (SQLException e) {
        throw new RuntimeException("Got problems running 'DROP ALL OBJECTS DELETE FILES'.", e);
    }
    log.info("--- BEFORE done! JUnit Rule '" + id(Rule_MatsWithDb.class) + "', H2 database.");
}
 
Example 15
Project: digdag   File: DataSourceProvider.java   Source Code and License 6 votes vote down vote up
private void createSimpleDataSource()
{
    String url = DatabaseConfig.buildJdbcUrl(config);

    // By default, H2 closes database when all of the connections are closed. When database
    // is closed, data is gone with in-memory mode. It's unexpected. However, if here disables
    // that such behavior using DB_CLOSE_DELAY=-1 option, there're no methods to close the
    // database explicitly. Only way to close is to not disable shutdown hook of H2 database
    // (DB_CLOSE_ON_EXIT=TRUE). But this also causes unexpected behavior when PreDestroy is
    // triggered in a shutdown hook. Therefore, here needs to rely on injector to take care of
    // dependencies so that the database is closed after calling all other PreDestroy methods
    // that depend on this DataSourceProvider.
    // To solve this issue, here holds one Connection until PreDestroy.
    JdbcDataSource ds = new JdbcDataSource();
    ds.setUrl(url + ";DB_CLOSE_ON_EXIT=FALSE");

    logger.debug("Using database URL {}", url);

    try {
        this.closer = ds.getConnection();
    }
    catch (SQLException ex) {
        throw Throwables.propagate(ex);
    }
    this.ds = ds;
}
 
Example 16
Project: stepic_java_webserver   File: DBService.java   Source Code and License 6 votes vote down vote up
public static Connection getH2Connection() {
    try {
        String url = "jdbc:h2:./h2db";
        String name = "tully";
        String pass = "tully";

        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL(url);
        ds.setUser(name);
        ds.setPassword(pass);

        Connection connection = DriverManager.getConnection(url, name, pass);
        return connection;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 17
Project: switchyard   File: CamelJpaBindingTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
    namingMixIn = new NamingMixIn();
    namingMixIn.initialize();

    connection = DriverManager.getConnection("jdbc:h2:mem:events-jpa-quickstart", "sa", "sa");

    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:events-jpa-quickstart");
    ds.setUser("sa");
    ds.setPassword("sa");

    InitialContext initialContext = new InitialContext();
    bind(initialContext, System.getProperty("jpa.persistence.datasource.name"), ds);

}
 
Example 18
Project: switchyard   File: CamelSqlBindingTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void startUp() throws Exception {
    dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:test");
    dataSource.setUser("sa");
    dataSource.setPassword("sa");
    connection = dataSource.getConnection();

    String createStatement = "CREATE TABLE greetings ("
        + "id INT PRIMARY KEY AUTO_INCREMENT, "
        + "receiver VARCHAR(255), "
        + "sender VARCHAR(255) "
        + ");";

    connection.createStatement().executeUpdate("DROP TABLE IF EXISTS greetings");
    connection.createStatement().executeUpdate(createStatement);

    namingMixIn = new NamingMixIn();
    namingMixIn.initialize();
    bindDataSource(namingMixIn.getInitialContext(), "java:jboss/myDS", dataSource);
}
 
Example 19
Project: solr-jdbc   File: JdbcReaderFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test for {@link JdbcReaderFactory#createFromSolrParams(Map, String)}.
 */
@Test
public void createFromSolrParams_solr() {
   // Configure data source via JdbcDataSourceFactory.
   NamedList<Object> poolConfig = new NamedList<>();
   poolConfig.add("class", JdbcDataSource.class.getName());
   poolConfig.add("url", "jdbc:h2:mem:testdb");
   poolConfig.add("user", "sa");
   poolConfig.add("password", "");

   Map<String, Object> shardHandlerConfig = new HashMap<>();
   NamedList<Object> pools = new NamedList<>();
   pools.add("dataSource", poolConfig);
   shardHandlerConfig.put("pools", pools);

   // Configure JdbcReaderFactory.
   Map<String, String> readerDefinition = new HashMap<>();
   readerDefinition.put(JdbcReaderFactoryParams.DATASOURCE, "dataSource");
   readerDefinition.put(JdbcReaderFactoryParams.SQL, "sql");
   readerDefinition.put(JdbcReaderFactoryParams.IGNORE, "false");

   JdbcReader reader = JdbcReaderFactory.createFromSolrParams(readerDefinition, "dummy");
   assertNotNull(reader);
   assertEquals("sql", reader.getSql());
}
 
Example 20
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetConnection() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    DataSource sniffyDataSource = new SniffyDataSource(h2DataSource);

    try (Connection connection = sniffyDataSource.getConnection()) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1));
             Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
    }
}
 
Example 21
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetConnectionWithSocketOperation() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    JdbcDataSource targetDataSource = Mockito.spy(h2DataSource);

    when(targetDataSource.getConnection()).then(invocation -> {
        Sniffy.logSocket(1, new InetSocketAddress(InetAddress.getLoopbackAddress(), 9876), 2, 3, 4);
        return invocation.callRealMethod();
    });

    SniffyDataSource sniffyDataSource = new SniffyDataSource(targetDataSource);

    try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1)).expect(TcpConnections.none());
         Connection connection = sniffyDataSource.getConnection()) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
        assertTrue(spy.getSocketOperations(Threads.CURRENT, null, false).isEmpty());
    }
}
 
Example 22
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetConnectionWithCredentialsWithSocketOperation() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    JdbcDataSource targetDataSource = Mockito.spy(h2DataSource);

    when(targetDataSource.getConnection(anyString(), anyString())).then(invocation -> {
        Sniffy.logSocket(1, new InetSocketAddress(InetAddress.getLoopbackAddress(), 9876), 2, 3, 4);
        return invocation.callRealMethod();
    });

    SniffyDataSource sniffyDataSource = new SniffyDataSource(targetDataSource);

    try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1)).expect(TcpConnections.none());
         Connection connection = sniffyDataSource.getConnection("sa","sa")) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
        assertTrue(spy.getSocketOperations(Threads.CURRENT, null, false).isEmpty());
    }
}
 
Example 23
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetXAConnectionWithSocketOperation() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    JdbcDataSource targetDataSource = Mockito.spy(h2DataSource);

    when(targetDataSource.getXAConnection()).then(invocation -> {
        Sniffy.logSocket(1, new InetSocketAddress(InetAddress.getLoopbackAddress(), 9876), 2, 3, 4);
        return invocation.callRealMethod();
    });

    SniffyDataSource sniffyDataSource = new SniffyDataSource(targetDataSource);

    try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1)).expect(TcpConnections.none());
         Connection connection = sniffyDataSource.getXAConnection().getConnection()) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
        assertTrue(spy.getSocketOperations(Threads.CURRENT, null, false).isEmpty());
    }
}
 
Example 24
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetXAConnectionWithCredentialsWithSocketOperation() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    JdbcDataSource targetDataSource = Mockito.spy(h2DataSource);

    when(targetDataSource.getXAConnection(anyString(), anyString())).then(invocation -> {
        Sniffy.logSocket(1, new InetSocketAddress(InetAddress.getLoopbackAddress(), 9876), 2, 3, 4);
        return invocation.callRealMethod();
    });

    SniffyDataSource sniffyDataSource = new SniffyDataSource(targetDataSource);

    try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1)).expect(TcpConnections.none());
         Connection connection = sniffyDataSource.getXAConnection("sa","sa").getConnection()) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
        assertTrue(spy.getSocketOperations(Threads.CURRENT, null, false).isEmpty());
    }
}
 
Example 25
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetPooledConnectionWithSocketOperation() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    JdbcDataSource targetDataSource = Mockito.spy(h2DataSource);

    when(targetDataSource.getXAConnection()).then(invocation -> {
        Sniffy.logSocket(1, new InetSocketAddress(InetAddress.getLoopbackAddress(), 9876), 2, 3, 4);
        return invocation.callRealMethod();
    });

    SniffyDataSource sniffyDataSource = new SniffyDataSource(targetDataSource);

    try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1)).expect(TcpConnections.none());
         Connection connection = sniffyDataSource.getPooledConnection().getConnection()) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
        assertTrue(spy.getSocketOperations(Threads.CURRENT, null, false).isEmpty());
    }
}
 
Example 26
Project: sniffy   File: SniffyDataSourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetPooledConnectionWithCredentialsWithSocketOperation() throws Exception {
    JdbcDataSource h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:");

    JdbcDataSource targetDataSource = Mockito.spy(h2DataSource);

    when(targetDataSource.getXAConnection(anyString(), anyString())).then(invocation -> {
        Sniffy.logSocket(1, new InetSocketAddress(InetAddress.getLoopbackAddress(), 9876), 2, 3, 4);
        return invocation.callRealMethod();
    });

    SniffyDataSource sniffyDataSource = new SniffyDataSource(targetDataSource);

    try (Spy spy = Sniffy.expect(SqlQueries.exactQueries(1)).expect(TcpConnections.none());
         Connection connection = sniffyDataSource.getPooledConnection("sa","sa").getConnection()) {
        assertNotNull(connection);
        assertTrue(Proxy.isProxyClass(connection.getClass()));
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1 FROM DUAL");
            statement.getResultSet().next();
        }
        assertTrue(spy.getSocketOperations(Threads.CURRENT, null, false).isEmpty());
    }
}
 
Example 27
Project: trainings   File: DataSourceMain.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws SQLException {

        JdbcDataSource dataSource = new JdbcDataSource();
//        dataSource.setUrl("jdbc:h2:~/datasource-test.db");
        dataSource.setUrl("jdbc:h2:mem:test");
        dataSource.setUser("sa");
        dataSource.setPassword("");

        Connection connection = dataSource.getConnection();

        Statement statement = connection.createStatement();

        statement.execute("drop table t1 if exists ");
        statement.execute("create table t1(id int primary key, name char)");
        statement.execute("insert into t1(id,name) values (1,'jdbc')");
        statement.execute("insert into t1(id,name) values (2,'java')");
        statement.execute("insert into t1(id,name) values (3,'trainig')");
        statement.execute("insert into t1(id,name) values (4,'persistence')");

        ResultSet resultSet = statement.executeQuery("select * from t1");

        printResults(resultSet);
    }
 
Example 28
Project: splinter   File: DatabaseProvider.java   Source Code and License 6 votes vote down vote up
private static DataSource getDataSource(Driver driver, String url, String user, String password) {
    DataSource dataSource;
    switch (driver) {
        case H2:
            JdbcDataSource h2DataSource = new JdbcDataSource();
            h2DataSource.setUrl(url);
            user = user != null ? user : "";
            password = password != null ? password : "";
            h2DataSource.setUser(user);
            h2DataSource.setPassword(password);
            return h2DataSource;
        case MYSQL:
            MysqlDataSource mysqlDataSource = new MysqlDataSource();
            mysqlDataSource.setURL(url);
            mysqlDataSource.setUser(user);
            mysqlDataSource.setPassword(password);
            return mysqlDataSource;
        default:
            throw new IllegalArgumentException("Unknown database driver");
    }
}
 
Example 29
Project: rxjava-jdbc   File: DatabaseViaDataSourceTest.java   Source Code and License 6 votes vote down vote up
private static DataSource initDataSource() {
    JdbcDataSource dataSource = new JdbcDataSource();
    String dbUrl = DatabaseCreator.nextUrl();
    dataSource.setURL(dbUrl);

    String jndiName = "jdbc/RxDS";

    try {
        Context context = new InitialContext();
        context.rebind(jndiName, dataSource);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }

    return dataSource;
}
 
Example 30
Project: camel-cookbook-examples   File: EmbeddedDataSourceFactory.java   Source Code and License 6 votes vote down vote up
public static JdbcDataSource getJdbcDataSource(String initScriptLocation) {
    Validate.notEmpty(initScriptLocation, "initScriptLocation is empty");

    String mavenRelativePath = "src/main/resources/" + initScriptLocation;
    String mavenRootRelativePath = "camel-cookbook-transactions/" + mavenRelativePath;

    // check that we can load the init script
    FileLocator locator = new FileLocator().with(initScriptLocation).with(mavenRelativePath).with(mavenRootRelativePath);
    File file = locator.find();
    Validate.notNull(file, locator.getErrorMessage());
    FileSystemResource script = new FileSystemResource(file);

    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("");

    DataSourceInitializer.initializeDataSource(dataSource, script);

    return dataSource;
}
 
Example 31
Project: jqm   File: DbConfig.java   Source Code and License 6 votes vote down vote up
@Bean
public DataSource dataSource()
{
    try
    {
        // When running inside a container, use its resource directory.
        return (DataSource) new JndiTemplate().lookup("jdbc/spring_ds");
    }
    catch (NamingException e)
    {
        // When running on the command line, just create a temporary file DB (only needed for debug).
        System.out.println("JNDI datasource does not exist - falling back on hard coded DS");
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:./target/TEST.db");
        ds.setUser("sa");
        ds.setPassword("sa");
        return ds;
    }
}
 
Example 32
Project: Rubus   File: H2Consumer.java   Source Code and License 5 votes vote down vote up
@Override
protected Connection createConnection() throws SQLException
{
    final JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
    ds.setURL("jdbc:h2:" + dbFileName.getAbsolutePath() + ";DB_CLOSE_ON_EXIT=FALSE");
    ds.setUser("sa");
    Connection results = ds.getConnection();
    results.setAutoCommit(false);
    return results;
}
 
Example 33
Project: crnk-framework   File: JpaTestConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource testDataSource() {
	JdbcDataSource dataSource = new JdbcDataSource();
	dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE");
	dataSource.setUser("sa");
	return dataSource;
}
 
Example 34
Project: crnk-framework   File: OperationsTestConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource testDataSource() {
	JdbcDataSource dataSource = new JdbcDataSource();
	dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE");
	dataSource.setUser("sa");
	return dataSource;
}
 
Example 35
Project: org.ops4j.pax.transx   File: H2Test.java   Source Code and License 5 votes vote down vote up
private XADataSource createH2DataSource() {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test");
    ds.setUser("sa");
    ds.setPassword("");
    return ds;
}
 
Example 36
Project: ThriftyPaxos   File: TestXA.java   Source Code and License 5 votes vote down vote up
private void testXAAutoCommit() throws Exception {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test");
    ds.setUser("sa");
    ds.setPassword("");
    XAConnection xa = ds.getXAConnection();
    MyXid xid = new MyXid();
    xa.getXAResource().start(xid,
            XAResource.TMNOFLAGS);
    Connection c = xa.getConnection();
    assertTrue(!c.getAutoCommit());
    c.close();
    xa.close();
}
 
Example 37
Project: ThriftyPaxos   File: TestXA.java   Source Code and License 5 votes vote down vote up
private XADataSource createXADatasource(boolean useOneDatabase, String url) {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setPassword(getPassword(""));
    ds.setUser("sa");
    if (useOneDatabase) {
        ds.setURL(getURL("xa", true));
    } else {
        ds.setURL(url);
    }
    return ds;
}
 
Example 38
Project: ThriftyPaxos   File: TestDataSource.java   Source Code and License 5 votes vote down vote up
private void testDataSourceFactory() throws Exception {
    ObjectFactory factory = new JdbcDataSourceFactory();
    assertTrue(null == factory.getObjectInstance("test", null, null, null));
    Reference ref = new Reference("java.lang.String");
    assertTrue(null == factory.getObjectInstance(ref, null, null, null));
    ref = new Reference(JdbcDataSource.class.getName());
    ref.add(new StringRefAddr("url", "jdbc:h2:mem:"));
    ref.add(new StringRefAddr("user", "u"));
    ref.add(new StringRefAddr("password", "p"));
    ref.add(new StringRefAddr("loginTimeout", "1"));
    ref.add(new StringRefAddr("description", "test"));
    JdbcDataSource ds = (JdbcDataSource) factory.getObjectInstance(
            ref, null, null, null);
    assertEquals(1, ds.getLoginTimeout());
    assertEquals("test", ds.getDescription());
    assertEquals("jdbc:h2:mem:", ds.getURL());
    assertEquals("u", ds.getUser());
    assertEquals("p", ds.getPassword());
    Reference ref2 = ds.getReference();
    assertEquals(ref.size(), ref2.size());
    assertEquals(ref.get("url").getContent().toString(),
            ref2.get("url").getContent().toString());
    assertEquals(ref.get("user").getContent().toString(),
            ref2.get("user").getContent().toString());
    assertEquals(ref.get("password").getContent().toString(),
            ref2.get("password").getContent().toString());
    assertEquals(ref.get("loginTimeout").getContent().toString(),
            ref2.get("loginTimeout").getContent().toString());
    assertEquals(ref.get("description").getContent().toString(),
            ref2.get("description").getContent().toString());
    ds.setPasswordChars("abc".toCharArray());
    assertEquals("abc", ds.getPassword());
}
 
Example 39
Project: ThriftyPaxos   File: TestConnectionPool.java   Source Code and License 5 votes vote down vote up
private JdbcConnectionPool getConnectionPool(int poolSize) {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(getURL("connectionPool", true));
    ds.setUser(getUser());
    ds.setPassword(getPassword());
    JdbcConnectionPool pool = JdbcConnectionPool.create(ds);
    pool.setMaxConnections(poolSize);
    return pool;
}
 
Example 40
Project: enkan   File: DomaEntityTaskTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws Exception {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    createTable(ds);
    DomaEntityTask task = new DomaEntityTask("example/entity", "product", ds);
    PathResolverMock resolver = new PathResolverMock();
    task.execute(resolver);
}
 
Example 41
Project: sourcerer-samples   File: Application.java   Source Code and License 5 votes vote down vote up
@Bean
DataSource getDataSource(
        @Value("${spring.datasource.url}") final String url,
        @Value("${spring.datasource.username}") final String username,
        @Value("${spring.datasource.password}") final String password) {
    // Spring auto configures an embedded database with its own url when one is detected,
    // explicitly create the h2 data source here to force it to use our settings :/
    JdbcDataSource jdbcDataSource = new JdbcDataSource();
    jdbcDataSource.setURL(url);
    jdbcDataSource.setUser(username);
    jdbcDataSource.setPassword(password);
    return jdbcDataSource;
}
 
Example 42
Project: muon-app   File: DataSourceFactory.java   Source Code and License 5 votes vote down vote up
public static DataSource getH2DataSource() {
    
    // this factory does not depend on injected properties, used for test only
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    ds.setUser("sa");
    ds.setPassword("sa");
    return ds;
}
 
Example 43
Project: jdbcis   File: AbstractOperationTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
    final JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("");

    final Connection connection = dataSource.getConnection();
    RunScript.execute(connection, new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("test.sql")));
    System.out.println("Created in-memory database: " + connection.getMetaData().getURL());

    connectionManager = new CountingConnectionManager(new DataSourceConnectionManager(dataSource));
    toTest = new JdbcOperations(connectionManager);
}
 
Example 44
Project: katharsis-framework   File: TestConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource testDataSource() {
	JdbcDataSource dataSource = new JdbcDataSource();
	dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE");
	dataSource.setUser("sa");
	return dataSource;
}
 
Example 45
Project: light-task-scheduler   File: H2DataSourceProvider.java   Source Code and License 5 votes vote down vote up
private DataSource createDataSource(Config config) throws ClassNotFoundException {

        String url = config.getParameter(URL_KEY);
        String username = config.getParameter(USERNAME_KEY);
        String password = config.getParameter(PASSWORD_KEY);

        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

        return dataSource;
    }
 
Example 46
Project: syndesis-rest   File: JsonDBTest.java   Source Code and License 5 votes vote down vote up
@Before
public void before() {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL");
    DBI dbi = new DBI(ds);
    this.jsondb = new SqlJsonDB(dbi, null);

    try {
        this.jsondb.dropTables();
    } catch (Exception e) {
    }
    this.jsondb.createTables();
}
 
Example 47
Project: flowable-engine   File: MultiTenantProcessEngineTest.java   Source Code and License 5 votes vote down vote up
private DataSource createDataSource(String jdbcUrl, String jdbcUsername, String jdbcPassword) {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(jdbcUrl);
    ds.setUser(jdbcUsername);
    ds.setPassword(jdbcPassword);
    return ds;
}
 
Example 48
Project: carbon-device-mgt   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * To create the database tables for the particular device-type based on the scripts
 *
 * @param databaseName Name of the Database
 * @param scriptFilePath Path of the SQL script File
 * @throws IOException  IO Exception
 * @throws SQLException SQL Exception.
 */
public static DataSource createDataTables(String databaseName, String scriptFilePath) throws IOException,
        SQLException {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:" + databaseName + ";DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("sa");

    File file = new File(scriptFilePath);

    final String LOAD_DATA_QUERY = "RUNSCRIPT FROM '" + file.getCanonicalPath() + "'";

    Connection connection = null;
    try {
        connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        statement.execute(LOAD_DATA_QUERY);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
    return dataSource;
}
 
Example 49
Project: bss   File: BetterSqlSupportTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    server = Server.createTcpServer().start();
    Class.forName("org.h2.Driver");
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl("jdbc:h2:mem:");
    connection = dataSource.getConnection();
    String create = new Scanner(BetterSqlMapperTest.class.getResourceAsStream("/sql/test_create.sql"), "UTF-8").useDelimiter("\\A").next();
    Statement statement = connection.createStatement();
    statement.execute(create);
    statement.close();
}
 
Example 50
Project: bss   File: BetterSqlTransactionTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    server = Server.createTcpServer().start();
    Class.forName("org.h2.Driver");
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl("jdbc:h2:mem:");
    connectionH2 = dataSource.getConnection();
    String create = new Scanner(BetterSqlMapperTest.class.getResourceAsStream("/sql/test_create.sql"), "UTF-8").useDelimiter("\\A").next();
    Statement statement = connectionH2.createStatement();
    statement.execute(create);
    statement.close();
}
 
Example 51
Project: bss   File: BetterSqlMapperTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    server = Server.createTcpServer().start();
    Class.forName("org.h2.Driver");
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl("jdbc:h2:mem:");
    connection = dataSource.getConnection();
    String create = new Scanner(BetterSqlMapperTest.class.getResourceAsStream("/sql/test_create.sql"), "UTF-8").useDelimiter("\\A").next();
    Statement statement = connection.createStatement();
    statement.execute(create);
    statement.close();
}
 
Example 52
Project: che   File: H2DBTestServer.java   Source Code and License 5 votes vote down vote up
@Override
public void start() {
  final JdbcDataSource dataSource = new JdbcDataSource();
  dataSource.setUrl(getUrl() + ";DB_CLOSE_DELAY=-1");
  try (Connection conn = dataSource.getConnection()) {
    RunScript.execute(conn, new StringReader("SELECT 1"));
  } catch (SQLException x) {
    throw new RuntimeException(x);
  }
}
 
Example 53
Project: db-upgrader   File: DbUpgraderTest.java   Source Code and License 5 votes vote down vote up
DataSource getDataSource(String name){
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:" + name + ";DB_CLOSE_DELAY=-1");
    dataSource.setUser("admin");
    dataSource.setPassword("");
    return dataSource;
}
 
Example 54
Project: respiro   File: UserDatabaseIT.java   Source Code and License 5 votes vote down vote up
@Before
public void before() {
    dataSource = new JdbcDataSource();
    dataSource.setUrl("jdbc:h2:tcp://localhost:" + getH2Port() + "/mem:hellodata;MODE=Oracle");
    dataSource.setUser("admin");
    dataSource.setPassword("password");
}
 
Example 55
Project: ldtm   File: H2Utils.java   Source Code and License 5 votes vote down vote up
public static DataSource getDataSource(){
	JdbcDataSource ds = new JdbcDataSource();  
       ds.setURL("jdbc:h2:"+dbDir);  
       ds.setUser("sa");  
       ds.setPassword("123456"); 
      
       return ds;
}
 
Example 56
Project: ignite   File: CacheJdbcPojoStoreFactorySelfTest.java   Source Code and License 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
public void testCacheConfiguration() throws Exception {
    try (Ignite ignite = Ignition.start("modules/spring/src/test/config/node.xml")) {
        try (Ignite ignite1 = Ignition.start("modules/spring/src/test/config/node1.xml")) {
            try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(cacheConfiguration())) {
                try (IgniteCache<Integer, String> cache1 = ignite1.getOrCreateCache(cacheConfiguration())) {
                    checkStore(cache, JdbcDataSource.class);

                    checkStore(cache1, CacheJdbcBlobStoreFactorySelfTest.DummyDataSource.class);
                }
            }
        }
    }
}
 
Example 57
Project: ignite   File: CacheJdbcPojoStoreFactorySelfTest.java   Source Code and License 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
public void testSerializable() throws Exception {
    try (Ignite ignite = Ignition.start("modules/spring/src/test/config/node.xml")) {
        try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(cacheConfigurationH2Dialect())) {
            checkStore(cache, JdbcDataSource.class);
        }
    }
}
 
Example 58
Project: ignite   File: CacheJdbcBlobStoreFactorySelfTest.java   Source Code and License 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
public void testXmlConfiguration() throws Exception {
    try (Ignite ignite = Ignition.start("modules/spring/src/test/config/store-cache.xml")) {
        try(Ignite ignite1 = Ignition.start("modules/spring/src/test/config/store-cache1.xml")) {
            checkStore(ignite.<Integer, String>cache(CACHE_NAME), JdbcDataSource.class);

            checkStore(ignite1.<Integer, String>cache(CACHE_NAME), DummyDataSource.class);
        }
    }
}
 
Example 59
Project: ignite   File: CacheJdbcBlobStoreFactorySelfTest.java   Source Code and License 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
public void testCacheConfiguration() throws Exception {
    try (Ignite ignite = Ignition.start("modules/spring/src/test/config/node.xml")) {
        try (Ignite ignite1 = Ignition.start("modules/spring/src/test/config/node1.xml")) {
            try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(cacheConfiguration())) {
                try (IgniteCache<Integer, String> cache1 = ignite1.getOrCreateCache(cacheConfiguration())) {
                    checkStore(cache, JdbcDataSource.class);

                    checkStore(cache1, DummyDataSource.class);
                }
            }
        }
    }
}
 
Example 60
Project: teiid   File: TestRelate.java   Source Code and License 5 votes vote down vote up
@BeforeClass public static void oneTimeSetUp() throws Exception {
  	//DQPConfiguration config = new DQPConfiguration();
  	//config.setUserRequestSourceConcurrency(1);
  	server = new FakeServer(true);
  	JdbcDataSource h2ds = new JdbcDataSource();
  	System.out.println(UnitTestUtil.getTestDataFile("relate/test.zip").getAbsolutePath());
  	h2ds.setURL("jdbc:h2:zip:"+UnitTestUtil.getTestDataFile("relate/test.zip").getAbsolutePath()+"!/test;");
  	final DataSource ds = JdbcConnectionPool.create(h2ds);
ExecutionFactory h2 = new H2ExecutionFactory();
h2.start();
ConnectorManagerRepository cmr = new ConnectorManagerRepository();
ConnectorManager cm = new ConnectorManager("source", "bar", h2) {
	@Override
	public Object getConnectionFactory() throws TranslatorException {
		return ds;
	}
};
cmr.addConnectorManager("source", cm);
server.setConnectorManagerRepository(cmr);
server.deployVDB("VehicleRentalsVDB", UnitTestUtil.getTestDataPath()+"/relate/VehicleRentalsVDB.vdb");
if (DEBUG) {
   	Logger logger = Logger.getLogger("org.teiid");
   	logger.setLevel(Level.FINER);
   	ConsoleHandler handler = new ConsoleHandler();
   	handler.setLevel(Level.FINER);
   	logger.addHandler(handler);
  	}
  }