Java Code Examples for org.h2.jdbcx.JdbcConnectionPool

The following are top voted examples for showing how to use org.h2.jdbcx.JdbcConnectionPool. 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: JInsight   File: JDBCInstrumentationTest.java   View source code 7 votes vote down vote up
@Before
public void setUp() throws Exception {
  registry = RegistryService.getMetricRegistry();

  String sqlId = new StringUniqueIdService().getUniqueId(SELECT_QUERY);
  executeStatementName = JdbcRuleHelper.EXECUTE_STATEMENT_NAME.withTags("sql", sqlId);

  presetElements = IntStream.range(0, 1000).boxed()
      .collect(Collectors.toMap(i -> UUID.randomUUID().toString(), i -> i));
  presetElementKeys = new ArrayList<>(presetElements.keySet());

  StringBuilder sb = new StringBuilder(CREATE_TABLE_STRING);
  presetElements.forEach((s, o) -> {
    sb.append("\nINSERT INTO TEST VALUES('").append(s).append("', ").append(o).append(");");
  });

  String dbName = "JDBCInstrumentationTest." + UUID.randomUUID();
  datasource = JdbcConnectionPool.create("jdbc:h2:mem:" + dbName, "h2", "h2");
  ((JdbcConnectionPool) datasource).setMaxConnections(POOL_SIZE);
  datasource.setLoginTimeout(-1);
  Connection conn = datasource.getConnection();
  RunScript.execute(conn, new StringReader(sb.toString()));
  conn.close();
}
 
Example 2
Project: servicebuilder   File: H2InMemoryDatasourceAddon.java   View source code 6 votes vote down vote up
@Override
public Addon initialize(ServiceConfig serviceConfig) {
    String databaseName = unitTest ? "" : ! isNullOrEmpty(name) ? name : "test";

    DataSource dataSource = JdbcConnectionPool.create("jdbc:h2:mem:" + databaseName + ";DB_CLOSE_DELAY=-1", "user", "password");
    scripts.forEach(script -> {

        try {
            Connection conn = dataSource.getConnection();
            conn.createStatement().executeUpdate(script);
            conn.close();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    });

    return this.withDataSource(dataSource);
}
 
Example 3
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 6 votes vote down vote up
private void testPerformance() throws SQLException {
    String url = getURL("connectionPool", true), user = getUser();
    String password = getPassword();
    JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);
    Connection conn = man.getConnection();
    int len = 1000;
    long time = System.currentTimeMillis();
    for (int i = 0; i < len; i++) {
        man.getConnection().close();
    }
    man.dispose();
    trace((int) (System.currentTimeMillis() - time));
    time = System.currentTimeMillis();
    for (int i = 0; i < len; i++) {
        DriverManager.getConnection(url, user, password).close();
    }
    trace((int) (System.currentTimeMillis() - time));
    conn.close();
}
 
Example 4
Project: jdblender   File: RunnerMybatis.java   View source code 6 votes vote down vote up
@Override
public void init(DbConnection connection) throws Exception {
    JdbcConnectionPool pool = JdbcConnectionPool.create(connection.uri, connection.username, connection.password);

    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("jdblender", transactionFactory, pool);

    Configuration cfg = new Configuration(environment);
    cfg.setMapUnderscoreToCamelCase(true);
    cfg.addMapper(BrandsMapper.class);
    cfg.addMapper(SeriesMapper.class);
    cfg.addMapper(ModelsMapper.class);
    cfg.addMapper(SparesMapper.class);

    //Create session
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(cfg);
}
 
Example 5
Project: reactor   File: H2Handler.java   View source code 6 votes vote down vote up
@Override
public void init() throws Exception {
    File dir = new File(this.dbPath);
    if (dir.exists()) {
        FileUtils.cleanDirectory(dir);
    }
    this.connPool = JdbcConnectionPool.create("jdbc:h2:" + this.dbPath + SYS_CONFIG.getExecId(), "sa", "sa");
    connPool.setMaxConnections(Integer.MAX_VALUE);
    try (Connection conn = this.getConnection()) {
        try {
            conn.prepareStatement("SELECT * FROM case_result WHERE 0;").executeQuery();
        } catch (SQLException ex) {
            LOG.warn("{}", ex.getMessage());
            this.initSchema();
        }
    }
}
 
Example 6
Project: DigitalMediaServer   File: DLNAMediaDatabase.java   View source code 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 7
Project: pipeline-maven-plugin   File: PipelineMavenPluginH2Dao.java   View source code 6 votes vote down vote up
public PipelineMavenPluginH2Dao(File rootDir) {
    rootDir.getClass(); // check non null

    File databaseFile = new File(rootDir, "jenkins-jobs");
    String jdbcUrl = "jdbc:h2:file:" + databaseFile.getAbsolutePath() + ";AUTO_SERVER=TRUE;MULTI_THREADED=1";
    if(LOGGER.isLoggable(Level.FINEST)) {
        jdbcUrl += ";TRACE_LEVEL_SYSTEM_OUT=3";
    } else if (LOGGER.isLoggable(Level.FINE)) {
        jdbcUrl += ";TRACE_LEVEL_SYSTEM_OUT=2";
    }
    LOGGER.log(Level.INFO, "Open database {0}", jdbcUrl);
    jdbcConnectionPool = JdbcConnectionPool.create(jdbcUrl, "sa", "sa");

    initializeDatabase();
    testDatabase();
}
 
Example 8
Project: horizon-blocknet   File: Db.java   View source code 6 votes vote down vote up
static void init() {
    long maxCacheSize = Nhz.getIntProperty("nhz.dbCacheKB");
    if (maxCacheSize == 0) {
        maxCacheSize = Runtime.getRuntime().maxMemory() / (1024 * 2);
    }
    String dbUrl = Constants.isTestnet ? Nhz.getStringProperty("nhz.testDbUrl") : Nhz.getStringProperty("nhz.dbUrl");
    if (! dbUrl.contains("CACHE_SIZE=")) {
        dbUrl += ";CACHE_SIZE=" + maxCacheSize;
    }
    Logger.logDebugMessage("Database jdbc url set to: " + dbUrl);
    cp = JdbcConnectionPool.create(dbUrl, "sa", "sa");
    cp.setMaxConnections(Nhz.getIntProperty("nhz.maxDbConnections"));
    cp.setLoginTimeout(Nhz.getIntProperty("nhz.dbLoginTimeout"));
    int defaultLockTimeout = Nhz.getIntProperty("nhz.dbDefaultLockTimeout") * 1000;
    try (Connection con = cp.getConnection();
         Statement stmt = con.createStatement()) {
        stmt.executeUpdate("SET DEFAULT_LOCK_TIMEOUT " + defaultLockTimeout);
    } catch (SQLException e) {
        throw new RuntimeException(e.toString(), e);
    }
    DbVersion.init();
}
 
Example 9
Project: freemarker-dynamic-ql-builder   File: FreemarkerDynamicQlBuilderJdbcTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void initialize() throws ClassNotFoundException, SQLException {
    pool = JdbcConnectionPool.create("jdbc:h2:mem:test", "sa", "");

    Connection connection = getConnection();
    try {
        Statement statement = connection.createStatement();
        statement.execute("CREATE TABLE users (" +
                "userId INT PRIMARY KEY, " +
                "name VARCHAR(255), " +
                "birthyear INT, " +
                "employeeType VARCHAR(16)) " +
                "AS SELECT * FROM CSVREAD('src/test/resources/META-INF/qltest/jdbc/users.csv')");
    } finally {
        closeQuietly(connection);
    }
}
 
Example 10
Project: OCRaptor   File: H2Database.java   View source code 6 votes vote down vote up
/**
 *
 *
 * @return
 * @throws ClassNotFoundException
 */
public H2Database initConnectionPool(boolean force) throws ClassNotFoundException {
  Class.forName(JDBC_EMBEDDED_DRIVER);

  if (force && connectionPool != null) {
    connectionPool.dispose();
  }

  if (connectionPool == null || force) {
    // *INDENT-OFF*
    connectionPool = JdbcConnectionPool.create(
        "jdbc:h2:"
        + dataPath.getAbsolutePath()
        + ";CREATE=TRUE", "sa", "sa");
    // *INDENT-ON*
    connectionPool.setMaxConnections(50);
  }

  return this;
}
 
Example 11
Project: jsonde   File: Client.java   View source code 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 12
Project: jsonde   File: Client.java   View source code 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 13
Project: nxt-client   File: Db.java   View source code 6 votes vote down vote up
static void init()
{
  long l = Nxt.getIntProperty("nxt.dbCacheKB");
  if (l == 0L) {
    l = Runtime.getRuntime().maxMemory() / 2048L;
  }
  String str = Nxt.getStringProperty("nxt.dbUrl");
  if (!str.contains("CACHE_SIZE=")) {
    str = str + ";CACHE_SIZE=" + l;
  }
  Logger.logDebugMessage("Database jdbc url set to: " + str);
  cp = JdbcConnectionPool.create(str, "sa", "sa");
  cp.setMaxConnections(Nxt.getIntProperty("nxt.maxDbConnections"));
  cp.setLoginTimeout(Nxt.getIntProperty("nxt.dbLoginTimeout"));
  DbVersion.init();
}
 
Example 14
Project: lightblue-rdbms   File: RDBMSUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void testGetDataSource() throws Exception {
    // Create initial context
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    // already tried System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
    InitialContext ic = new InitialContext();

    ic.createSubcontext("java:");
    ic.createSubcontext("java:/comp");
    ic.createSubcontext("java:/comp/env");
    ic.createSubcontext("java:/comp/env/jdbc");

    JdbcConnectionPool ds = JdbcConnectionPool.create("jdbc:h2:file:/tmp/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa");

    String jndiName = "java:/mydatasource";
    ic.bind(jndiName, ds);


    DataSource dataSource = RDBMSUtils.getDataSource(jndiName);
    assertEquals("org.h2.jdbcx.JdbcConnectionPool",dataSource.getClass().getCanonicalName());

}
 
Example 15
Project: jentrata   File: JDBCMessageStoreTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    dataSource = JdbcConnectionPool.create("jdbc:h2:mem:" + getTestMethodName(), "sa", "sa");
    assertThatTableDoesNotExist("repository");
    RepositoryManagerFactory repositoryManagerFactory = new RepositoryManagerFactory();
    repositoryManagerFactory.setDataSource(dataSource);
    messageStore = new JDBCMessageStore();
    messageStore.setUuidGenerator(new UUIDGenerator());
    messageStore.setRepositoryManager(repositoryManagerFactory.createRepositoryManager());
    messageStore.init();
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from(MessageStore.DEFAULT_MESSAGE_STORE_ENDPOINT)
                .bean(messageStore,"store")
                .bean(messageStore,"storeMessage")
            .routeId("testPostsgresMessageStore");
        }
    };
}
 
Example 16
Project: amberdb   File: AmberDbFactory.java   View source code 6 votes vote down vote up
public static AmberSession openAmberDb(String dbUrl, String dbUser, String dbPassword, String rootPath) throws InstantiationException, IllegalAccessException,
        ClassNotFoundException, SQLException {
    DataSource ds = null;
    AmberSession sess = null;

    try {
        MysqlDataSource mds = new MysqlDataSource();
        mds.setURL(dbUrl);
        mds.setUser(dbUser);
        mds.setPassword(dbPassword);
        ds = mds;
        sess = openAmberDb(ds, rootPath);
    } catch (Throwable e) {
        h2Test = true;
        // This is for build integration site which does not have
        // direct access to the mysql data source.
        DriverManager.registerDriver(new org.h2.Driver());
        dbUrl = "jdbc:h2:" + Paths.get(".").resolve("graph") + ";MVCC=true;DATABASE_TO_UPPER=false";
        dbUser = "garfield";
        dbPassword = "odde";
        ds = JdbcConnectionPool.create(dbUrl, dbUser, dbPassword);
        sess = openAmberDb(ds, rootPath);
    }

    return sess;
}
 
Example 17
Project: amberdb   File: AmberDbTest.java   View source code 6 votes vote down vote up
@Test
public void testSuspendResume() throws IOException {
    
    AmberDb adb = new AmberDb(JdbcConnectionPool.create("jdbc:h2:"+folder.getRoot()+"persist;DATABASE_TO_UPPER=false","per","per"), folder.getRoot().getAbsolutePath());
    
    Long sessId;
    Long bookId;
    
    Work book;
    
    try (AmberSession db = adb.begin()) {
        book = db.addWork();
        bookId = book.getId();
        book.setTitle("Test book");
        sessId = db.suspend();
    }

    AmberDb adb2 = new AmberDb(JdbcConnectionPool.create("jdbc:h2:"+folder.getRoot()+"persist;DATABASE_TO_UPPER=false","per","per"), folder.getRoot().getAbsolutePath());
    try (AmberSession db = adb2.resume(sessId)) {
        
        // now, can we retrieve the files ?
        Work book2 = db.findWork(bookId);
        assertEquals(book, book2);
        db.close();
    }
}
 
Example 18
Project: DropletPlayerData   File: DropletPlayerData.java   View source code 6 votes vote down vote up
@Override
public void onEnable() {
	config = new DatabaseConfiguration(this.getDataFolder());
	config.load();

	String path;
	try {
		path = getDataFolder().getCanonicalPath();
	} catch (IOException e) {
		path = getDataFolder().getPath();
	}
	final String connUrl = DatabaseConfiguration.CONNECTION_STRING.getString().replaceAll(Pattern.quote("${plugin_data_dir}"), Matcher.quoteReplacement(path));
	final String user = DatabaseConfiguration.USERNAME.getString();
	getLogger().info("Attempting to connect to " + connUrl + ", with user [" + user + "]");

	pool = JdbcConnectionPool.create(connUrl, user, DatabaseConfiguration.PASSWORD.getString());
	pool.setMaxConnections(DatabaseConfiguration.POOL_SIZE.getInt());
	getEngine().getEventManager().registerEvents(new DataEventListener(this), this);

	getLogger().info("enabled.");
}
 
Example 19
Project: simple-hostel-management   File: DatabaseUtils.java   View source code 5 votes vote down vote up
public static Connection getH2Connection(Path databasePath) throws SQLException {

        if (currentH2Pool == null) {
            currentH2Pool = new HashMap<>();
        }

        String key = databasePath.toAbsolutePath().toString();
        if (currentH2Pool.get(key) == null) {
            currentH2Pool.put(key, JdbcConnectionPool.create(getH2JdbcUrlFor(databasePath), "", ""));
        }

        return currentH2Pool.get(key).getConnection();
    }
 
Example 20
Project: nifi-registry   File: DataSourceFactory.java   View source code 5 votes vote down vote up
@Bean
@Primary
public DataSource getDataSource() {
    if (connectionPool == null) {
        // locate the repository directory
        final String repositoryDirectoryPath = properties.getDatabaseDirectory();

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

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

        // get a handle to the database file
        final File databaseFile = new File(repositoryDirectory, 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.getDatabaseUrlAppend();
        if (StringUtils.isNotBlank(databaseUrlAppend)) {
            databaseUrl += databaseUrlAppend;
        }

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

    return connectionPool;
}
 
Example 21
Project: ThriftyPaxos   File: JdbcConnectionPool.java   View source code 5 votes vote down vote up
protected JdbcConnectionPool(ConnectionPoolDataSource dataSource) {
    this.dataSource = dataSource;
    if (dataSource != null) {
        try {
            logWriter = dataSource.getLogWriter();
        } catch (SQLException e) {
            // ignore
        }
    }
}
 
Example 22
Project: ThriftyPaxos   File: JdbcConnectionPool.java   View source code 5 votes vote down vote up
/**
 * Constructs a new connection pool for H2 databases.
 *
 * @param url the database URL of the H2 connection
 * @param user the user name
 * @param password the password
 * @return the connection pool
 */
public static JdbcConnectionPool create(String url, String user,
        String password) {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(url);
    ds.setUser(user);
    ds.setPassword(password);
    return new JdbcConnectionPool(ds);
}
 
Example 23
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 5 votes vote down vote up
private void testShutdown() throws SQLException {
    String url = getURL("connectionPool2", true), user = getUser();
    String password = getPassword();
    JdbcConnectionPool cp = JdbcConnectionPool.create(url, user, password);
    StringWriter w = new StringWriter();
    cp.setLogWriter(new PrintWriter(w));
    Connection conn1 = cp.getConnection();
    Connection conn2 = cp.getConnection();
    conn1.close();
    conn2.createStatement().execute("shutdown immediately");
    cp.dispose();
    assertTrue(w.toString().length() > 0);
    cp.dispose();
}
 
Example 24
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 5 votes vote down vote up
private void testWrongUrl() {
    JdbcConnectionPool cp = JdbcConnectionPool.create(
            "jdbc:wrong:url", "", "");
    try {
        cp.getConnection();
    } catch (SQLException e) {
        assertEquals(8001, e.getErrorCode());
    }
    cp.dispose();
}
 
Example 25
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 5 votes vote down vote up
private void testTimeout() throws Exception {
    String url = getURL("connectionPool", true), user = getUser();
    String password = getPassword();
    final JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);
    man.setLoginTimeout(1);
    createClassProxy(man.getClass());
    assertThrows(IllegalArgumentException.class, man).
            setMaxConnections(-1);
    man.setMaxConnections(2);
    // connection 1 (of 2)
    Connection conn = man.getConnection();
    Task t = new Task() {
        @Override
        public void call() {
            while (!stop) {
                // this calls notifyAll
                man.setMaxConnections(1);
                man.setMaxConnections(2);
            }
        }
    };
    t.execute();
    long time = System.currentTimeMillis();
    try {
        // connection 2 (of 1 or 2) may fail
        man.getConnection();
        // connection 3 (of 1 or 2) must fail
        man.getConnection();
        fail();
    } catch (SQLException e) {
        assertTrue(e.toString().toLowerCase().contains("timeout"));
        time = System.currentTimeMillis() - time;
        assertTrue("timeout after " + time + " ms", time > 1000);
    } finally {
        conn.close();
        t.get();
    }

    man.dispose();
}
 
Example 26
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 5 votes vote down vote up
private void testUncommittedTransaction() throws SQLException {
    String url = getURL("connectionPool", true), user = getUser();
    String password = getPassword();
    JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);

    assertEquals(30, man.getLoginTimeout());
    man.setLoginTimeout(1);
    assertEquals(1, man.getLoginTimeout());
    man.setLoginTimeout(0);
    assertEquals(30, man.getLoginTimeout());
    assertEquals(10, man.getMaxConnections());

    PrintWriter old = man.getLogWriter();
    PrintWriter pw = new PrintWriter(new StringWriter());
    man.setLogWriter(pw);
    assertTrue(pw == man.getLogWriter());
    man.setLogWriter(old);

    Connection conn1 = man.getConnection();
    assertTrue(conn1.getAutoCommit());
    conn1.setAutoCommit(false);
    conn1.close();
    assertTrue(conn1.isClosed());

    Connection conn2 = man.getConnection();
    assertTrue(conn2.getAutoCommit());
    conn2.close();

    man.dispose();
}
 
Example 27
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 5 votes vote down vote up
private void testKeepOpen() throws Exception {
    JdbcConnectionPool man = getConnectionPool(1);
    Connection conn = man.getConnection();
    Statement stat = conn.createStatement();
    stat.execute("create local temporary table test(id int)");
    conn.close();
    conn = man.getConnection();
    stat = conn.createStatement();
    stat.execute("select * from test");
    conn.close();
    man.dispose();
}
 
Example 28
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 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 29
Project: ThriftyPaxos   File: TestConnectionPool.java   View source code 5 votes vote down vote up
private void testConnect() throws SQLException {
    JdbcConnectionPool pool = getConnectionPool(3);
    for (int i = 0; i < 100; i++) {
        Connection conn = pool.getConnection();
        conn.close();
    }
    pool.dispose();
    DataSource ds = pool;
    assertThrows(IllegalStateException.class, ds).
            getConnection();
    assertThrows(UnsupportedOperationException.class, ds).
            getConnection(null, null);
}
 
Example 30
Project: jdblender   File: RunnerCayenne.java   View source code 5 votes vote down vote up
@Override
public void init(DbConnection connection) {
    cayenneRuntime = ServerRuntimeBuilder.builder()
        .addModule(new CayenneModule())
        .addConfig("cayenne-project.xml")
        .dataSource(JdbcConnectionPool.create(connection.uri, connection.username, connection.password))
        .build();
    context = cayenneRuntime.newContext();
}
 
Example 31
Project: jdblender   File: RunnerSpringData.java   View source code 5 votes vote down vote up
@Override
public void init(DbConnection connection) throws Exception {
    JdbcConnectionPool pool = JdbcConnectionPool.create(connection.uri, connection.username, connection.password);
    H2DS.init(pool);

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
    runner = ctx.getBean(FrameworkRunner.class);
}
 
Example 32
Project: eaudit4j   File: JdbcDsProcessorTest.java   View source code 5 votes vote down vote up
/**
 * Test that we can retrieve a connection.
 */
@Test
public void getConnectionTest()
        throws InvocationTargetException, IllegalAccessException, SQLException {

    // get a data source and add it to the ProcessingObjects
    JdbcConnectionPool cp = JdbcConnectionPool.create(H2Server.URL, H2Server.USER, H2Server.PASSWORD);
    ProcessingObjects processingObjects = new ProcessingObjects();
    processingObjects.add(DS_NAME, cp);

    Map<String, String> props = new HashMap<>();

    // the JDBC Processor configuration
    props.put(MapBasedJdbcPropsBuilder.KEY_DATA_SOURCE_NAME, DS_NAME);

    JdbcProperties jdbcProps = MapBasedJdbcPropsBuilder.build(props);
    CommonProperties commonProps = MapBasedCommonPropsBuilder.build(props);
    Processor processor = new JdbcDsProcessor();
    processor.init(commonProps);

    Connection con = (Connection) method_getConnection.invoke(processor, jdbcProps, processingObjects);

    String error = "The connection is null";
    assertThat(error, con, is(notNullValue()));

    con.close();
}
 
Example 33
Project: eaudit4j   File: JndiUtil.java   View source code 5 votes vote down vote up
public static void setUpJndiConnectionPool(int maxConnections, String jndiName)
        throws NamingException {

    if (poolCreated) {
        LOG.info("Pool already exists, and JNDI name already registered");
    } else {
        LOG.info("Creating pool and registering JNDI name");

        // create a data source from the H2 default connection pool of the test database
        JdbcConnectionPool pool = JdbcConnectionPool.create(H2Server.URL, H2Server.USER, H2Server.PASSWORD);
        pool.setMaxConnections(maxConnections);
        pool.setLoginTimeout(1); // set a short login timeout in case of errors

        // this requires the tomcat dependency to work, but is required to init and bind the context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

        // init and bind
        Context context = new InitialContext();
        context.createSubcontext("java:");
        context.createSubcontext("java:/comp");
        context.createSubcontext("java:/comp/env");
        context.createSubcontext("java:/comp/env/jdbc");
        context.bind(jndiName, pool);

        poolCreated = true;
    }
}
 
Example 34
Project: tiny-rxjava-jdbc   File: H2ConnectionProvider.java   View source code 5 votes vote down vote up
public H2ConnectionProvider(String name, String options) {
  try {
    Class.forName("org.h2.Driver");
  } catch (ClassNotFoundException e) {
    log.error("Error loading class for H2 JDBC driver", e);
    throw new RuntimeException(e);
  }
  connectionPool =  JdbcConnectionPool.create("jdbc:h2:mem:" + name + options, "sa", "sa");
}
 
Example 35
Project: pipeline-maven-plugin   File: PipelineMavenPluginH2Dao.java   View source code 5 votes vote down vote up
public PipelineMavenPluginH2Dao(JdbcConnectionPool jdbcConnectionPool) {
    jdbcConnectionPool.getClass(); // check non null

    this.jdbcConnectionPool = jdbcConnectionPool;

    initializeDatabase();
    testDatabase();
}
 
Example 36
Project: pipeline-maven-plugin   File: PipelineMavenPluginH2Dao.java   View source code 5 votes vote down vote up
public PipelineMavenPluginH2Dao(String jdbcUrl, String username, String password) {
    jdbcUrl.getClass(); // check non null
    username.getClass(); // check non null
    password.getClass(); // check non null

    this.jdbcConnectionPool = JdbcConnectionPool.create(jdbcUrl, username, password);
    LOGGER.log(Level.FINE, "Open database {0}", jdbcUrl);

    initializeDatabase();
}
 
Example 37
Project: pipeline-maven-plugin   File: PipelineMavenPluginH2DaoTest.java   View source code 5 votes vote down vote up
@Before
public void before() {
    jdbcConnectionPool = JdbcConnectionPool.create("jdbc:h2:mem:", "sa", "");
    SqlTestsUtils.silentlyDeleteTableRows(jdbcConnectionPool, "JENKINS_BUILD", "MAVEN_ARTIFACT", "MAVEN_DEPENDENCY", "GENERATED_MAVEN_ARTIFACT");
    dao = new PipelineMavenPluginH2Dao(jdbcConnectionPool);

}
 
Example 38
Project: pipeline-maven-plugin   File: SqlTestsUtils.java   View source code 5 votes vote down vote up
public static void dump(String sql, JdbcConnectionPool jdbcConnectionPool, PrintStream out) throws RuntimeSqlException {
    try (Connection connection = jdbcConnectionPool.getConnection()) {
        out.println("# DUMP " + sql);
        out.println();
        try (Statement stmt = connection.createStatement()) {
            try (ResultSet rst = stmt.executeQuery(sql)) {
                dump(rst, out);
            }
        }
        out.println("----");
    } catch (SQLException e) {
        throw new RuntimeSqlException(e);
    }
}
 
Example 39
Project: pipeline-maven-plugin   File: SqlTestsUtils.java   View source code 5 votes vote down vote up
public static void silentlyDeleteTableRows(JdbcConnectionPool jdbcConnectionPool, String... tables) {
    for (String table : tables) {
        try (Connection cnn = jdbcConnectionPool.getConnection()) {
            try (Statement stmt = cnn.createStatement()) {
                int deleted = stmt.executeUpdate("delete from " + table);
            }
        } catch (SQLException e) {
            if (e.getErrorCode() == 42102) {
                // ignore "table not found"
            } else {
                throw new RuntimeSqlException(e);
            }
        }
    }
}
 
Example 40
Project: service-base   File: TestDataSource.java   View source code 5 votes vote down vote up
public static void setUpDemoH2Resource() {
    try {
        JdbcConnectionPool dataPool = JdbcConnectionPool.create(
                "jdbc:h2:mem:base;DB_CLOSE_DELAY=-1", "blah","blah-blah");
        new Resource(null, "jdbc/conName", dataPool);
    } catch (NamingException ex) {
        logger.info("Error setting up demo resource \n" + ex);
    }
}