Java Code Examples for org.h2.jdbcx.JdbcDataSource

The following examples show how to use org.h2.jdbcx.JdbcDataSource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: JImageHash   Source File: DatabaseManager.java    License: MIT License 6 votes vote down vote up
public DatabaseManager(String subPath, String username, String password) throws SQLException {
	// Setup database connection
	JdbcDataSource ds = new JdbcDataSource();
	ds.setURL("jdbc:h2:" + subPath);
	ds.setUser(username);
	ds.setPassword(password);
	conn = ds.getConnection();

	createTables();

	prepareStatements();

	// Make sure to release the database at shutdown. lose connection
	Runtime.getRuntime().addShutdownHook(new Thread(() -> {
		try {
			if (!conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}));

}
 
Example 2
Source Project: Spring5Tutorial   Source File: Main.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Properties prop = new Properties();
    prop.load(Main.class.getClassLoader().getResourceAsStream("jdbc.properties"));        
    
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL(prop.getProperty("cc.openhome.jdbcUrl"));
    dataSource.setUser(prop.getProperty("cc.openhome.user"));
    dataSource.setPassword(prop.getProperty("cc.openhome.password"));
    
    AccountDAO acctDAO = new AccountDAOJdbcImpl(dataSource);
    MessageDAO messageDAO = new MessageDAOJdbcImpl(dataSource);
    
    UserService userService = new UserService(acctDAO, messageDAO);
    
    userService.messages("caterpillar")
               .forEach(message -> {
                   System.out.printf("%s\t%s%n",
                       message.getLocalDateTime(),
                       message.getBlabla());
               });

}
 
Example 3
Source Project: syndesis   Source File: JsonDBTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeAll
public void before() {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1;MODE=PostgreSQL");
    DBI dbi = new DBI(ds);

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

    try {
        this.jsondb.dropTables();
    } catch (Exception e) {
    }
    this.jsondb.createTables();
}
 
Example 4
/**
 * 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 5
Source Project: homework_tester   Source File: DBServiceImpl.java    License: MIT 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 6
Source Project: digdag   Source File: DataSourceProvider.java    License: Apache License 2.0 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 7
Source Project: stepic_java_webserver   Source File: DBService.java    License: MIT 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 8
Source Project: rxjava-jdbc   Source File: DatabaseViaDataSourceTest.java    License: Apache License 2.0 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 9
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 10
Source Project: jqm   Source File: DbConfig.java    License: Apache License 2.0 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 11
Source Project: journalkeeper   Source File: H2DataSourceFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSource createDataSource(Path path, Properties properties) {
    String url = properties.getProperty(H2Configs.DATASOURCE_URL);
    if (StringUtils.isBlank(url)) {
        url = String.format("jdbc:h2:file:%s/data;AUTO_SERVER=TRUE;MVCC=TRUE;LOCK_TIMEOUT=30000", path.toString());
    }
    JdbcDataSource datasource = new JdbcDataSource();
    datasource.setURL(url);
    return datasource;
}
 
Example 12
Source Project: realworld-api-quarkus   Source File: DatabaseIntegrationTest.java    License: MIT License 5 votes vote down vote up
private static DataSource dataSource() {
  JdbcDataSource jdbcDataSource = new JdbcDataSource();
  jdbcDataSource.setUrl("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
  jdbcDataSource.setUser("sa");
  jdbcDataSource.setPassword("");
  return jdbcDataSource;
}
 
Example 13
Source Project: presto   Source File: H2DaoProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public H2DaoProvider(DbResourceGroupConfig config)
{
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(requireNonNull(config.getConfigDbUrl(), "resource-groups.config-db-url is null"));
    // TODO: this should use onDemand()
    this.dao = Jdbi.create(ds)
            .installPlugin(new SqlObjectPlugin())
            .open()
            .attach(H2ResourceGroupsDao.class);
}
 
Example 14
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 15
@Bean
public DataSource getDataSource() {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL(jdbcUrl);
    dataSource.setUser(user);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example 16
public static UserService getUserService() throws IOException {
	Properties prop = new Properties();
	prop.load(Main.class.getClassLoader().getResourceAsStream("jdbc.properties"));		
	
	JdbcDataSource dataSource = new JdbcDataSource();
       dataSource.setURL(prop.getProperty("cc.openhome.jdbcUrl"));
       dataSource.setUser(prop.getProperty("cc.openhome.user"));
       dataSource.setPassword(prop.getProperty("cc.openhome.password"));
       
       AccountDAO acctDAO = new AccountDAOJdbcImpl(dataSource);
       MessageDAO messageDAO = new MessageDAOJdbcImpl(dataSource);
       
       UserService userService = new UserService(acctDAO, messageDAO);
	return userService;
}
 
Example 17
@Profile("dev")
@Bean
public DataSource getDataSource() {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL(jdbcUrl);
    dataSource.setUser(user);
    dataSource.setPassword(password);
    
    return dataSource;
}
 
Example 18
@Bean
public DataSource getDataSource() {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:tcp://localhost/c:/workspace/SpringDI/gossip");
    dataSource.setUser("caterpillar");
    dataSource.setPassword("12345678");
    return dataSource;
}
 
Example 19
Source Project: metanome-algorithms   Source File: JdbcTest.java    License: Apache License 2.0 5 votes vote down vote up
private static DataSource getDataSource() {
	JdbcDataSource dataSource = new JdbcDataSource();
	dataSource.setURL(JDBC_URL);
	dataSource.setUser(USER);
	dataSource.setPassword(PASSWORD);
	return dataSource;
}
 
Example 20
Source Project: syndesis   Source File: MetricsCollectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws IOException, ParseException {
    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();

    jsondbRM = new JsonDBRawMetrics(jsondb);

    load();

    CacheManager cacheManager = new LRUCacheManager(100);
    EncryptionComponent encryptionComponent = new EncryptionComponent(null);
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    //Create Data Manager
    dataManager = new DataManager(cacheManager, Collections.emptyList(), null, encryptionComponent, resourceLoader, null);
    intMH = new IntegrationMetricsHandler(dataManager);
}
 
Example 21
Source Project: syndesis   Source File: ActivityTrackingControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:t;DB_CLOSE_DELAY=-1;MODE=PostgreSQL");
    this.dbi = new DBI(ds);
    this.jsondb = new SqlJsonDB(dbi, null);
    this.jsondb.createTables();

    client = mock(KubernetesClient.class);
    when(client.getConfiguration()).thenReturn(new ConfigBuilder().withMasterUrl("http://master").build());
}
 
Example 22
Source Project: syndesis   Source File: MemorySqlJsonDB.java    License: Apache License 2.0 5 votes vote down vote up
public static CloseableJsonDB create(Collection<Index> indexes) {
    JdbcDataSource ds = new JdbcDataSource();
    DBI dbi = new DBI(ds);
    ds.setURL("jdbc:h2:mem:"+ KeyGenerator.createKey()+";MODE=PostgreSQL");
    try {
        Connection keepsDBOpen = ds.getConnection();
        ClosableSqlJsonDB result = new ClosableSqlJsonDB(keepsDBOpen, dbi, indexes);
        result.createTables();
        return result;
    } catch (SQLException e) {
        throw new JsonDBException(e);
    }
}
 
Example 23
Source Project: crnk-framework   Source File: JpaTestConfig.java    License: Apache License 2.0 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 24
Source Project: crnk-framework   Source File: OperationsTestConfig.java    License: Apache License 2.0 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 25
Source Project: spring-boot-inside   Source File: MyDataSourceConfig.java    License: MIT License 5 votes vote down vote up
@Bean(name = "dataSource1")
public DataSource dataSource1(@Value("${db.user}") String user) {
	System.err.println("user: " + user);
	JdbcDataSource ds = new JdbcDataSource();
	ds.setURL("jdbc:h2:˜/test");
	ds.setUser(user);
	return ds;
}
 
Example 26
Source Project: gradle-plugins   Source File: LiquibaseSchemaTarget.java    License: Apache License 2.0 5 votes vote down vote up
private Connection setupDataSource(File file) throws SQLException, IOException {
	JdbcDataSource dataSource = new JdbcDataSource();
	dataSource.setUrl("jdbc:h2:mem:test");
	String script = FileUtils.readAsString(file);
	Connection connection = dataSource.getConnection();
	SqlUtils.executeSql(connection, script, ";");
	return connection;

}
 
Example 27
Source Project: Plan   Source File: H2DB.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private Connection getConnectionFor(String dbFilePath) throws SQLException {
    String username = config.get(DatabaseSettings.H2_USER);
    String password = config.get(DatabaseSettings.H2_PASS);

    JdbcDataSource jdbcDataSource = new JdbcDataSource();
    jdbcDataSource.setURL("jdbc:h2:file:" + dbFilePath + ";mode=MySQL;DATABASE_TO_UPPER=false");
    jdbcDataSource.setUser(username);
    jdbcDataSource.setPassword(password);

    return jdbcDataSource.getConnection();
}
 
Example 28
Source Project: enkan   Source File: DomaEntityTaskTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
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 29
Source Project: katharsis-framework   Source File: TestConfig.java    License: Apache License 2.0 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 30
Source Project: shardingsphere   Source File: DataSourceSwapperTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertResult(final XADataSource xaDataSource) {
    assertThat(xaDataSource, instanceOf(JdbcDataSource.class));
    JdbcDataSource h2XADataSource = (JdbcDataSource) xaDataSource;
    assertThat(h2XADataSource.getUrl(), is("jdbc:mysql://localhost:3306/demo_ds"));
    assertThat(h2XADataSource.getUser(), is("root"));
    assertThat(h2XADataSource.getPassword(), is("root"));
}