Java Code Examples for org.h2.jdbcx.JdbcConnectionPool#create()

The following examples show how to use org.h2.jdbcx.JdbcConnectionPool#create() . 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 File: Client.java    From jsonde with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Client(String databaseFileName, String address, int port) {

        online = true;

        jdbcConnectionPool = JdbcConnectionPool.create(
                "jdbc:h2:" + databaseFileName + ";" + DB_CONNECTION_MODIFIERS,
                "sa", "sa");
        jdbcConnectionPool.setMaxConnections(100);
        jdbcConnectionPool.setLoginTimeout(0);

        try {

            DaoFactory.initialize(
                    jdbcConnectionPool
            );

            DaoFactory.createSchema();

        } catch (DaoException e) {
            e.printStackTrace();
        }
        networkClient = new NetworkClientImpl(address, port);
    }
 
Example 2
Source File: H2ClusterHA.java    From dew with Apache License 2.0 6 votes vote down vote up
@Override
public void init(HAConfig haConfig) throws SQLException {
    String url = "jdbc:h2:" + haConfig.getStoragePath() + haConfig.getStorageName() + ";DB_CLOSE_ON_EXIT=FALSE";
    jdbcConnectionPool = JdbcConnectionPool
            .create(url,
                    haConfig.getAuthUsername() == null ? "" : haConfig.getAuthUsername(),
                    haConfig.getAuthPassword() == null ? "" : haConfig.getAuthPassword());
    try (Connection conn = jdbcConnectionPool.getConnection(); Statement stmt = conn.createStatement()) {
        stmt.execute("CREATE TABLE IF NOT EXISTS MQ_MSG("
                + "ADDR VARCHAR(1024),"
                + "MSG_ID VARCHAR(32),"
                + "MSG TEXT,"
                + "CREATED_TIME TIMESTAMP ,"
                + "PRIMARY KEY(MSG_ID)"
                + ")");
    }
}
 
Example 3
Source File: Client.java    From jsonde with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Client(String databaseFileName) {

        online = false;

        jdbcConnectionPool = JdbcConnectionPool.create(
                "jdbc:h2:" + databaseFileName + ";" + DB_CONNECTION_MODIFIERS,
                "sa", "sa");
        jdbcConnectionPool.setMaxConnections(100);
        jdbcConnectionPool.setLoginTimeout(0);

        try {

            DaoFactory.initialize(
                    jdbcConnectionPool
            );

        } catch (DaoException e) {
            e.printStackTrace();
        }
    }
 
Example 4
Source File: EmbeddedJdbcPizzaRepositoryTests.java    From pizza-shop-example with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Before
public void setUp() {
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test;MVCC=FALSE", "", "");

    eventLog = mock(EventLog.class);
    repository = new EmbeddedJdbcPizzaRepository(eventLog,
            new Topic("pizzas"),
            pool);
    ref = repository.nextIdentity();
    pizza = Pizza.builder()
            .ref(ref)
            .size(Pizza.Size.MEDIUM)
            .kitchenOrderRef(new KitchenOrderRef())
            .eventLog(eventLog)
            .build();
}
 
Example 5
Source File: EmbeddedJdbcOnlineOrderRepositoryIntegrationTests.java    From pizza-shop-example with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Before
public void setUp() {
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test;MVCC=FALSE", "", "");

    eventLog = InProcessEventLog.instance();
    repository = new EmbeddedJdbcOnlineOrderRepository(eventLog,
            new Topic("ordering"),
            pool);
    ref = repository.nextIdentity();
    onlineOrder = OnlineOrder.builder()
            .ref(ref)
            .type(OnlineOrder.Type.PICKUP)
            .eventLog(eventLog)
            .build();
    pizza = Pizza.builder().size(Pizza.Size.MEDIUM).build();
}
 
Example 6
Source File: EmbeddedJdbcDeliveryOrderRepositoryTests.java    From pizza-shop-example with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Before
public void setUp() {
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test;MVCC=FALSE", "", "");

    eventLog = mock(EventLog.class);
    repository = new EmbeddedJdbcDeliveryOrderRepository(eventLog,
            new Topic("delivery_orders"),
            pool);
    ref = repository.nextIdentity();
    deliveryOrder = DeliveryOrder.builder()
            .ref(ref)
            .kitchenOrderRef(new KitchenOrderRef(RefStringGenerator.generateRefString()))
            .onlineOrderRef(new OnlineOrderRef(RefStringGenerator.generateRefString()))
            .pizza(DeliveryOrder.Pizza.builder().size(DeliveryOrder.Pizza.Size.MEDIUM).build())
            .eventLog(eventLog)
            .build();
}
 
Example 7
Source File: EmbeddedJdbcPaymentRepositoryIntegrationTests.java    From pizza-shop-example with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Before
public void setUp() {
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test", "", "");

    eventLog = InProcessEventLog.instance();
    repository = new EmbeddedJdbcPaymentRepository(eventLog,
            new Topic("payments"),
            pool);
    ref = repository.nextIdentity();
    payment = Payment.builder()
            .ref(ref)
            .amount(Amount.of(10, 0))
            .paymentProcessor(mock(PaymentProcessor.class))
            .eventLog(eventLog)
            .build();
}
 
Example 8
Source File: DeliveryServiceWithJdbcIntegrationTests.java    From pizza-shop-example with Do What The F*ck You Want To Public License 5 votes vote down vote up
@Before
public void setUp() {
    eventLog = InProcessEventLog.instance();
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test;MVCC=FALSE", "", "");

    DeliveryOrderRepository deliveryOrderRepository = new EmbeddedJdbcDeliveryOrderRepository(eventLog,
            new Topic("delivery_orders"),
            pool);
    orderingService = mock(OrderingService.class);
    kitchenService = mock(KitchenService.class);
    deliveryService = new DeliveryService(eventLog, deliveryOrderRepository, orderingService, kitchenService);
}
 
Example 9
Source File: DefaultOrderingServiceWithJdbcIntegrationTests.java    From pizza-shop-example with Do What The F*ck You Want To Public License 5 votes vote down vote up
@Before
public void setUp() {
    eventLog = InProcessEventLog.instance();
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test;MVCC=FALSE", "", "");
    repository = new EmbeddedJdbcOnlineOrderRepository(eventLog,
            new Topic("ordering"), pool);
    new DefaultOrderingService(eventLog, repository, mock(PaymentService.class));
}
 
Example 10
Source File: LegacyDataSourceFactory.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
public DataSource getDataSource() {
    if (connectionPool == null) {
        final String databaseUrl = getDatabaseUrl(properties);
        connectionPool = JdbcConnectionPool.create(databaseUrl, DB_USERNAME_PASSWORD, DB_USERNAME_PASSWORD);
        connectionPool.setMaxConnections(MAX_CONNECTIONS);
    }

    return connectionPool;
}
 
Example 11
Source File: MethodCallSummaryDaoTest.java    From jsonde with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    testDataSource =
            JdbcConnectionPool.create("jdbc:h2:mem:testMethodCallSummary", "sa", "sa");

    DaoFactory.initialize(testDataSource);
    DaoFactory.createSchema();

}
 
Example 12
Source File: DbH2ServerStartup.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Populate sample database.
 *
 * @throws SQLException if
 */
public static void populateDatabase() throws SQLException {
    // Try to connect to database TCP server.
    JdbcConnectionPool dataSrc = JdbcConnectionPool.create("jdbc:h2:tcp://localhost/mem:ExampleDb", "sa", "");

    // Create Person table in database.
    RunScript.execute(dataSrc.getConnection(), new StringReader(CREATE_PERSON_TABLE));

    // Populates Person table with sample data in database.
    RunScript.execute(dataSrc.getConnection(), new StringReader(POPULATE_PERSON_TABLE));
}
 
Example 13
Source File: EmbeddedDBHandler.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void createConnectionPool(String connectString, String userName, String pwd) throws OpenAS2Exception {
    // Check that a connection pool is not already running
    if (cp != null) {
        throw new OpenAS2Exception("Connection pool already initialized. Cannot create a new connection pool. Stop current one first. DB connect string:" + connectString + " :: Active pool connect string: " + this.connectString);
    }
    this.connectString = connectString;

    cp = JdbcConnectionPool.create(connectString, userName, pwd);
}
 
Example 14
Source File: MethodDaoTest.java    From jsonde with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    testDataSource =
            JdbcConnectionPool.create("jdbc:h2:target/test-database/db", "sa", "sa");
    methodDao =
            new MethodDao(testDataSource);

    methodDao.createTable();

}
 
Example 15
Source File: AuditDataSourceFactoryBean.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Object getObject() throws Exception {
    if (connectionPool == null) {

        // locate the repository directory
        String repositoryDirectoryPath = properties.getProperty(NiFiProperties.REPOSITORY_DATABASE_DIRECTORY);

        // ensure the repository directory is specified
        if (repositoryDirectoryPath == null) {
            throw new NullPointerException("Database directory must be specified.");
        }

        // create a handle to the repository directory
        File repositoryDirectory = new File(repositoryDirectoryPath);

        // get a handle to the database file
        File databaseFile = new File(repositoryDirectory, AUDIT_DATABASE_FILE_NAME);

        // format the database url
        String databaseUrl = "jdbc:h2:" + databaseFile + ";AUTOCOMMIT=OFF;DB_CLOSE_ON_EXIT=FALSE;LOCK_MODE=3";
        String databaseUrlAppend = properties.getProperty(NiFiProperties.H2_URL_APPEND);
        if (StringUtils.isNotBlank(databaseUrlAppend)) {
            databaseUrl += databaseUrlAppend;
        }

        // create the pool
        connectionPool = JdbcConnectionPool.create(databaseUrl, NF_USERNAME_PASSWORD, NF_USERNAME_PASSWORD);
        connectionPool.setMaxConnections(MAX_CONNECTIONS);

        Connection connection = null;
        ResultSet rs = null;
        Statement statement = null;
        try {
            // get a connection
            connection = connectionPool.getConnection();
            connection.setAutoCommit(false);

            // create a statement for initializing the database
            statement = connection.createStatement();

            // determine if the tables need to be created
            rs = connection.getMetaData().getTables(null, null, "ACTION", null);
            if (!rs.next()) {
                logger.info("Database not built for repository: " + databaseUrl + ".  Building now...");
                RepositoryUtils.closeQuietly(rs);

                // action table
                statement.execute(CREATE_ACTION_TABLE);

                // component details
                statement.execute(CREATE_PROCESSOR_DETAILS_TABLE);
                statement.execute(CREATE_REMOTE_PROCESS_GROUP_DETAILS_TABLE);

                // action details
                statement.execute(CREATE_MOVE_DETAILS_TABLE);
                statement.execute(CREATE_CONFIGURE_DETAILS_TABLE);
                statement.execute(CREATE_CONNECT_DETAILS_TABLE);
                statement.execute(CREATE_PURGE_DETAILS_TABLE);
            }

            // commit any changes
            connection.commit();
        } catch (SQLException sqle) {
            RepositoryUtils.rollback(connection, logger);
            throw sqle;
        } finally {
            RepositoryUtils.closeQuietly(rs);
            RepositoryUtils.closeQuietly(statement);
            RepositoryUtils.closeQuietly(connection);
        }
    }

    return connectionPool;
}
 
Example 16
Source File: H2DataSourceFactory.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public DataSource create() {
    return JdbcConnectionPool.create(DFLT_CONN_URL, "sa", "");
}
 
Example 17
Source File: DataSourceAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @return H2 pooled data source
 * @throws SQLException
 */
@Bean(destroyMethod = "dispose")
public DataSource dataSource() throws SQLException {
	final JdbcConnectionPool pool = JdbcConnectionPool.create(url, user, password);
	pool.setMaxConnections(maxPoolConnections);
	Connection con = null;
	con = pool.getConnection();

	final Flyway flyway = new Flyway();
	flyway.setLocations("classpath:sql/migration");
	flyway.setDataSource(pool);
	flyway.setSqlMigrationPrefix("VOS-");
	flyway.setIgnoreFailedFutureMigration(true);

	final JdbcTemplate tpl = new JdbcTemplate(pool);
	if (tpl.queryForObject("select count(*) from information_schema.tables where table_name = 'LOG_SOURCES'",
			int.class) == 0) {
		logger.info("H2 database not found, creating new schema and populate with default data");
		flyway.setBaselineVersion(MigrationVersion.fromVersion(DB_SETUP_VERSION));
		flyway.setBaselineOnMigrate(true);
		try {
			final ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator();
			dbPopulator.addScript(new ClassPathResource("/sql/quartz/tables_h2.sql"));
			dbPopulator.addScript(new ClassPathResource("/sql/model/schema_h2.sql"));
			dbPopulator.populate(con);
			newSchema = true;
			logger.info("Established H2 connection pool with new database");
		} finally {
			if (con != null) {
				con.close();
			}
		}
	} else {
		logger.info("Established H2 connection pool with existing database");
		if (tpl.queryForObject("select count(*) from information_schema.tables where table_name = 'schema_version'",
				int.class) == 0) {
			logger.info("Flyway's DB migration not setup in this version, set baseline version to 0.5.0");
			flyway.setBaselineVersion(MigrationVersion.fromVersion("0.5.0"));
			flyway.setBaselineOnMigrate(true);
		}
	}

	logger.debug("Migrating database, base version is: {}", flyway.getBaselineVersion());
	flyway.migrate();
	logger.debug("Database migrated from base version: {}", flyway.getBaselineVersion());

	return pool;
}
 
Example 18
Source File: PipelineMavenPluginH2Dao.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
public PipelineMavenPluginH2Dao(@Nonnull File rootDir) {
    this(JdbcConnectionPool.create("jdbc:h2:file:" + new File(rootDir, "jenkins-jobs").getAbsolutePath() + ";" +
            "AUTO_SERVER=TRUE;MULTI_THREADED=1;QUERY_CACHE_SIZE=25;JMX=TRUE", "sa", "sa"));
}
 
Example 19
Source File: AuditDataSourceFactoryBean.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Object getObject() throws Exception {
    if (connectionPool == null) {

        // locate the repository directory
        String repositoryDirectoryPath = properties.getProperty(NiFiProperties.REPOSITORY_DATABASE_DIRECTORY);

        // ensure the repository directory is specified
        if (repositoryDirectoryPath == null) {
            throw new NullPointerException("Database directory must be specified.");
        }

        // create a handle to the repository directory
        File repositoryDirectory = new File(repositoryDirectoryPath);

        // get a handle to the database file
        File databaseFile = new File(repositoryDirectory, AUDIT_DATABASE_FILE_NAME);

        // format the database url
        String databaseUrl = "jdbc:h2:" + databaseFile + ";AUTOCOMMIT=OFF;DB_CLOSE_ON_EXIT=FALSE;LOCK_MODE=3";
        String databaseUrlAppend = properties.getProperty(NiFiProperties.H2_URL_APPEND);
        if (StringUtils.isNotBlank(databaseUrlAppend)) {
            databaseUrl += databaseUrlAppend;
        }

        // create the pool
        connectionPool = JdbcConnectionPool.create(databaseUrl, NF_USERNAME_PASSWORD, NF_USERNAME_PASSWORD);
        connectionPool.setMaxConnections(MAX_CONNECTIONS);

        Connection connection = null;
        ResultSet rs = null;
        Statement statement = null;
        try {
            // get a connection
            connection = connectionPool.getConnection();
            connection.setAutoCommit(false);

            // create a statement for initializing the database
            statement = connection.createStatement();

            // determine if the tables need to be created
            rs = connection.getMetaData().getTables(null, null, "ACTION", null);
            if (!rs.next()) {
                logger.info("Database not built for repository: " + databaseUrl + ".  Building now...");
                RepositoryUtils.closeQuietly(rs);

                // action table
                statement.execute(CREATE_ACTION_TABLE);

                // component details
                statement.execute(CREATE_PROCESSOR_DETAILS_TABLE);
                statement.execute(CREATE_REMOTE_PROCESS_GROUP_DETAILS_TABLE);

                // action details
                statement.execute(CREATE_MOVE_DETAILS_TABLE);
                statement.execute(CREATE_CONFIGURE_DETAILS_TABLE);
                statement.execute(CREATE_CONNECT_DETAILS_TABLE);
                statement.execute(CREATE_PURGE_DETAILS_TABLE);
            }

            // commit any changes
            connection.commit();
        } catch (SQLException sqle) {
            RepositoryUtils.rollback(connection, logger);
            throw sqle;
        } finally {
            RepositoryUtils.closeQuietly(rs);
            RepositoryUtils.closeQuietly(statement);
            RepositoryUtils.closeQuietly(connection);
        }
    }

    return connectionPool;
}
 
Example 20
Source File: PersistenceLayerTests.java    From demo with MIT License 2 votes vote down vote up
/**
 * Get a file-based {@link JdbcConnectionPool}, which makes it easier
 * to debug database tests when they are running.
 * <p>
 * Because we set AUTO_SERVER to true, we can access this database
 * from multiple places when it starts.
 * <p>
 * This method is solely meant to be used by database tests.
 */
private static JdbcConnectionPool getFileBasedDatabaseConnectionPool() {
    return JdbcConnectionPool.create(
            "jdbc:h2:./build/db/training;AUTO_SERVER=TRUE;MODE=PostgreSQL", "", "");
}