Java Examples for org.h2.jdbcx.JdbcDataSource

The following java examples will help you to understand the usage of org.h2.jdbcx.JdbcDataSource. These source code samples are taken from different open source projects.

Example 1
Project: manager.v3-master  File: DatabaseConnectionPoolTest.java View source code
public void testConnectionPoolwithH2() throws SQLException {
    // Setup in-memory H2 JDBC DataSource;
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:testdb");
    ds.setUser("sa");
    ds.setPassword("sa");
    DatabaseConnectionPool pool = new DatabaseConnectionPool(ds);
    //Test getConnection
    Connection c = pool.getConnection();
    assertTrue(c.isValid(1));
    //Test release connection
    pool.releaseConnection(c);
    Connection newOne = pool.getConnection();
    assertTrue(newOne.isValid(1));
    // verify same released connection is returned.
    assertEquals(c, newOne);
    //verify close connection.
    pool.releaseConnection(newOne);
    pool.closeConnections();
    assertTrue(newOne.isClosed());
}
Example 2
Project: Karaf-Tutorial-master  File: PersonRepoTest.java View source code
@Test
public void testList() throws SQLException {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setUrl("jdbc:h2:mem:person;DB_CLOSE_DELAY=-1");
    new Migrator().prepare(ds);
    PersonRepo personRepo = new PersonRepo();
    personRepo.ds = ds;
    List<Person> persons = personRepo.list();
    Person person = persons.iterator().next();
    Assert.assertEquals(1, person.id);
    Assert.assertEquals("Chris", person.name);
//Assert.assertEquals(42, person.age);
}
Example 3
Project: rxjava-jdbc-master  File: DatabaseViaDataSourceTest.java View source code
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 4
Project: infinispan-master  File: JdbcStringBasedStoreManagedFactoryFunctionalTest.java View source code
@Before
public void setUp() {
    Bundle bundle = FrameworkUtil.getBundle(getClass());
    BundleContext bundleContext = bundle.getBundleContext();
    org.h2.jdbcx.JdbcDataSource service = new org.h2.jdbcx.JdbcDataSource();
    service.setURL("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1");
    service.setUser("sa");
    service.setPassword("");
    bundleContext.registerService(javax.sql.DataSource.class, service, null);
}
Example 5
Project: junit-benchmarks-master  File: TestH2Consumer.java View source code
@AfterClass
public static void verify() throws Exception {
    // Check DB upgrade process.
    DbVersions ver = h2consumer.getDbVersion();
    int maxVersion = DbVersions.UNINITIALIZED.version;
    for (DbVersions v : DbVersions.values()) maxVersion = Math.max(maxVersion, v.version);
    assertEquals(maxVersion, ver.version);
    h2consumer.close();
    assertTrue(dbFileFull.exists());
    // Check if rows have been added.
    final JdbcDataSource ds = new org.h2.jdbcx.JdbcDataSource();
    ds.setURL("jdbc:h2:" + dbFile.getAbsolutePath());
    ds.setUser("sa");
    final Connection connection = ds.getConnection();
    ResultSet rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM TESTS");
    assertTrue(rs.next());
    assertEquals(2, rs.getInt(1));
    rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM RUNS");
    assertTrue(rs.next());
    assertEquals(1, rs.getInt(1));
    rs = connection.createStatement().executeQuery("SELECT CUSTOM_KEY FROM RUNS");
    assertTrue(rs.next());
    assertEquals(CUSTOM_KEY_VALUE, rs.getString(1));
    connection.close();
    assertTrue(dbFileFull.delete());
}
Example 6
Project: sql2o-master  File: H2Tests.java View source code
@Before
public void setUp() throws Exception {
    driverClassName = "org.h2.Driver";
    url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
    user = "sa";
    pass = "";
    org.h2.jdbcx.JdbcDataSource datasource = new org.h2.jdbcx.JdbcDataSource();
    datasource.setURL(url);
    datasource.setUser(user);
    datasource.setPassword(pass);
    ds = datasource;
}
Example 7
Project: hibernate-orm-master  File: H2SkipAutoCommitTest.java View source code
@Override
protected DataSource dataSource() {
    DataSource dataSource = ReflectionUtil.newInstance("org.h2.jdbcx.JdbcDataSource");
    ReflectionUtil.setProperty(dataSource, "URL", Environment.getProperties().getProperty(AvailableSettings.URL));
    ReflectionUtil.setProperty(dataSource, "user", Environment.getProperties().getProperty(AvailableSettings.USER));
    ReflectionUtil.setProperty(dataSource, "password", Environment.getProperties().getProperty(AvailableSettings.PASS));
    return dataSource;
}
Example 8
Project: jqm-master  File: DbConfig.java View source code
@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) {
        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 9
Project: lsql-master  File: AbstractLSqlTest.java View source code
@BeforeMethod
public void beforeMethod() throws SQLException {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:testdb;mode=postgresql");
    Connection connection = ds.getConnection();
    Flyway flyway = new Flyway();
    flyway.setDataSource(ds);
    flyway.clean();
    this.lSql = new LSql(new H2Dialect(), ConnectionProviders.fromInstance(connection));
}
Example 10
Project: Sparqlify-master  File: H2TestCase.java View source code
public static void main(String[] args) throws Exception {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test_mem");
    ds.setUser("sa");
    ds.setPassword("sa");
    Connection conn = ds.getConnection();
    conn.createStatement().executeUpdate("DROP TABLE IF EXISTS person;");
    conn.createStatement().executeUpdate("CREATE TABLE person (id INT PRIMARY KEY, name VARCHAR, age INT)");
    conn.createStatement().executeUpdate("INSERT INTO person VALUES (1, 'Anne', 20)");
    conn.createStatement().executeUpdate("INSERT INTO person VALUES (2, 'Bob', 22)");
    ResultSet rs = conn.createStatement().executeQuery("SELECT name AS foo FROM person");
    ResultSetMetaData meta = rs.getMetaData();
    for (int i = 1; i <= meta.getColumnCount(); ++i) {
        String colName = meta.getColumnLabel(i);
        // Expected: Foo
        System.out.println("Column [" + i + "]: " + colName);
    }
}
Example 11
Project: smsc-server-master  File: DBMessageManagerFactory.java View source code
private void configureEmbeddedMode() {
    if (this.datasource == null) {
        if (StringUtils.isEmpty(this.url)) {
            throw new SmscServerConfigurationException("When using embedded mode and no datasource provided, URL paramater is required!");
        }
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL(this.url);
        ds.setUser("sa");
        ds.setPassword("");
        this.datasource = ds;
    }
    if (this.sqlCreateTable == null) {
        this.sqlCreateTable = this.getProfileSQL("createtable");
    }
    if (this.sqlInsertMessage == null) {
        this.sqlInsertMessage = this.getProfileSQL("insert");
    }
    if (this.sqlUpdateMessage == null) {
        this.sqlUpdateMessage = this.getProfileSQL("update");
    }
    if (this.sqlSelectMessage == null) {
        this.sqlSelectMessage = this.getProfileSQL("select");
    }
    if (this.sqlSelectUserMessage == null) {
        this.sqlSelectUserMessage = this.getProfileSQL("select-user");
    }
    if (this.sqlSelectLatestReplacableMessage == null) {
        this.sqlSelectLatestReplacableMessage = this.getProfileSQL("selectlatestreplacable");
    }
}
Example 12
Project: resthub-spring-stack-master  File: HikariCPDataSourceFactoryTest.java View source code
@Test
public void testHikariDataSourceConfigAllProps() throws Exception {
    Properties configProps = new Properties();
    configProps.put("dataSourceClassName", "org.resthub.jpa.sql.FakeDataSource");
    configProps.put("dataSource.url", "jdbc:h2:mem:resthub");
    configProps.put("dataSource.user", "sa");
    configProps.put("dataSource.password", "");
    configProps.put("connectionCustomizerClassName", "com.zaxxer.hikari.TestConnectionCustomization");
    configProps.put("connectionInitSql", "select 1");
    configProps.put("connectionTestQuery", "select 1");
    configProps.put("connectionTimeout", 1000L);
    configProps.put("dataSourceClassName", "org.resthub.jpa.sql.FakeDataSource");
    configProps.put("idleTimeout", 60000L);
    configProps.put("leakDetectionThreshold", 100000L);
    configProps.put("minimumIdle", 2);
    configProps.put("maximumPoolSize", 10);
    configProps.put("maxLifetime", 200000L);
    configProps.put("poolName", "testPoolName");
    configProps.put("transactionIsolation", "TRANSACTION_READ_COMMITTED");
    configProps.put("autoCommit", false);
    configProps.put("jdbc4ConnectionTest", false);
    configProps.put("initializationFailFast", true);
    configProps.put("registerMbeans", true);
    DataSource dataSource = hikariCPDataSourceFactory.create(HikariCPTestDataSource.class, configProps);
    Assertions.assertThat(dataSource).isNotNull().isInstanceOf(HikariCPTestDataSource.class);
    HikariCPTestDataSource testDataSource = (HikariCPTestDataSource) dataSource;
    Assertions.assertThat(testDataSource).isNotNull();
    Assertions.assertThat(testDataSource.getConfig()).isNotNull();
    Assertions.assertThat(testDataSource.getConfig().getConnectionCustomizerClassName()).isEqualTo((String) configProps.get("connectionCustomizerClassName"));
    Assertions.assertThat(testDataSource.getConfig().getConnectionInitSql()).isEqualTo((String) configProps.get("connectionInitSql"));
    Assertions.assertThat(testDataSource.getConfig().getConnectionTestQuery()).isEqualTo((String) configProps.get("connectionTestQuery"));
    Assertions.assertThat(testDataSource.getConfig().getConnectionTimeout()).isEqualTo((Long) configProps.get("connectionTimeout"));
    Assertions.assertThat(testDataSource.getConfig().getDataSourceClassName()).isEqualTo((String) configProps.get("dataSourceClassName"));
    Assertions.assertThat(testDataSource.getConfig().getIdleTimeout()).isEqualTo((Long) configProps.get("idleTimeout"));
    Assertions.assertThat(testDataSource.getConfig().getLeakDetectionThreshold()).isEqualTo((Long) configProps.get("leakDetectionThreshold"));
    Assertions.assertThat(testDataSource.getConfig().getMaximumPoolSize()).isEqualTo((Integer) configProps.get("maximumPoolSize"));
    Assertions.assertThat(testDataSource.getConfig().getMaxLifetime()).isEqualTo((Long) configProps.get("maxLifetime"));
    Assertions.assertThat(testDataSource.getConfig().getPoolName()).isEqualTo((String) configProps.get("poolName"));
    Field field = Connection.class.getField((String) configProps.get("transactionIsolation"));
    int level = field.getInt(null);
    Assertions.assertThat(testDataSource.getConfig().getTransactionIsolation()).isEqualTo(level);
    Assertions.assertThat(testDataSource.getConfig().isAutoCommit()).isEqualTo((Boolean) configProps.get("autoCommit"));
    Assertions.assertThat(testDataSource.getConfig().isJdbc4ConnectionTest()).isEqualTo((Boolean) configProps.get("jdbc4ConnectionTest"));
    Assertions.assertThat(testDataSource.getConfig().isInitializationFailFast()).isEqualTo((Boolean) configProps.get("initializationFailFast"));
    Assertions.assertThat(testDataSource.getConfig().isRegisterMbeans()).isEqualTo((Boolean) configProps.get("registerMbeans"));
    // check concrete datasource parameters
    Assertions.assertThat(testDataSource.isWrapperFor(FakeDataSource.class)).isTrue();
    JdbcDataSource ds = (JdbcDataSource) TestElf.getPool(testDataSource).getDataSource();
    Assertions.assertThat(ds.getURL()).isNotNull().isEqualTo((String) configProps.get("dataSource.url"));
    Assertions.assertThat(ds.getUser()).isNotNull().isEqualTo((String) configProps.get("dataSource.user"));
    Assertions.assertThat(ds.getPassword()).isNotNull().isEqualTo((String) configProps.get("dataSource.password"));
}
Example 13
Project: camel-cookbook-examples-master  File: XATransactionTest.java View source code
@Override
protected CamelContext createCamelContext() throws Exception {
    SimpleRegistry registry = new SimpleRegistry();
    // JMS setup
    ActiveMQXAConnectionFactory xaConnectionFactory = new ActiveMQXAConnectionFactory();
    xaConnectionFactory.setBrokerURL(broker.getTcpConnectorUri());
    registry.put("connectionFactory", xaConnectionFactory);
    atomikosConnectionFactoryBean = new AtomikosConnectionFactoryBean();
    atomikosConnectionFactoryBean.setXaConnectionFactory(xaConnectionFactory);
    atomikosConnectionFactoryBean.setUniqueResourceName("xa.activemq");
    atomikosConnectionFactoryBean.setMaxPoolSize(10);
    atomikosConnectionFactoryBean.setIgnoreSessionTransactedFlag(false);
    registry.put("atomikos.connectionFactory", atomikosConnectionFactoryBean);
    // JDBC setup
    JdbcDataSource jdbcDataSource = EmbeddedDataSourceFactory.getJdbcDataSource("sql/schema.sql");
    AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
    atomikosDataSourceBean.setXaDataSource(jdbcDataSource);
    atomikosDataSourceBean.setUniqueResourceName("xa.h2");
    registry.put("atomikos.dataSource", atomikosDataSourceBean);
    // Atomikos setup
    userTransactionManager = new UserTransactionManager();
    userTransactionManager.setForceShutdown(false);
    userTransactionManager.init();
    UserTransactionImp userTransactionImp = new UserTransactionImp();
    userTransactionImp.setTransactionTimeout(300);
    JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
    jtaTransactionManager.setTransactionManager(userTransactionManager);
    jtaTransactionManager.setUserTransaction(userTransactionImp);
    registry.put("jta.transactionManager", jtaTransactionManager);
    SpringTransactionPolicy propagationRequired = new SpringTransactionPolicy();
    propagationRequired.setTransactionManager(jtaTransactionManager);
    propagationRequired.setPropagationBehaviorName("PROPAGATION_REQUIRED");
    registry.put("PROPAGATION_REQUIRED", propagationRequired);
    auditLogDao = new AuditLogDao(jdbcDataSource);
    CamelContext camelContext = new DefaultCamelContext(registry);
    {
        SqlComponent sqlComponent = new SqlComponent();
        sqlComponent.setDataSource(atomikosDataSourceBean);
        camelContext.addComponent("sql", sqlComponent);
    }
    {
        // transactional JMS component
        ActiveMQComponent activeMQComponent = new ActiveMQComponent();
        activeMQComponent.setConnectionFactory(atomikosConnectionFactoryBean);
        activeMQComponent.setTransactionManager(jtaTransactionManager);
        camelContext.addComponent("jms", activeMQComponent);
    }
    {
        // non-transactional JMS component setup for test purposes
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(broker.getTcpConnectorUri());
        ActiveMQComponent activeMQComponent = new ActiveMQComponent();
        activeMQComponent.setConnectionFactory(connectionFactory);
        activeMQComponent.setTransactionManager(jtaTransactionManager);
        camelContext.addComponent("nonTxJms", activeMQComponent);
    }
    return camelContext;
}
Example 14
Project: cdi-jpa-jta-generic-dao-master  File: ProductServiceTest.java View source code
@BeforeClass
public static void setUp() throws Exception {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:test;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
    dataSource.setUser("sa");
    dataSource.setPassword("");
    InitialContext context = new InitialContext();
    context.bind("java:/jdbc/testDS1", dataSource);
}
Example 15
Project: cdo-master  File: NodeType.java View source code
protected IRepository createRepository(Node node) {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:" + node.getFolder() + "/db/repository");
    IMappingStrategy mappingStrategy = CDODBUtil.createHorizontalMappingStrategy(true, true);
    IDBAdapter dbAdapter = new H2Adapter();
    IDBConnectionProvider dbConnectionProvider = dbAdapter.createConnectionProvider(dataSource);
    IStore store = CDODBUtil.createStore(mappingStrategy, dbAdapter, dbConnectionProvider);
    Map<String, String> props = new HashMap<String, String>();
    props.put(IRepository.Props.OVERRIDE_UUID, REPOSITORY_NAME);
    props.put(IRepository.Props.SUPPORTING_AUDITS, "true");
    props.put(IRepository.Props.SUPPORTING_BRANCHES, "true");
    props.put(IRepository.Props.ID_GENERATION_LOCATION, "CLIENT");
    IRepository repository = createRepository(node, store, props);
    repository.setInitialPackages(CompanyPackage.eINSTANCE);
    activateRepository(repository);
    return repository;
}
Example 16
Project: che-master  File: H2DBTestServer.java View source code
@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 17
Project: DevTools-master  File: H2DBTestServer.java View source code
@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 18
Project: jboss-as7-jbpm-module-master  File: VariablePersistenceStrategyTest.java View source code
@Before
public void setUp() throws Exception {
    ds1 = new PoolingDataSource();
    ds1.setUniqueName("jdbc/testDS1");
    ds1.setClassName("org.h2.jdbcx.JdbcDataSource");
    ds1.setMaxPoolSize(3);
    ds1.setAllowLocalTransactions(true);
    ds1.getDriverProperties().put("user", "sa");
    ds1.getDriverProperties().put("password", "sasa");
    ds1.getDriverProperties().put("URL", "jdbc:h2:mem:mydb");
    ds1.init();
    emf = Persistence.createEntityManagerFactory("org.drools.persistence.jpa");
}
Example 19
Project: jbpm-examples-master  File: KieServerMain.java View source code
public static void main(String[] args) throws Exception {
    Swarm container = new Swarm();
    // Configure the Datasources subsystem with a driver and a datasource
    container.fraction(new DatasourcesFraction().jdbcDriver("h2", ( d) -> {
        d.driverClassName("org.h2.Driver");
        d.xaDatasourceClass("org.h2.jdbcx.JdbcDataSource");
        d.driverModuleName("com.h2database.h2");
    }).dataSource("ExampleDS", ( ds) -> {
        ds.driverName("h2");
        ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        ds.userName("sa");
        ds.password("sa");
    }));
    // configure transactions
    container.fraction(TransactionsFraction.createDefaultFraction());
    System.out.println("\tBuilding kie server deployable...");
    JAXRSArchive deployment = createDeployment(container);
    System.out.println("\tStarting Wildfly Swarm....");
    container.start();
    System.out.println("\tConfiguring kjars to be auto deployed to server " + Arrays.toString(args));
    installKJars(args);
    System.out.println("\tDeploying kie server ....");
    container.deploy(deployment);
}
Example 20
Project: jbpm-master  File: AbstractCaseServicesBaseTest.java View source code
protected void buildDatasource() {
    ds = new PoolingDataSource();
    ds.setUniqueName("jdbc/testDS1");
    //NON XA CONFIGS
    ds.setClassName("org.h2.jdbcx.JdbcDataSource");
    ds.setMaxPoolSize(3);
    ds.setAllowLocalTransactions(true);
    ds.getDriverProperties().put("user", "sa");
    ds.getDriverProperties().put("password", "sasa");
    ds.getDriverProperties().put("URL", "jdbc:h2:mem:mydb");
    ds.init();
}
Example 21
Project: jdbi-master  File: TestOnDemandSqlObject.java View source code
@Before
public void setUp() throws Exception {
    ds = new JdbcDataSource();
    // in MVCC mode h2 doesn't shut down immediately on all connections closed, so need random db name
    ds.setURL(String.format("jdbc:h2:mem:%s;MVCC=TRUE", UUID.randomUUID()));
    db = Jdbi.create(ds);
    db.installPlugin(new SqlObjectPlugin());
    handle = db.open();
    handle.execute("create table something (id int primary key, name varchar(100))");
    db.installPlugin(tracker);
}
Example 22
Project: light-task-scheduler-master  File: H2DataSourceProvider.java View source code
private DataSource createDataSource(Config config) throws ClassNotFoundException {
    String url = config.getParameter(ExtConfig.JDBC_URL);
    String username = config.getParameter(ExtConfig.JDBC_USERNAME);
    String password = config.getParameter(ExtConfig.JDBC_PASSWORD);
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl(url);
    dataSource.setUser(username);
    dataSource.setPassword(password);
    return dataSource;
}
Example 23
Project: meta-server-master  File: WebServerBasedTests.java View source code
@BeforeClass
public static void setup() throws Exception {
    String secret = "edit";
    // make a unique database for each testing class
    String dbUri = "jdbc:h2:mem:test_" + atomCount.getAndIncrement();
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(dbUri);
    GeoLocationService geoService = new DummyGeoLocationService();
    // Open a dummy connection to the in-memory database to keep it alive
    dummyConn = DriverManager.getConnection(dbUri);
    dataBase = new JooqDatabase(ds, geoService);
    File cacheFolder = tempFolder.newFolder("module", "cache");
    ModuleListModelImpl moduleListModel = new ModuleListModelImpl(cacheFolder.toPath(), new DummyExtractor());
    releaseRepo = new DummyArtifactRepo(RepoType.RELEASE);
    addRelease("Core", "Core-0.53.1.jar_info.json");
    snapshotRepo = new DummyArtifactRepo(RepoType.SNAPSHOT);
    addSnapshot("ChrisVolume1OST", "ChrisVolume1OST-0.2.1-20150608.034649-1.jar_info.json");
    addSnapshot("MusicDirector", "MusicDirector-0.2.1-20150608.041945-1.jar_info.json");
    moduleListModel.addRepository(releaseRepo);
    moduleListModel.addRepository(snapshotRepo);
    moduleListModel.updateAllModules();
    ServerListModel serverListModel = new ServerListModelImpl(dataBase, SERVER_TABLE, secret);
    webServer = JettyMain.createServer(PORT, new AboutServlet(), // the server list servlet
    new ServerServlet(serverListModel), // the module list servlet
    new ModuleServlet(moduleListModel));
    webServer.start();
    dataBase.createTable(SERVER_TABLE);
    GeoLocation geo = geoService.resolve("localhost");
    firstEntry = new ServerEntry("localhost", 25000);
    firstEntry.setName("myName");
    firstEntry.setOwner("Tester");
    firstEntry.setCountry(geo.getCountry());
    firstEntry.setStateprov(geo.getStateOrProvince());
    firstEntry.setCity(geo.getCity());
    dataBase.insert(SERVER_TABLE, firstEntry);
}
Example 24
Project: rdfbean-master  File: SchemaExport.java View source code
public static void main(String[] args) throws SQLException {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:target/h2");
    ds.setUser("sa");
    ds.setPassword("");
    Connection conn = ds.getConnection();
    // export
    try {
        Configuration configuration = new DefaultConfiguration();
        SQLTemplates templates = new H2Templates();
        Repository repository = new RDBRepository(configuration, ds, templates, new MemoryIdSequence());
        repository.initialize();
        NamingStrategy namingStrategy = new DefaultNamingStrategy();
        MetaDataExporter exporter = new MetaDataExporter();
        exporter.setPackageName("com.mysema.rdfbean.rdb.schema");
        exporter.setTargetFolder(new File("src/main/java"));
        exporter.setNamingStrategy(namingStrategy);
        exporter.export(conn.getMetaData());
    } finally {
        conn.close();
    }
}
Example 25
Project: spring-data-jdbc-repository-master  File: StandaloneUsageTest.java View source code
@Test
public void shouldStartRepositoryWithoutSpring() throws Exception {
    //given
    final JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL(JDBC_URL);
    final UserRepository userRepository = new UserRepository("users");
    userRepository.setDataSource(dataSource);
    //optional
    userRepository.setSqlGenerator(new SqlGenerator());
    //when
    final List<User> list = userRepository.findAll();
    //then
    assertThat(list).isEmpty();
}
Example 26
Project: wildfly-swarm-master  File: Main.java View source code
public static void main(String... args) throws Exception {
    Swarm swarm = new Swarm(args);
    swarm.fraction(new DatasourcesFraction().jdbcDriver("h2", ( d) -> {
        d.driverClassName("org.h2.Driver");
        d.xaDatasourceClass("org.h2.jdbcx.JdbcDataSource");
        d.driverModuleName("com.h2database.h2");
    }).dataSource("ExampleDS", ( ds) -> {
        ds.driverName("h2");
        ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        ds.userName("sa");
        ds.password("sa");
    }));
    swarm.start().deploy();
}
Example 27
Project: jooby-master  File: JdbcTest.java View source code
@Test
public void memdb() throws Exception {
    Config config = ConfigFactory.parseResources(getClass(), "jdbc.conf");
    Config dbconf = config.withValue("db", ConfigValueFactory.fromAnyRef("mem")).withValue("application.charset", fromAnyRef("UTF-8")).withValue("application.name", fromAnyRef("jdbctest")).withValue("application.tmpdir", fromAnyRef("target")).withValue("runtime.processors-x2", fromAnyRef(POOL_SIZE)).resolve();
    new MockUnit(Env.class, Config.class, Binder.class).expect(currentTimeMillis(123)).expect(props("org.h2.jdbcx.JdbcDataSource", "jdbc:h2:mem:123;DB_CLOSE_DELAY=-1", "h2.123", "sa", "", false)).expect(hikariConfig()).expect(hikariDataSource()).expect(serviceKey("123")).expect(onStop).run( unit -> {
        new Jdbc().configure(unit.get(Env.class), dbconf, unit.get(Binder.class));
    });
}
Example 28
Project: ode-master  File: SelectObjectTest.java View source code
@Override
protected void setUp() throws Exception {
    JdbcDataSource h2 = new JdbcDataSource();
    h2.setURL("jdbc:h2:mem:" + new GUID().toString() + ";DB_CLOSE_DELAY=-1");
    h2.setUser("sa");
    _ds = h2;
    _txm = new EmbeddedGeronimoFactory().getTransactionManager();
    factory = new BPELDAOConnectionFactoryImpl();
    factory.setDataSource(_ds);
    factory.setTransactionManager(_txm);
    Properties props = new Properties();
    props.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=false)");
    factory.init(props);
    _txm.begin();
}
Example 29
Project: Phynixx-master  File: AtomikosPersistenceConfig.java View source code
@Bean(destroyMethod = "close")
public PoolingDataSource dataSource() throws SQLException {
    PoolingDataSource ds = new PoolingDataSource();
    // a h2 in-memory database...make sure to use the XADatasources for other databases
    ds.setClassName("org.h2.jdbcx.JdbcDataSource");
    ds.setUniqueName("ds1");
    ds.setMaxPoolSize(10);
    // Ansonsten keine automatische Enlistement als XAResource
    ds.setAllowLocalTransactions(true);
    Properties props = new Properties();
    // muss gross geschrieben werden; Propertery heisst URL statt url
    props.put("URL", "jdbc:h2:mem:ds1");
    props.put("user", "sa");
    props.put("password", "");
    ds.setUniqueName("ds1");
    ds.setDriverProperties(props);
    return ds;
}
Example 30
Project: wildfly-master  File: DataSourceTestCase.java View source code
private void testAddDataSourceConnectionProperties() throws Exception {
    // add data source
    cli.sendLine("data-source add --name=TestDS --jndi-name=java:jboss/datasources/TestDS --driver-name=h2 --datasource-class=org.h2.jdbcx.JdbcDataSource --connection-properties={\"url\"=>\"jdbc:h2:mem:test;DB_CLOSE_DELAY=-1\"}");
    // check the data source is listed
    cli.sendLine("cd /subsystem=datasources/data-source");
    cli.sendLine("ls");
    String ls = cli.readOutput();
    assertTrue(ls.contains("TestDS"));
    // check that it is available through JNDI
    String jndiClass = JndiServlet.lookup(url.toString(), "java:jboss/datasources/TestDS");
    Assert.assertTrue(javax.sql.DataSource.class.isAssignableFrom(Class.forName(jndiClass)));
}
Example 31
Project: AdServing-master  File: H2TrackingService.java View source code
@Override
public void open(BaseContext context) throws ServiceException {
    // TODO Auto-generated method stub
    DataSource ds = context.get(EmbeddedBaseContext.EMBEDDED_TRACKING_DATASOURCE, DataSource.class, null);
    if (ds == null) {
        throw new ServiceException("DataSource can not be null");
    }
    ((JdbcDataSource) ds).setPassword("sa");
    ((JdbcDataSource) ds).setUser("sa");
    int maxcon = context.get(EmbeddedBaseContext.EMBEDDED_TRACKING_DATASOURCE_MAX_CONNECTIONS, int.class, 50);
    this.poolMgr = new MiniConnectionPoolManager((ConnectionPoolDataSource) ds, maxcon);
    initTable();
}
Example 32
Project: HotSUploader-master  File: DataSourceFactoryBean.java View source code
private JdbcDataSource getOrmLiteDataSource(File database) {
    final JdbcDataSource dataSource = new JdbcDataSource();
    final String databaseName;
    if (releaseManager == null || releaseManager.getCurrentVersion().equals("Development")) {
        databaseName = database.toString() + "-dev";
    } else {
        databaseName = database.toString();
    }
    final String url = "jdbc:h2:" + databaseName;
    LOG.info("Setting up DataSource with URL " + url);
    dataSource.setUrl(url);
    return dataSource;
}
Example 33
Project: learning-master  File: Step4Test.java View source code
@Before
public void createAndBind() throws Exception {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:test");
    dataSource.setUser("sa");
    dataSource.setPassword("sa");
    connection = dataSource.getConnection();
    String createStatement = "CREATE TABLE CUSTOMER(" + "SSN VARCHAR(11) PRIMARY KEY," + "FIRSTNAME VARCHAR(50)," + "LASTNAME VARCHAR(50)," + "STREETADDRESS VARCHAR(255)," + "CITY VARCHAR(60)," + "STATE VARCHAR(2)," + "POSTALCODE VARCHAR(60)," + "DOB DATE," + "CHECKINGBALANCE DECIMAL(14,2)," + "SAVINGSBALANCE DECIMAL(14,2));";
    String insertCustomer = "INSERT INTO CUSTOMER VALUES " + "('755-55-5555', 'Joseph', 'Smith', '123 Street', 'Elm', 'NC', '27808', '1970-01-01', 14000.40, 22000.99);";
    connection.createStatement().executeUpdate("DROP TABLE IF EXISTS CUSTOMER");
    connection.createStatement().executeUpdate(createStatement);
    connection.createStatement().executeUpdate(insertCustomer);
    namingMixIn = new NamingMixIn();
    namingMixIn.initialize();
    bindDataSource(namingMixIn.getInitialContext(), "java:jboss/datasources/CustomerDS", dataSource);
}
Example 34
Project: miniprofiler-jvm-master  File: Main.java View source code
public static void main(String... args) throws Exception {
    RatpackServer.start( server -> server.serverConfig(ServerConfig.builder().baseDir(BaseDir.find())).registry(Guice.registry( bindings -> {
        bindings.module(TextTemplateModule.class);
        bindings.module(MiniProfilerHikariModule.class,  hikariConfig -> {
            hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
            hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:miniprofiler;DB_CLOSE_DELAY=-1");
        });
        bindings.module(MiniProfilerModule.class,  profilerConfig -> {
            profilerConfig.uiConfig.setPosition(ProfilerUiConfig.Position.LEFT);
        });
        bindings.add(new DataSetup());
        bindings.bind(TestHandler.class);
    })).handlers( chain -> chain.prefix(MiniProfilerHandlerChain.DEFAULT_PREFIX, MiniProfilerHandlerChain.class).files( f -> f.dir("public")).prefix("page",  c -> c.insert(MiniProfilerStartProfilingHandlers.class).get(TestHandler.class))));
}
Example 35
Project: narayana-master  File: TestCommitMarkableResourceReturnUnknownOutcomeFrom1PCCommit.java View source code
@Test
public void testRMFAILAfterCommit() throws Exception {
    jtaPropertyManager.getJTAEnvironmentBean().setNotifyCommitMarkableResourceRecoveryModuleOfCompleteBranches(false);
    final JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:JBTMDB;MVCC=TRUE;DB_CLOSE_DELAY=-1");
    // Test code
    Utils.createTables(dataSource.getConnection());
    // We can't just instantiate one as we need to be using the
    // same one as
    // the transaction
    // manager would have used to mark the transaction for GC
    CommitMarkableResourceRecordRecoveryModule commitMarkableResourceRecoveryModule = null;
    Vector recoveryModules = manager.getModules();
    if (recoveryModules != null) {
        Enumeration modules = recoveryModules.elements();
        while (modules.hasMoreElements()) {
            RecoveryModule m = (RecoveryModule) modules.nextElement();
            if (m instanceof CommitMarkableResourceRecordRecoveryModule) {
                commitMarkableResourceRecoveryModule = (CommitMarkableResourceRecordRecoveryModule) m;
            } else if (m instanceof XARecoveryModule) {
                XARecoveryModule xarm = (XARecoveryModule) m;
                xarm.addXAResourceRecoveryHelper(new XAResourceRecoveryHelper() {

                    public boolean initialise(String p) throws Exception {
                        return true;
                    }

                    public XAResource[] getXAResources() throws Exception {
                        return new XAResource[] { xaResource };
                    }
                });
            }
        }
    }
    javax.transaction.TransactionManager tm = com.arjuna.ats.jta.TransactionManager.transactionManager();
    tm.begin();
    Uid get_uid = ((TransactionImple) tm.getTransaction()).get_uid();
    Connection localJDBCConnection = dataSource.getConnection();
    localJDBCConnection.setAutoCommit(false);
    nonXAResource = new JDBCConnectableResource(localJDBCConnection) {

        @Override
        public void commit(Xid arg0, boolean arg1) throws XAException {
            super.commit(arg0, arg1);
            throw new XAException(XAException.XAER_RMFAIL);
        }
    };
    tm.getTransaction().enlistResource(nonXAResource);
    xaResource = new SimpleXAResource();
    tm.getTransaction().enlistResource(xaResource);
    localJDBCConnection.createStatement().execute("INSERT INTO foo (bar) VALUES (1)");
    tm.commit();
    assertTrue(xaResource.wasCommitted());
    Xid committed = ((JDBCConnectableResource) nonXAResource).getStartedXid();
    assertNotNull(committed);
    InputObjectState uids = new InputObjectState();
    StoreManager.getRecoveryStore().allObjUids(new AtomicAction().type(), uids);
    Uid uid = UidHelper.unpackFrom(uids);
    assertTrue(uid.equals(get_uid));
    // Belt and braces but we don't expect the CMR to be removed anyway as
    // the RM is "offline"
    manager.scan();
    manager.scan();
    // The recovery module has to perform lookups
    new InitialContext().rebind("commitmarkableresource", dataSource);
    assertTrue(commitMarkableResourceRecoveryModule.wasCommitted("commitmarkableresource", committed));
    // This will complete the atomicaction
    manager.scan();
    StoreManager.getRecoveryStore().allObjUids(new AtomicAction().type(), uids);
    uid = UidHelper.unpackFrom(uids);
    assertTrue(uid.equals(Uid.nullUid()));
    // This is when the CMR deletes are done due to ordering
    manager.scan();
    // of the recovery modules
    assertFalse(commitMarkableResourceRecoveryModule.wasCommitted("commitmarkableresource", committed));
}
Example 36
Project: PermissionsEx-master  File: TestImplementationInterface.java View source code
@Override
public DataSource getDataSourceForURL(String url) {
    if (url.startsWith("jdbc:h2")) {
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL(url);
        return ds;
    } else if (url.startsWith("jdbc:mysql")) {
        try {
            return new MariaDbDataSource(url);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    } else if (url.startsWith("jdbc:postgresql")) {
        PGSimpleDataSource ds = new PGSimpleDataSource();
        ds.setUrl(url);
        return ds;
    }
    throw new IllegalArgumentException("Unsupported database implementation!");
}
Example 37
Project: quickstarts-master  File: CamelSqlBindingTest.java View source code
@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 38
Project: registry-master  File: HikariBasicConfig.java View source code
// Hikari config to connect to H2 databases. Useful for integration tests
public static Map<String, Object> getH2HikariConfig() {
    Map<String, Object> config = new HashMap<>();
    config.put("dataSourceClassName", "org.h2.jdbcx.JdbcDataSource");
    //        In memory configuration. Faster, useful for integration tests
    config.put("dataSource.URL", "jdbc:h2:mem:test;MODE=MySQL;DATABASE_TO_UPPER=false");
    //        config.put("dataSource.URL", "jdbc:h2:~/test;MODE=MySQL;DATABASE_TO_UPPER=false");
    return config;
}
Example 39
Project: tester-master  File: DBServiceImpl.java View source code
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 40
Project: ABC-Go-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts(liquiBasePropertyResolver.getProperty("context"));
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourcePropertyResolver.getProperty("dataSourceClassName"))) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 41
Project: agile-itsm-master  File: ConnectionProviderAbstractTest.java View source code
@BeforeClass
public static void setUpClass() throws Exception {
    if (getConnection().isClosed()) {
        connection = openConnection();
    }
    try (Statement stmt = getConnection().createStatement()) {
        stmt.executeUpdate(String.format("create user if not exists %s password '%s'", EMBEDDED_JAVADB_JDBC_USER, EMBEDDED_JAVADB_JDBC_PASSWORD));
        stmt.executeUpdate(String.format("alter user %s set password '%s'", EMBEDDED_JAVADB_JDBC_USER, EMBEDDED_JAVADB_JDBC_PASSWORD));
        stmt.executeUpdate(String.format("alter user %s admin true", EMBEDDED_JAVADB_JDBC_USER));
    }
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    context = new InitialContext();
    context.createSubcontext(JNDI_JAVA);
    context.createSubcontext(JNDI_JAVA_JDBC);
    final JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(EMBEDDED_JAVADB_JDBC_URL);
    ds.setUser(EMBEDDED_JAVADB_JDBC_USER);
    ds.setPassword(EMBEDDED_JAVADB_JDBC_PASSWORD);
    final JNDIFactory jndiFactory = new JNDIFactory();
    ReflectionUtils.setField(jndiFactory, "context", context);
    jndiFactory.putResource(context, JNDI_DATASOURCE, ds);
}
Example 42
Project: Bam-master  File: DatabaseTestSettings.java View source code
public DataSource lookup(SQLDataSetDef def) throws Exception {
    String url = connectionSettings.getProperty("url");
    String user = connectionSettings.getProperty("user");
    String password = connectionSettings.getProperty("password");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(url);
    if (!StringUtils.isBlank(user)) {
        ds.setUser(user);
    }
    if (!StringUtils.isBlank(password)) {
        ds.setPassword(password);
    }
    return ds;
}
Example 43
Project: BikeMan-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts("development, production");
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 44
Project: CAJPII-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts("development, production");
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 45
Project: cbe-master  File: AppTest.java View source code
/**
     * Register a data source with JNDI for all unit tests in this test suite.
     *
     * @return The suite of tests being tested.
     */
public static Test suite() throws Exception {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:cbe");
    ds.setUser("sa");
    ds.setPassword("sa");
    Context ctx = new InitialContext();
    ctx.createSubcontext("java:comp/env");
    ctx.bind("jdbc/cbe", ds);
    return new TestSuite(AppTest.class);
}
Example 46
Project: cloudtm-data-platform-master  File: JBossTSTest.java View source code
@BeforeClass
public static void setUp() throws Exception {
    FileHelper.delete(tempDirectory);
    tempDirectory.mkdir();
    //DataSource configuration
    final String url = "jdbc:h2:file:./test-tmp/h2db";
    final String user = "sa";
    final String password = "";
    //H2 DataSource creation
    final JdbcDataSource underlyingDataSource = new JdbcDataSource();
    underlyingDataSource.setURL(url);
    underlyingDataSource.setUser(user);
    underlyingDataSource.setPassword(password);
    //build JBoss-bound DataSource
    DataSource ds = new JBossTADataSourceBuilder().setXADataSource(underlyingDataSource).setUser(user).setPassword(password).setTimeout(//infinite transaction
    0).createDataSource();
    PersistenceUnitInfoBuilder pub = new PersistenceUnitInfoBuilder();
    final PersistenceUnitInfo unitInfo = pub.setExcludeUnlistedClasses(true).setJtaDataSource(ds).setPersistenceProviderClassName(HibernatePersistence.class.getName()).setPersistenceUnitName("jbossjta").setPersistenceXMLSchemaVersion("2.0").setSharedCacheMode(SharedCacheMode.NONE).setValidationMode(ValidationMode.NONE).setTransactionType(PersistenceUnitTransactionType.JTA).addManagedClassNames(Tweet.class.getName()).addProperty("hibernate.transaction.manager_lookup_class", JBossTSStandaloneTransactionManagerLookup.class.getName()).addProperty("hibernate.dialect", H2Dialect.class.getName()).addProperty(Environment.HBM2DDL_AUTO, "create-drop").addProperty(Environment.SHOW_SQL, "true").addProperty(//I don't pool connections by JTA transaction. Leave the work to Hibernate Core
    Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_TRANSACTION.toString()).addProperty("hibernate.search.default.directory_provider", "ram").create();
    final HibernatePersistence hp = new HibernatePersistence();
    factory = hp.createContainerEntityManagerFactory(unitInfo, new HashMap());
}
Example 47
Project: dashbuilder-master  File: DatabaseTestSettings.java View source code
public DataSource lookup(SQLDataSetDef def) throws Exception {
    String url = connectionSettings.getProperty("url");
    String user = connectionSettings.getProperty("user");
    String password = connectionSettings.getProperty("password");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(url);
    if (!StringUtils.isBlank(user)) {
        ds.setUser(user);
    }
    if (!StringUtils.isBlank(password)) {
        ds.setPassword(password);
    }
    return ds;
}
Example 48
Project: droolsjbpm-master  File: VariablePersistenceStrategyTest.java View source code
@Before
public void setUp() throws Exception {
    ds1 = new PoolingDataSource();
    ds1.setUniqueName("jdbc/testDS1");
    ds1.setClassName("org.h2.jdbcx.JdbcDataSource");
    ds1.setMaxPoolSize(3);
    ds1.setAllowLocalTransactions(true);
    ds1.getDriverProperties().put("user", "sa");
    ds1.getDriverProperties().put("password", "sasa");
    ds1.getDriverProperties().put("URL", "jdbc:h2:mem:mydb");
    ds1.init();
    emf = Persistence.createEntityManagerFactory("org.drools.persistence.jpa");
}
Example 49
Project: felix-master  File: H2Activator.java View source code
@Override
public void start(BundleContext context) throws Exception {
    ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
    Dictionary<String, String> props = new Hashtable<String, String>();
    props.put("dataSourceName", "test");
    context.registerService(DataSource.class.getName(), ds, props);
    loadData(ds);
    //Register the H2 console servlet
    Dictionary<String, String> servletProps = new Hashtable<String, String>();
    servletProps.put("alias", "/h2");
    servletProps.put("init.webAllowOthers", "true");
    context.registerService(Servlet.class.getName(), new WebServlet(), servletProps);
}
Example 50
Project: geoserver-master  File: H2TestSupport.java View source code
@Override
public void close() throws SQLException {
    conn.close();
    // Verify that all the connections are closed by opening a new one and checking if the 
    // database is empty.
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test");
    try (Connection testConn = ds.getConnection()) {
        try (ResultSet rs = testConn.getMetaData().getTables(null, null, null, new String[] { "TABLE" })) {
            boolean result = false;
            while (rs.next()) {
                result = true;
            //System.out.printf("%s\n", rs.getString("TABLE_NAME"));
            }
            assertThat(result, describedAs("connection closed", is(false)));
        }
    }
}
Example 51
Project: h2-bitmap-master  File: TestXA.java View source code
private void testRollbackWithoutPrepare() throws Exception {
    if (config.memory) {
        return;
    }
    Xid xid = new Xid() {

        public int getFormatId() {
            return 3145;
        }

        public byte[] getGlobalTransactionId() {
            return new byte[] { 1, 2, 3, 4, 5, 6, 6, 7, 8 };
        }

        public byte[] getBranchQualifier() {
            return new byte[] { 34, 43, 33, 3, 3, 3, 33, 33, 3 };
        }
    };
    deleteDb("xa");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(getURL("xa", true));
    ds.setPassword(getPassword());
    Connection dm = ds.getConnection();
    Statement stat = dm.createStatement();
    stat.execute("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, VAL INT)");
    stat.execute("INSERT INTO TEST(ID,VAL) VALUES (1,1)");
    dm.close();
    XAConnection c = ds.getXAConnection();
    XAResource xa = c.getXAResource();
    Connection connection = c.getConnection();
    xa.start(xid, XAResource.TMJOIN);
    PreparedStatement ps = connection.prepareStatement("UPDATE TEST SET VAL=? WHERE ID=?");
    ps.setInt(1, new Random().nextInt());
    ps.setInt(2, 1);
    ps.close();
    xa.rollback(xid);
    connection.close();
    c.close();
    deleteDb("xa");
}
Example 52
Project: H2-Mirror-master  File: TestXA.java View source code
private void testRollbackWithoutPrepare() throws Exception {
    if (config.memory) {
        return;
    }
    Xid xid = new Xid() {

        @Override
        public int getFormatId() {
            return 3145;
        }

        @Override
        public byte[] getGlobalTransactionId() {
            return new byte[] { 1, 2, 3, 4, 5, 6, 6, 7, 8 };
        }

        @Override
        public byte[] getBranchQualifier() {
            return new byte[] { 34, 43, 33, 3, 3, 3, 33, 33, 3 };
        }
    };
    deleteDb("xa");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(getURL("xa", true));
    ds.setPassword(getPassword());
    Connection dm = ds.getConnection();
    Statement stat = dm.createStatement();
    stat.execute("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, VAL INT)");
    stat.execute("INSERT INTO TEST(ID,VAL) VALUES (1,1)");
    dm.close();
    XAConnection c = ds.getXAConnection();
    XAResource xa = c.getXAResource();
    Connection connection = c.getConnection();
    xa.start(xid, XAResource.TMJOIN);
    PreparedStatement ps = connection.prepareStatement("UPDATE TEST SET VAL=? WHERE ID=?");
    ps.setInt(1, new Random().nextInt());
    ps.setInt(2, 1);
    ps.close();
    xa.rollback(xid);
    connection.close();
    c.close();
    deleteDb("xa");
}
Example 53
Project: H2-Research-master  File: TestXA.java View source code
private void testRollbackWithoutPrepare() throws Exception {
    if (config.memory) {
        return;
    }
    Xid xid = new Xid() {

        @Override
        public int getFormatId() {
            return 3145;
        }

        @Override
        public byte[] getGlobalTransactionId() {
            return new byte[] { 1, 2, 3, 4, 5, 6, 6, 7, 8 };
        }

        @Override
        public byte[] getBranchQualifier() {
            return new byte[] { 34, 43, 33, 3, 3, 3, 33, 33, 3 };
        }
    };
    deleteDb("xa");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(getURL("xa", true));
    ds.setPassword(getPassword());
    Connection dm = ds.getConnection();
    Statement stat = dm.createStatement();
    stat.execute("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, VAL INT)");
    stat.execute("INSERT INTO TEST(ID,VAL) VALUES (1,1)");
    dm.close();
    XAConnection c = ds.getXAConnection();
    XAResource xa = c.getXAResource();
    Connection connection = c.getConnection();
    xa.start(xid, XAResource.TMJOIN);
    PreparedStatement ps = connection.prepareStatement("UPDATE TEST SET VAL=? WHERE ID=?");
    ps.setInt(1, new Random().nextInt());
    ps.setInt(2, 1);
    ps.close();
    xa.rollback(xid);
    connection.close();
    c.close();
    deleteDb("xa");
}
Example 54
Project: h2database-master  File: TestXA.java View source code
private void testRollbackWithoutPrepare() throws Exception {
    if (config.memory) {
        return;
    }
    Xid xid = new Xid() {

        @Override
        public int getFormatId() {
            return 3145;
        }

        @Override
        public byte[] getGlobalTransactionId() {
            return new byte[] { 1, 2, 3, 4, 5, 6, 6, 7, 8 };
        }

        @Override
        public byte[] getBranchQualifier() {
            return new byte[] { 34, 43, 33, 3, 3, 3, 33, 33, 3 };
        }
    };
    deleteDb("xa");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(getURL("xa", true));
    ds.setPassword(getPassword());
    Connection dm = ds.getConnection();
    Statement stat = dm.createStatement();
    stat.execute("CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, VAL INT)");
    stat.execute("INSERT INTO TEST(ID,VAL) VALUES (1,1)");
    dm.close();
    XAConnection c = ds.getXAConnection();
    XAResource xa = c.getXAResource();
    Connection connection = c.getConnection();
    xa.start(xid, XAResource.TMJOIN);
    PreparedStatement ps = connection.prepareStatement("UPDATE TEST SET VAL=? WHERE ID=?");
    ps.setInt(1, new Random().nextInt());
    ps.setInt(2, 1);
    ps.close();
    xa.rollback(xid);
    connection.close();
    c.close();
    deleteDb("xa");
}
Example 55
Project: jena-sparql-api-master  File: SparqlTest.java View source code
@Test
public void testMultiThreaded() throws InterruptedException, ClassNotFoundException, SQLException, IOException {
    int nThreads = 4;
    int nResources = 50;
    int nLoops = 100;
    Model model = createTestModel(nResources);
    QueryExecutionFactory qefBase = new QueryExecutionFactoryModel(model);
    QueryExecutionFactory qef = qefBase;
    //        QueryExecutionFactory qef2 = new QueryExecutionFactoryModel(model);
    //        QueryExecutionFactory qef3 = new QueryExecutionFactoryModel(model);
    qef = new QueryExecutionFactoryRetry(qef, 5, 1);
    // Add delay in order to be nice to the remote server (delay in milli seconds)
    //qef = new QueryExecutionFactoryDelay(qef, 1);
    // Set up a cache
    // Cache entries are valid for 1 day
    long timeToLive = 24l * 60l * 60l * 1000l;
    // This creates a 'cache' folder, with a database file named 'sparql.db'
    // Technical note: the cacheBackend's purpose is to only deal with streams,
    // whereas the frontend interfaces with higher level classes - i.e. ResultSet and Model
    Class.forName("org.h2.Driver");
    //        JdbcDataSource dataSource = new JdbcDataSource();
    //        dataSource.setURL("jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE");
    //        dataSource.setUser("sa");
    //        dataSource.setPassword("sa");
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("sa");
    String schemaResourceName = "/org/aksw/jena_sparql_api/cache/cache-schema-pgsql.sql";
    InputStream in = SparqlTest.class.getResourceAsStream(schemaResourceName);
    if (in == null) {
        throw new RuntimeException("Failed to load resource: " + schemaResourceName);
    }
    InputStreamReader reader = new InputStreamReader(in);
    Connection conn = dataSource.getConnection();
    try {
        RunScript.execute(conn, reader);
    } finally {
        conn.close();
    }
    CacheBackendDao dao = new CacheBackendDaoPostgres();
    CacheBackend cacheBackend = new CacheBackendDataSource(dataSource, dao);
    CacheFrontend cacheFrontend = new CacheFrontendImpl(cacheBackend);
    qef = new QueryExecutionFactoryCacheEx(qef, cacheFrontend);
    //
    //        // Add pagination
    qef = new QueryExecutionFactoryPaginated(qef, 900);
    QueryExecutionFactoryCompare qefCompare = new QueryExecutionFactoryCompare(qef, qefBase);
    ExecutorService executors = Executors.newFixedThreadPool(nThreads);
    Random rand = new Random();
    Collection<Callable<Integer>> callables = new ArrayList<>();
    for (int i = 0; i < nThreads; ++i) {
        Callable<Integer> callable = new QueryCallable(nLoops, rand, nResources, qefCompare);
        callables.add(callable);
    }
    List<Future<Integer>> futures = executors.invokeAll(callables);
    executors.shutdown();
    executors.awaitTermination(20, TimeUnit.SECONDS);
    for (Future<Integer> future : futures) {
        try {
            future.get();
        } catch (Exception e) {
            logger.error("Test case failed: ", e);
        }
    }
}
Example 56
Project: jhipster-example-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts("development, production");
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 57
Project: jhipster-ionic-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts(liquiBasePropertyResolver.getProperty("context"));
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourcePropertyResolver.getProperty("dataSourceClassName"))) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 58
Project: jhipster_myapp-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts(liquiBasePropertyResolver.getProperty("context"));
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourcePropertyResolver.getProperty("dataSourceClassName"))) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 59
Project: live-chat-engine-master  File: BaseMemSqlTest.java View source code
@Before
public void initDB() throws Exception {
    Class.forName("org.h2.Driver");
    //1-err,2-info,3-debug
    int logMode = 1;
    String url = "jdbc:h2:mem:db-" + randomSimpleId() + ";DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=" + logMode;
    JdbcDataSource ds = new JdbcDataSource();
    ds.setUrl(url);
    ds.setUser("sa");
    ds.setPassword("sa");
    this.ds = ds;
    //create db
    try (Connection conn = ds.getConnection()) {
        Statement st = conn.createStatement();
        st.execute("CREATE TABLE user (id INT, name VARCHAR(50)); " + " CREATE SEQUENCE user_seq START WITH 1 INCREMENT BY 1;");
        st.close();
    }
    async = ExecutorsUtil.newSingleThreadExecutor("async");
}
Example 60
Project: logging-log4j2-master  File: LoggerPrintWriterJdbcH2Test.java View source code
@Test
@Ignore("DataSource#setLogWriter() has no effect in H2, it uses its own internal logging and an SLF4J bridge.")
public void testDataSource_setLogWriter() throws SQLException {
    final JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setUrl(H2_URL);
    dataSource.setUser(USER_ID);
    dataSource.setPassword(PASSWORD);
    dataSource.setLogWriter(createLoggerPrintWriter());
    // dataSource.setLogWriter(new PrintWriter(new OutputStreamWriter(System.out)));
    try (final Connection conn = dataSource.getConnection()) {
        conn.prepareCall("select 1");
    }
    Assert.assertTrue(this.getListAppender().getMessages().size() > 0);
}
Example 61
Project: manifold-master  File: BaseITHSQLDB.java View source code
// Setup/teardown
@Before
public void setUpAlfresco() throws Exception {
    alfrescoServer = new Server(9090);
    alfrescoServer.setStopAtShutdown(true);
    String alfrescoServerWarPath = "../../connectors/alfresco/alfresco-war/alfresco.war";
    if (System.getProperty("alfrescoServerWarPath") != null)
        alfrescoServerWarPath = System.getProperty("alfrescoServerWarPath");
    //Initialize Alfresco Server bindings
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    alfrescoServer.setHandler(contexts);
    WebAppContext alfrescoServerApi = new WebAppContext(alfrescoServerWarPath, "/alfresco");
    alfrescoServerApi.setParentLoaderPriority(false);
    HashLoginService dummyLoginService = new HashLoginService("TEST-SECURITY-REALM");
    alfrescoServerApi.getSecurityHandler().setLoginService(dummyLoginService);
    contexts.addHandler(alfrescoServerApi);
    Class h2DataSource = Thread.currentThread().getContextClassLoader().loadClass("org.h2.jdbcx.JdbcDataSource");
    Object o = h2DataSource.newInstance();
    String jdbcUrl = "jdbc:h2:.alf_data_jetty/h2_data/alf_jetty";
    String jdbcUsername = "alfresco";
    String jdbcPassword = "alfresco";
    String jdbcJndiName = "jdbc/dataSource";
    h2DataSource.getMethod("setURL", new Class[] { String.class }).invoke(o, new Object[] { jdbcUrl });
    h2DataSource.getMethod("setUser", new Class[] { String.class }).invoke(o, new Object[] { jdbcUsername });
    h2DataSource.getMethod("setPassword", new Class[] { String.class }).invoke(o, new Object[] { jdbcPassword });
    Resource jdbcResource = new Resource(jdbcJndiName, o);
    alfrescoServer.start();
    boolean entered = false;
    while (alfrescoServer.isStarted() && alfrescoServerApi.isStarted() && !entered) {
        entered = true;
        Thread.sleep(5000);
    }
}
Example 62
Project: moonshine-master  File: H2.java View source code
@Override
public DataSource get() {
    final JdbcDataSource xaDataSource = new JdbcDataSource();
    xaDataSource.setURL(url + ";DB_CLOSE_ON_EXIT=FALSE");
    xaDataSource.setUser(username);
    xaDataSource.setPassword(password);
    String name = Thread.currentThread().getName();
    if (getId() == null) {
        name += "-defaultDataSource";
    } else {
        name = getId();
    }
    xaDataSource.setDescription(name);
    dataSource = wrapper.wrap(name, xaDataSource, pool, testQuery);
    executeMigrations(dataSource);
    return dataSource;
}
Example 63
Project: nuxeo-core-master  File: DatabaseH2.java View source code
@Override
public RepositoryDescriptor getRepositoryDescriptor() {
    RepositoryDescriptor descriptor = new RepositoryDescriptor();
    descriptor.xaDataSourceName = "org.h2.jdbcx.JdbcDataSource";
    Map<String, String> properties = new HashMap<String, String>();
    properties.put("URL", url);
    properties.put("User", Framework.getProperty(USER_PROPERTY));
    properties.put("Password", Framework.getProperty(PASSWORD_PROPERTY));
    descriptor.properties = properties;
    return descriptor;
}
Example 64
Project: org.eclipse.ecr-master  File: DatabaseH2.java View source code
@Override
public RepositoryDescriptor getRepositoryDescriptor() {
    RepositoryDescriptor descriptor = new RepositoryDescriptor();
    descriptor.xaDataSourceName = "org.h2.jdbcx.JdbcDataSource";
    Map<String, String> properties = new HashMap<String, String>();
    properties.put("URL", url);
    properties.put("User", System.getProperty(USER_PROPERTY));
    properties.put("Password", System.getProperty(PASSWORD_PROPERTY));
    descriptor.properties = properties;
    return descriptor;
}
Example 65
Project: riftsaw-ode-master  File: H2Database.java View source code
public void init(File workRoot, OdeConfigProperties props, TransactionManager txm) {
    String db = props.getDbEmbeddedName();
    String rollbackedDS = props.getProperties().getProperty("needed.Rollback");
    if ("true".equals(rollbackedDS) || workRoot != null) {
        db = db + new GUID().toString();
    }
    if (workRoot == null) {
        _dbUrl = "jdbc:h2:mem:" + db + ";DB_CLOSE_DELAY=-1";
    } else {
        _dbUrl = "jdbc:h2:" + workRoot + File.separator + db;
        if (!props.isDbEmbeddedCreate()) {
            _dbUrl += ";IFEXISTS=TRUE";
        }
    }
    __log.info("The db url is: " + _dbUrl);
    __log.info("The rollbackedDS: " + rollbackedDS + ":workRoot ->" + workRoot);
    if (workRoot != null || "true".equals(rollbackedDS)) {
        String clazz = org.h2.Driver.class.getName();
        _connectionManager = new DatabaseConnectionManager(txm, props);
        try {
            _connectionManager.init(_dbUrl, clazz, "sa", null);
        } catch (DatabaseConfigException ex) {
            __log.error("Unable to initialize connection pool", ex);
        }
        _dataSource = _connectionManager.getDataSource();
    } else {
        JdbcDataSource hds = new JdbcDataSource();
        hds.setURL(_dbUrl);
        hds.setUser("sa");
        _dataSource = hds;
    }
    __log.info("Using Embedded Database: " + _dbUrl);
}
Example 66
Project: tomee-master  File: DataSourceDefinitionTest.java View source code
@Test
public void checkDs() throws SQLException {
    final DataSource ds = persister.getDs();
    assertNotNull(ds);
    assertThat(ds, instanceOf(DbcpManagedDataSource.class));
    final DbcpManagedDataSource castedDs = (DbcpManagedDataSource) ds;
    final String driver = castedDs.getDriverClassName();
    assertEquals("org.h2.jdbcx.JdbcDataSource", driver);
    final String user = castedDs.getUserName();
    assertEquals("sa", user);
    final String url = castedDs.getUrl();
    assertEquals("jdbc:h2:mem:persister", url);
    final int initPoolSize = castedDs.getInitialSize();
    assertEquals(1, initPoolSize);
    final int maxIdle = castedDs.getMaxIdle();
    assertEquals(3, maxIdle);
    final Connection connection = ds.getConnection();
    assertNotNull(connection);
    execute(connection, "CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
    execute(connection, "INSERT INTO TEST(ID, NAME) VALUES(1, 'foo')");
    connection.commit();
    final PreparedStatement statement = ds.getConnection().prepareStatement("SELECT NAME FROM TEST");
    statement.execute();
    final ResultSet set = statement.getResultSet();
    assertTrue(set.next());
    assertEquals("foo", set.getString("NAME"));
}
Example 67
Project: be-worktajm-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource, DataSourceProperties dataSourceProperties, LiquibaseProperties liquibaseProperties) {
    // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
    SpringLiquibase liquibase = new AsyncSpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts(liquibaseProperties.getContexts());
    liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
    liquibase.setDropFirst(liquibaseProperties.isDropFirst());
    liquibase.setShouldRun(liquibaseProperties.isEnabled());
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourceProperties.getDriverClassName())) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 68
Project: emergency-service-drools-app-master  File: HumanTaskServerService.java View source code
public void initTaskServer() {
    System.out.println(">>> Starting Human Task Server ...");
    ds1 = new PoolingDataSource();
    ds1.setUniqueName("jdbc/testDS1");
    //ds1.setClassName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
    ds1.setClassName("org.h2.jdbcx.JdbcDataSource");
    ds1.setMaxPoolSize(5);
    ds1.setAllowLocalTransactions(true);
    ds1.getDriverProperties().put("user", "root");
    ds1.getDriverProperties().put("password", "atcroot");
    //ds1.getDriverProperties().put("databaseName", "droolsflow");
    //ds1.getDriverProperties().put("serverName", "localhost");
    ds1.init();
    // Use persistence.xml configuration
    emf = Persistence.createEntityManagerFactory("org.jbpm.task");
    taskService = new TaskService(emf, SystemEventListenerFactory.getSystemEventListener());
    taskSession = taskService.createSession();
    User operator = new User("operator");
    User driver = new User("control");
    User hospital = new User("hospital");
    User doctor = new User("doctor");
    User firefighter = new User("firefighter");
    User garageEmergencyService = new User("garage_emergency_service");
    User Administrator = new User("Administrator");
    taskSession.addUser(Administrator);
    taskSession.addUser(operator);
    taskSession.addUser(driver);
    taskSession.addUser(hospital);
    taskSession.addUser(doctor);
    taskSession.addUser(firefighter);
    taskSession.addUser(garageEmergencyService);
    if (server != null && server.isRunning()) {
        System.out.println(">>> Server Already Started");
        return;
    }
    //server = new MinaTaskServer(taskService);
    server = new HornetQTaskServer(taskService, 5446);
    try {
        Thread thread = new Thread(server);
        thread.start();
        while (!server.isRunning()) {
            System.out.print(".");
            Thread.sleep(50);
        }
    } catch (Exception ex) {
        Logger.getLogger(HumanTaskServerService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(" >>> ERROR: Server Not Started:  " + ex.getMessage());
    }
    if (server.isRunning()) {
        System.out.println(">>> Human Task Server Started!");
    }
}
Example 69
Project: ha-jdbc-master  File: SmokeTest.java View source code
private static void test(StateManagerFactory factory) throws Exception {
    JdbcDataSource ds1 = new JdbcDataSource();
    ds1.setUrl("jdbc:h2:mem:db1");
    ds1.setUser("sa");
    ds1.setPassword("");
    JdbcDataSource ds2 = new JdbcDataSource();
    ds2.setUrl("jdbc:h2:mem:db2");
    ds2.setUser("sa");
    ds2.setPassword("");
    try (DataSource ds = new DataSource()) {
        ds.setCluster("cluster");
        DataSourceDatabaseClusterConfigurationBuilder builder = ds.getConfigurationBuilder();
        builder.addDatabase("db1").dataSource(ds1).credentials("sa", "");
        builder.addDatabase("db2").dataSource(ds2).credentials("sa", "");
        builder.addSynchronizationStrategy("passive");
        builder.defaultSynchronizationStrategy("passive");
        builder.dialect("hsqldb");
        builder.metaDataCache("none");
        builder.state(factory);
        builder.durability("fine");
        try (Connection c1 = ds1.getConnection()) {
            createTable(c1);
            try (Connection c2 = ds2.getConnection()) {
                createTable(c2);
                try (Connection c = ds.getConnection()) {
                    c.setAutoCommit(false);
                    try (PreparedStatement ps = c.prepareStatement("INSERT INTO test (id, name) VALUES (?, ?)")) {
                        ps.setInt(1, 1);
                        ps.setString(2, "1");
                        ps.addBatch();
                        ps.setInt(1, 2);
                        ps.setString(2, "2");
                        ps.addBatch();
                        ps.executeBatch();
                    }
                    c.commit();
                    validate(c1);
                    validate(c2);
                } finally {
                    dropTable(c2);
                }
            } finally {
                dropTable(c1);
            }
        }
    }
}
Example 70
Project: hibernate-search-master  File: JBossTSIT.java View source code
@BeforeClass
public static void setUp() throws Exception {
    //DataSource configuration
    final String url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1";
    final String user = "sa";
    final String password = "";
    //H2 DataSource creation
    final JdbcDataSource underlyingDataSource = new JdbcDataSource();
    underlyingDataSource.setURL(url);
    underlyingDataSource.setUser(user);
    underlyingDataSource.setPassword(password);
    //build JBoss-bound DataSource
    DataSource ds = new JBossTADataSourceBuilder().setXADataSource(underlyingDataSource).setUser(user).setPassword(password).setTimeout(//infinite transaction
    0).createDataSource();
    PersistenceUnitInfoBuilder pub = new PersistenceUnitInfoBuilder();
    final PersistenceUnitInfo unitInfo = pub.setExcludeUnlistedClasses(true).setJtaDataSource(ds).setPersistenceProviderClassName(HibernatePersistenceProvider.class.getName()).setPersistenceUnitName("jbossjta").setPersistenceXMLSchemaVersion("2.0").setSharedCacheMode(SharedCacheMode.NONE).setValidationMode(ValidationMode.NONE).setTransactionType(PersistenceUnitTransactionType.JTA).addManagedClassNames(Tweet.class.getName()).addProperty("hibernate.dialect", H2Dialect.class.getName()).addProperty(Environment.HBM2DDL_AUTO, "create-drop").addProperty(Environment.SHOW_SQL, "true").addProperty(Environment.JTA_PLATFORM, JBossStandAloneJtaPlatform.class.getName()).addProperty(//I don't pool connections by JTA transaction. Leave the work to Hibernate Core
    Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_TRANSACTION.toString()).addProperty("hibernate.search.default.directory_provider", "ram").create();
    final HibernatePersistenceProvider hp = new HibernatePersistenceProvider();
    factory = hp.createContainerEntityManagerFactory(unitInfo, new HashMap());
}
Example 71
Project: ignite-master  File: CacheJdbcPojoStoreFactorySelfTest.java View source code
/**
     * @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 72
Project: inmemdb-maven-plugin-master  File: H2Database.java View source code
/**
     * Get the data source that describes the connection to the in-memory H2
     * database.
     *
     * @return Returns {@code dataSource} which was initialised by the
     *         constructor.
     */
@Override
public DataSource getDataSource() {
    final Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("DB_CLOSE_DELAY", "-1");
    final JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL(getUrl(attributes));
    dataSource.setUser(getUsername());
    dataSource.setPassword(getPassword());
    return dataSource;
}
Example 73
Project: iris-master  File: TestJdbcProducer.java View source code
/**
     * Check that Jndi itself is working
     */
@Test
public void testJndiWorking() {
    // Start up Jndi
    jndiSetUp();
    // Write reference to the data source into Jndi
    boolean threw = false;
    try {
        // Remove any existing objects with same name
        jndiTemplate.unbind(DATA_SOURCE_JNDI_NAME);
        jndiTemplate.bind(DATA_SOURCE_JNDI_NAME, dataSource);
    } catch (Exception e) {
        threw = true;
    }
    assertFalse("Could not bind object to JndiTemplate", threw);
    // Test Jndi by reading the object.
    threw = false;
    JdbcDataSource actualSource = null;
    try {
        actualSource = (JdbcDataSource) jndiTemplate.lookup(DATA_SOURCE_JNDI_NAME);
    } catch (Exception e) {
        threw = true;
    }
    assertFalse("Could not read object from JndiTemplate", threw);
    // Check returned data.
    assertEquals(dataSource.getUrl(), actualSource.getUrl());
    assertEquals(dataSource.getUser(), actualSource.getUser());
    assertEquals(dataSource.getPassword(), actualSource.getPassword());
    // Tidy
    jndiShutDown();
}
Example 74
Project: jhipster-sample-app-java7-master  File: DatabaseConfiguration.java View source code
@Bean
public SpringLiquibase liquibase(DataSource dataSource, DataSourceProperties dataSourceProperties, LiquibaseProperties liquibaseProperties) {
    // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
    SpringLiquibase liquibase = new AsyncSpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog("classpath:config/liquibase/master.xml");
    liquibase.setContexts(liquibaseProperties.getContexts());
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
        if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourceProperties.getDriverClassName())) {
            liquibase.setShouldRun(true);
            log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST);
        } else {
            liquibase.setShouldRun(false);
        }
    } else {
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
Example 75
Project: kazuki-master  File: DataSourceModuleH2Impl.java View source code
private JdbcConnectionPool createDataSource() {
    ResourceHelper.forName(config.getJdbcDriver(), getClass());
    JdbcDataSource datasource = new JdbcDataSource();
    datasource.setURL(config.getJdbcUrl());
    datasource.setUser(config.getJdbcUser());
    datasource.setPassword(config.getJdbcPassword());
    JdbcConnectionPool pooledDatasource = JdbcConnectionPool.create(datasource);
    pooledDatasource.setMaxConnections(config.getPoolMaxConnections());
    return pooledDatasource;
}
Example 76
Project: mylyn.docs.intent.main-master  File: IntentCDORepository.java View source code
/**
	 * Starts the Intent test Server (if not already launched).
	 * 
	 * @param cleanStore
	 *            true if the store must be clean (i.e. database should be dropped)
	 * @param repositoryName
	 *            the name of the repository to launch
	 */
public static void start(boolean cleanStore, String repositoryName) {
    if (acceptor == null) {
        // Step 1 : setting up the db
        // Step 1.1 : defining the datasource
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:_database/" + repositoryName);
        // Step 1.2 : defining the mapping strategy
        IMappingStrategy mappingStrategy = CDODBUtil.createHorizontalMappingStrategy(true);
        Map<String, String> mappingProperties = new LinkedHashMap<String, String>();
        mappingProperties.put(AbstractHorizontalMappingStrategy.PROP_OBJECT_TYPE_CACHE_SIZE, "1000");
        mappingProperties.put(AbstractHorizontalMappingStrategy.PROP_QUALIFIED_NAMES, Boolean.TRUE.toString());
        mappingStrategy.setProperties(mappingProperties);
        // Step 1.3 : use a H2 database
        IDBAdapter dbAdapter = new H2Adapter();
        IDBConnectionProvider dbConnectionProvider = DBUtil.createConnectionProvider(dataSource);
        // Clean the store if needed
        if (cleanStore) {
            DBUtil.dropAllTables(dbConnectionProvider.getConnection(), repositoryName);
        }
        // Step 1.4 : creating the IStore from the specified DB
        IStore store = CDODBUtil.createStore(mappingStrategy, dbAdapter, dbConnectionProvider);
        // Step 2 : creating the repository
        Map<String, String> props = new HashMap<String, String>();
        props.put(IRepository.Props.OVERRIDE_UUID, repositoryName);
        props.put(IRepository.Props.SUPPORTING_AUDITS, "false");
        props.put(IRepository.Props.SUPPORTING_BRANCHES, "false");
        props.put(IRepository.Props.SUPPORTING_ECORE, "true");
        repository = CDOServerUtil.createRepository(repositoryName, store, props);
        CDOServerUtil.addRepository(IPluginContainer.INSTANCE, repository);
        CDONet4jServerUtil.prepareContainer(IPluginContainer.INSTANCE);
        // Step 3 : creating an acceptor on the server side
        acceptor = (IAcceptor) IPluginContainer.INSTANCE.getElement("org.eclipse.net4j.acceptors", "tcp", SERVER_LOCATION + ":" + SERVER_PORT_NUMBER);
    }
}
Example 77
Project: p6spy-master  File: XADataSourceTest.java View source code
@Before
public void setUpXADataSourceTest() throws NamingException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
    final P6TestLoadableOptions testOptions = P6TestOptions.getActiveInstance();
    jndiResources = new ArrayList<Resource>();
    poolingDSs = new ArrayList<PoolingDataSource>();
    tm = TransactionManagerServices.getTransactionManager();
    // in test DS setup
    {
        final XADataSource realInTestDs = (XADataSource) P6Util.forName(testOptions.getXaDataSource().getClass().getName()).newInstance();
        setXADSProperties(realInTestDs, testOptions.getUrl().replace(":p6spy", ""), testOptions.getUser(), testOptions.getPassword());
        jndiResources.add(new Resource("jdbc/realInTestDs", realInTestDs));
        final PoolingDataSource inTestDs = new PoolingDataSource();
        inTestDs.setClassName(P6DataSource.class.getName());
        inTestDs.setUniqueName("jdbc/inTestDs");
        inTestDs.setMaxPoolSize(10);
        inTestDs.getDriverProperties().setProperty("realDataSource", "jdbc/realInTestDs");
        inTestDs.setAllowLocalTransactions(true);
        inTestDs.init();
        jndiResources.add(new Resource("jdbc/inTestDs", inTestDs));
        poolingDSs.add(inTestDs);
    }
    // fixed DS setup
    {
        final XADataSource realFixedDs = (XADataSource) P6Util.forName("org.h2.jdbcx.JdbcDataSource").newInstance();
        setXADSProperties(realFixedDs, "jdbc:h2:mem:p6spy_realFixedDs", "sa", "sa");
        jndiResources.add(new Resource("jdbc/realFixedDs", realFixedDs));
        final PoolingDataSource fixedDs = new PoolingDataSource();
        fixedDs.setClassName(P6DataSource.class.getName());
        fixedDs.setUniqueName("jdbc/fixedDs");
        fixedDs.setMaxPoolSize(10);
        fixedDs.getDriverProperties().setProperty("realDataSource", "jdbc/realFixedDs");
        fixedDs.setAllowLocalTransactions(true);
        fixedDs.init();
        jndiResources.add(new Resource("jdbc/fixedDs", fixedDs));
        poolingDSs.add(fixedDs);
    }
    // liquibase opens it's own transaction => keep it out of ours
    try {
        P6TestUtil.setupTestData(new JndiDataSourceLookup().getDataSource("jdbc/inTestDs"));
        P6TestUtil.setupTestData(new JndiDataSourceLookup().getDataSource("jdbc/fixedDs"));
    } catch (LiquibaseException e) {
        e.printStackTrace();
    }
    try {
        tm.begin();
        // TODO move to liquibase?
        cleanData(new JndiDataSourceLookup().getDataSource("jdbc/inTestDs"));
        cleanData(new JndiDataSourceLookup().getDataSource("jdbc/fixedDs"));
        tm.commit();
    } catch (NotSupportedException e) {
        e.printStackTrace();
    } catch (SystemException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        e.printStackTrace();
    } catch (RollbackException e) {
        e.printStackTrace();
    }
}
Example 78
Project: picketlink-master  File: JDBCStoreConfigurationTester.java View source code
private void setupDB(JdbcDataSource ds) throws Exception {
    Connection connection = ds.getConnection();
    //User
    connection.createStatement().executeUpdate("drop table if exists User");
    connection.createStatement().executeUpdate("create table User(id varchar,firstName varchar,lastName varchar," + "email varchar,loginName varchar,enabled varchar,createdDate timestamp,expirationDate timestamp,partitionID varchar)");
    //Role
    connection.createStatement().executeUpdate("drop table if exists Role");
    connection.createStatement().executeUpdate("create table Role(id varchar,name varchar," + "enabled varchar,createdDate timestamp,expirationDate timestamp,partitionID varchar)");
    //Group
    connection.createStatement().executeUpdate("drop table if exists Groups");
    connection.createStatement().executeUpdate("create table Groups(id varchar,name varchar," + "enabled varchar,createdDate timestamp,expirationDate timestamp,parentGroup varchar," + "path varchar,partitionID varchar)");
    //Partition
    connection.createStatement().executeUpdate("drop table if exists Partition");
    connection.createStatement().executeUpdate("create table Partition(id varchar,name varchar," + "typeName varchar,configurationName varchar)");
    //Attribute
    connection.createStatement().executeUpdate("drop table if exists Attributes");
    connection.createStatement().executeUpdate("create table Attributes(owner varchar,name varchar," + "value varchar,attributeType varchar)");
    //Relationship
    connection.createStatement().executeUpdate("drop table if exists Relationship");
    connection.createStatement().executeUpdate("create table Relationship(id varchar,relBegin varchar," + "relEnd varchar,type varchar,enabled varchar)");
}
Example 79
Project: ratpack-master  File: Example.java View source code
public static void main(String[] args) throws Exception {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:transactionExamples;DB_CLOSE_DELAY=-1");
    txDs = Transaction.dataSource(ds);
    tx = Transaction.create(ds::getConnection);
    try (Connection connection = txDs.getConnection()) {
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate("CREATE TABLE tbl (value VARCHAR(50)) ");
        }
    }
    List<Block> examples = Arrays.asList(Example::singleTransactionExample, Example::singleTransactionRollbackExample, Example::nestedTransactionExample, Example::nestedTransactionRollbackExample, () -> manualTransactionExample(true), () -> manualTransactionExample(false));
    try (ExecHarness harness = ExecHarness.harness()) {
        for (Block example : examples) {
            harness.execute(Operation.of(example));
            reset();
        }
    }
}
Example 80
Project: craftconomy3-master  File: H2ToMySQLConverter.java View source code
public void run() {
    Common.getInstance().sendConsoleMessage(Level.INFO, Common.getInstance().getLanguageManager().getString("starting_database_convert"));
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setMaximumPoolSize(Common.getInstance().getMainConfig().getInt("System.Database.Poolsize"));
    hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
    hikariConfig.addDataSourceProperty("user", "sa");
    hikariConfig.addDataSourceProperty("url", "jdbc:h2:file:" + new File(Common.getInstance().getServerCaller().getDataFolder().getPath(), "database").getAbsolutePath() + ";MV_STORE=FALSE");
    hikariConfig.setConnectionTimeout(5000);
    db = new HikariDataSource(hikariConfig);
    prefix = Common.getInstance().getMainConfig().getString("System.Database.Prefix");
    try {
        Connection connection = db.getConnection();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting accounts information");
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + prefix + AccountTable.TABLE_NAME);
        ResultSet set = statement.executeQuery();
        while (set.next()) {
            Account account = new Account();
            account.id = set.getInt("id");
            account.name = set.getString("name");
            account.ignoreACL = set.getBoolean("ignoreACL");
            if (set.getString("uuid") != null) {
                account.uuid = UUID.fromString(set.getString("uuid"));
            } else if (!set.getBoolean("bank")) {
                account.uuid = Common.getInstance().getServerCaller().getPlayerCaller().getUUID(account.name);
            }
            account.infiniteMoney = set.getBoolean("infiniteMoney");
            account.bank = set.getBoolean("bank");
            accountList.put(account.id, account);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting currency table information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + CurrencyTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            Currency currency = new Currency(set.getString("name"), set.getString("plural"), set.getString("minor"), set.getString("minorPlural"), set.getString("sign"), set.getBoolean("status"));
            currencyList.put(currency.getName(), currency);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting Balance table information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + BalanceTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            Balance balance = new Balance();
            balance.balance = set.getDouble("balance");
            balance.worldName = set.getString("worldName");
            balance.currency_id = set.getString("currency_id");
            accountList.get(set.getInt("username_id")).balanceList.add(balance);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting access table information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + AccessTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            Access access = new Access();
            access.acl = set.getBoolean("acl");
            access.balance = set.getBoolean("balance");
            access.deposit = set.getBoolean("deposit");
            access.owner = set.getBoolean("owner");
            access.withdraw = set.getBoolean("withdraw");
            access.playerName = set.getString("playerName");
            accountList.get(set.getInt("account_id")).accessList.add(access);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting config table information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + ConfigTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            Config config = new Config();
            config.name = set.getString("name");
            config.value = set.getString("value");
            configList.add(config);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting Exchange table information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + ExchangeTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            Exchange exchange = new Exchange();
            exchange.currency_id_from = set.getString("from_currency");
            exchange.currency_id_to = set.getString("to_currency");
            exchange.amount = set.getInt("amount");
            exchangeList.add(exchange);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting log table information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + LogTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            Log log = new Log();
            log.amount = set.getDouble("amount");
            log.cause = set.getString("cause");
            log.causeReason = set.getString("causeReason");
            log.currency_id = set.getString("currency_id");
            log.timestamp = set.getTimestamp("timestamp");
            log.type = set.getString("type");
            log.worldName = set.getString("worldName");
            accountList.get(set.getInt("username_id")).logList.add(log);
        }
        set.close();
        statement.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Getting world group information");
        statement = connection.prepareStatement("SELECT * FROM " + prefix + WorldGroupTable.TABLE_NAME);
        set = statement.executeQuery();
        while (set.next()) {
            WorldGroup worldGroup = new WorldGroup();
            worldGroup.groupName = set.getString("groupName");
            worldGroup.worldList = set.getString("worldList");
            worldGroupList.add(worldGroup);
        }
        set.close();
        statement.close();
        Common.getInstance().getStorageHandler().getStorageEngine().disableAutoCommit();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Inserting currency information");
        for (Map.Entry<String, Currency> currency : currencyList.entrySet()) {
            Common.getInstance().getStorageHandler().getStorageEngine().saveCurrency(currency.getValue().getName(), currency.getValue());
        }
        Common.getInstance().sendConsoleMessage(Level.INFO, "Inserting config information");
        for (Config config : configList) {
            Common.getInstance().getStorageHandler().getStorageEngine().setConfigEntry(config.name, config.value);
        }
        Common.getInstance().sendConsoleMessage(Level.INFO, "Inserting Exchange information");
        for (Exchange exchange : exchangeList) {
            Common.getInstance().getStorageHandler().getStorageEngine().setExchangeRate(currencyList.get(exchange.currency_id_from), currencyList.get(exchange.currency_id_to), exchange.amount);
        }
        Common.getInstance().sendConsoleMessage(Level.INFO, "Inserting World Group information");
        for (WorldGroup worldGroup : worldGroupList) {
            Common.getInstance().getStorageHandler().getStorageEngine().saveWorldGroup(worldGroup.groupName, worldGroup.worldList);
        }
        Common.getInstance().sendConsoleMessage(Level.INFO, "Inserting account/balance/log/access information");
        for (Map.Entry<Integer, Account> accountEntry : accountList.entrySet()) {
            com.greatmancode.craftconomy3.account.Account account = Common.getInstance().getStorageHandler().getStorageEngine().getAccount(accountEntry.getValue().name, accountEntry.getValue().bank, false);
            Common.getInstance().getStorageHandler().getStorageEngine().updateUUID(accountEntry.getValue().name, accountEntry.getValue().uuid);
            Common.getInstance().getStorageHandler().getStorageEngine().setInfiniteMoney(account, accountEntry.getValue().infiniteMoney);
            Common.getInstance().getStorageHandler().getStorageEngine().setIgnoreACL(account, accountEntry.getValue().ignoreACL);
            for (Balance balance : accountEntry.getValue().balanceList) {
                Common.getInstance().getStorageHandler().getStorageEngine().setBalance(account, balance.balance, currencyList.get(balance.currency_id), balance.worldName);
            }
            for (Access access : accountEntry.getValue().accessList) {
                Common.getInstance().getStorageHandler().getStorageEngine().saveACL(account, access.playerName, access.deposit, access.withdraw, access.acl, access.balance, access.owner);
            }
            for (Log log : accountEntry.getValue().logList) {
                Common.getInstance().getStorageHandler().getStorageEngine().saveLog(LogInfo.valueOf(log.type.toUpperCase()), Cause.valueOf(log.cause.toUpperCase()), log.causeReason, account, log.amount, currencyList.get(log.currency_id), log.worldName, log.timestamp);
            }
        }
        Common.getInstance().getStorageHandler().getStorageEngine().commit();
        Common.getInstance().getStorageHandler().getStorageEngine().enableAutoCommit();
        connection.close();
        db.close();
        Common.getInstance().sendConsoleMessage(Level.INFO, "Convertion complete!");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Example 81
Project: geotools-2.7.x-master  File: ThreadedH2EpsgFactory.java View source code
/**
     * Extract the directory from the specified data source, or {@code null} if this
     * information is not available.
     */
private static File getDirectory(final DataSource source) {
    if (source instanceof JdbcDataSource) {
        String path = ((JdbcDataSource) source).getURL();
        if (path != null && PREFIX.regionMatches(true, 0, path, 0, PREFIX.length())) {
            path = path.substring(PREFIX.length());
            if (path.indexOf(';') != -1) {
                path = path.substring(0, path.indexOf(';'));
            }
            return new File(path).getParentFile();
        }
    }
    return null;
}
Example 82
Project: geotools-old-master  File: ThreadedH2EpsgFactory.java View source code
/**
     * Extract the directory from the specified data source, or {@code null} if this
     * information is not available.
     */
private static File getDirectory(final DataSource source) {
    if (source instanceof JdbcDataSource) {
        String path = ((JdbcDataSource) source).getURL();
        if (path != null && PREFIX.regionMatches(true, 0, path, 0, PREFIX.length())) {
            path = path.substring(PREFIX.length());
            if (path.indexOf(';') != -1) {
                path = path.substring(0, path.indexOf(';'));
            }
            return new File(path).getParentFile();
        }
    }
    return null;
}
Example 83
Project: geotools-tike-master  File: ThreadedH2EpsgFactory.java View source code
/**
     * Extract the directory from the specified data source, or {@code null} if this
     * information is not available.
     */
private static File getDirectory(final DataSource source) {
    if (source instanceof JdbcDataSource) {
        String path = ((JdbcDataSource) source).getURL();
        if (path != null && PREFIX.regionMatches(true, 0, path, 0, PREFIX.length())) {
            path = path.substring(PREFIX.length());
            if (path.indexOf(';') != -1) {
                path = path.substring(0, path.indexOf(';'));
            }
            return new File(path).getParentFile();
        }
    }
    return null;
}
Example 84
Project: geotools_trunk-master  File: ThreadedH2EpsgFactory.java View source code
/**
     * Extract the directory from the specified data source, or {@code null} if this
     * information is not available.
     */
private static File getDirectory(final DataSource source) {
    if (source instanceof JdbcDataSource) {
        String path = ((JdbcDataSource) source).getURL();
        if (path != null && PREFIX.regionMatches(true, 0, path, 0, PREFIX.length())) {
            path = path.substring(PREFIX.length());
            if (path.indexOf(';') != -1) {
                path = path.substring(0, path.indexOf(';'));
            }
            return new File(path).getParentFile();
        }
    }
    return null;
}
Example 85
Project: killbill-commons-master  File: DataSourceProvider.java View source code
private void parseJDBCUrl() {
    final URI uri = URI.create(config.getJdbcUrl().substring(5));
    final String schemeLocation;
    if (uri.getPath() != null) {
        schemeLocation = null;
    } else if (uri.getSchemeSpecificPart() != null) {
        final String[] schemeParts = uri.getSchemeSpecificPart().split(":");
        schemeLocation = schemeParts[0];
    } else {
        schemeLocation = null;
    }
    dataSourceClassName = config.getDataSourceClassName();
    driverClassName = config.getDriverClassName();
    if ("mysql".equals(uri.getScheme())) {
        databaseType = DatabaseType.MYSQL;
        if (dataSourceClassName == null) {
            if (useMariaDB) {
                dataSourceClassName = "org.mariadb.jdbc.MySQLDataSource";
            } else {
                dataSourceClassName = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
            }
        }
        if (driverClassName == null) {
            if (useMariaDB) {
                driverClassName = "org.mariadb.jdbc.Driver";
            } else {
                driverClassName = "com.mysql.jdbc.Driver";
            }
        }
    } else if ("h2".equals(uri.getScheme()) && ("mem".equals(schemeLocation) || "file".equals(schemeLocation))) {
        databaseType = DatabaseType.H2;
        if (dataSourceClassName == null) {
            dataSourceClassName = "org.h2.jdbcx.JdbcDataSource";
        }
        if (driverClassName == null) {
            driverClassName = "org.h2.Driver";
        }
    } else if ("postgresql".equals(uri.getScheme())) {
        databaseType = DatabaseType.POSTGRESQL;
        if (dataSourceClassName == null) {
            dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource";
        }
        if (driverClassName == null) {
            driverClassName = "org.postgresql.Driver";
        }
    } else {
        databaseType = DatabaseType.GENERIC;
    }
}
Example 86
Project: orbisgis-master  File: EventListenerService.java View source code
@Reference
public void setDataManager(DataManager dataManager) {
    this.dataManager = dataManager;
    DataSource dataSource = dataManager.getDataSource();
    // Link
    try (Connection connection = dataSource.getConnection();
        Statement st = connection.createStatement()) {
        if (isLocalH2DataBase(connection.getMetaData())) {
            H2DatabaseEventListener.setDelegateDatabaseEventListener(this);
            // Change DATABASE_EVENT_LISTENER for this Database instance
            st.execute("SET DATABASE_EVENT_LISTENER '" + H2DatabaseEventListener.class.getName() + "'");
            // the JDBC url connection have to be changed
            try {
                if (dataSource instanceof JdbcDataSource || dataSource.isWrapperFor(JdbcDataSource.class)) {
                    JdbcDataSource jdbcDataSource;
                    if (dataSource instanceof JdbcDataSource) {
                        jdbcDataSource = (JdbcDataSource) dataSource;
                    } else {
                        jdbcDataSource = dataSource.unwrap(JdbcDataSource.class);
                    }
                    if (!jdbcDataSource.getURL().toUpperCase().contains("DATABASE_EVENT_LISTENER")) {
                        jdbcDataSource.setURL(jdbcDataSource.getURL() + ";DATABASE_EVENT_LISTENER='" + H2DatabaseEventListener.class.getName() + "'");
                    }
                }
            } catch (Exception ex) {
                logger.warn("Cannot change connection URL:\n" + ex.getLocalizedMessage(), ex);
            }
            H2Trigger.setTriggerFactory(this);
        }
    } catch (SQLException ex) {
        logger.error(ex.getLocalizedMessage(), ex);
    }
}
Example 87
Project: softwaremill-common-master  File: TransactionalDBTest.java View source code
protected void initTransactionManager(Ejb3Configuration cfg) throws Exception {
    String configurationFile = getConfigurationFile();
    if (configurationFile != null) {
        LOG.info("Using [{}] as a configuration file for Bitronix Transaction Manager!", configurationFile);
        TransactionManagerServices.getConfiguration().setResourceConfigurationFilename(configurationFile);
    } else {
        // create InMemory H2 database
        PoolingDataSource xa = new PoolingDataSource();
        xa.setUniqueName(cfg.getProperties().getProperty(BITRONIX_UNIQUE_NAME, "test-" + getClass().getSimpleName()));
        xa.setClassName(cfg.getProperties().getProperty(BITRONIX_DATASOURCE_CLASS, JdbcDataSource.class.getName()));
        xa.setAllowLocalTransactions(true);
        xa.setMaxPoolSize(3);
        xa.setMinPoolSize(1);
        Properties prop = new Properties();
        String url = cfg.getProperties().getProperty(BITRONIX_CONNECTION_URL, "jdbc:h2:mem:" + getClass().getSimpleName());
        if (compatibilityMode() != null) {
            url += ";MODE=" + compatibilityMode();
        }
        prop.setProperty("URL", url);
        prop.setProperty("user", cfg.getProperties().getProperty(BITRONIX_CONNECTION_USERNAME, "sa"));
        xa.setDriverProperties(prop);
        xa.init();
        TransactionManagerServices.getResourceLoader().getResources().put(xa.getUniqueName(), xa);
    }
    TransactionManagerServices.getResourceLoader().init();
}
Example 88
Project: spring-framework-issues-master  File: ReproTests.java View source code
@Bean(initMethod = "init", destroyMethod = "close")
DataSource dataSource() {
    AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean();
    dataSource.setXaDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
    dataSource.setUniqueResourceName("dataSourceResource");
    Properties props = new Properties();
    props.setProperty("user", "sa");
    props.setProperty("password", "");
    props.setProperty("url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    dataSource.setXaProperties(props);
    return dataSource;
}
Example 89
Project: OpenIDM-master  File: ActivitiServiceImpl.java View source code
@Activate
void activate(ComponentContext compContext) {
    logger.debug("Activating Service with configuration {}", compContext.getProperties());
    try {
        readConfiguration(compContext);
        if (enabled) {
            switch(location) {
                case //start our embedded ProcessEngine
                embedded:
                    // see if we have the DataSourceService bound
                    final DataSourceService dataSourceService = dataSourceServices.get(useDataSource);
                    //we need a TransactionManager to use this
                    JtaProcessEngineConfiguration configuration = new JtaProcessEngineConfiguration();
                    if (null == dataSourceService) {
                        //initialise the default h2 DataSource
                        //Implement it here. There are examples in the JDBCRepoService
                        JdbcDataSource jdbcDataSource = new org.h2.jdbcx.JdbcDataSource();
                        File root = IdentityServer.getFileForWorkingPath("db/activiti/database");
                        jdbcDataSource.setURL("jdbc:h2:file:" + URLDecoder.decode(root.getPath(), "UTF-8") + ";DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=1000");
                        jdbcDataSource.setUser("sa");
                        configuration.setDatabaseType("h2");
                        configuration.setDataSource(jdbcDataSource);
                    } else {
                        // use DataSourceService as source of DataSource
                        configuration.setDataSource(dataSourceService.getDataSource());
                    }
                    configuration.setIdentityService(identityService);
                    configuration.setTransactionManager(transactionManager);
                    configuration.setTransactionsExternallyManaged(true);
                    configuration.setDatabaseSchemaUpdate("true");
                    configuration.setDatabaseTablePrefix(tablePrefix);
                    configuration.setTablePrefixIsSchema(tablePrefixIsSchema);
                    List<SessionFactory> customSessionFactories = configuration.getCustomSessionFactories();
                    if (customSessionFactories == null) {
                        customSessionFactories = new ArrayList<SessionFactory>();
                    }
                    customSessionFactories.add(idmSessionFactory);
                    configuration.setCustomSessionFactories(customSessionFactories);
                    configuration.setExpressionManager(expressionManager);
                    configuration.setMailServerHost(mailhost);
                    configuration.setMailServerPort(mailport);
                    configuration.setMailServerUseTLS(starttls);
                    if (mailusername != null) {
                        configuration.setMailServerUsername(mailusername);
                    }
                    if (mailpassword != null) {
                        configuration.setMailServerPassword(mailpassword);
                    }
                    if (historyLevel != null) {
                        configuration.setHistory(historyLevel);
                    }
                    //needed for async workflows
                    configuration.setJobExecutorActivate(true);
                    processEngineFactory = new ProcessEngineFactory();
                    processEngineFactory.setProcessEngineConfiguration(configuration);
                    processEngineFactory.setBundle(compContext.getBundleContext().getBundle());
                    processEngineFactory.init();
                    //ScriptResolverFactory
                    List<ResolverFactory> resolverFactories = configuration.getResolverFactories();
                    resolverFactories.add(new OpenIDMResolverFactory());
                    configuration.setResolverFactories(resolverFactories);
                    configuration.getVariableTypes().addType(new JsonValueType());
                    configuration.setScriptingEngines(new OsgiScriptingEngines(new ScriptBindingsFactory(resolverFactories)));
                    //We are done!!
                    processEngine = processEngineFactory.getObject();
                    //We need to register the service because the Activiti-OSGi need this to deploy new BAR or BPMN
                    Hashtable<String, String> prop = new Hashtable<String, String>();
                    prop.put(Constants.SERVICE_PID, "org.forgerock.openidm.workflow.activiti.engine");
                    prop.put("openidm.activiti.engine", "true");
                    compContext.getBundleContext().registerService(ProcessEngine.class.getName(), processEngine, prop);
                    if (null != configurationAdmin) {
                        try {
                            barInstallerConfiguration = configurationAdmin.createFactoryConfiguration("org.apache.felix.fileinstall", null);
                            Dictionary<String, String> props = barInstallerConfiguration.getProperties();
                            if (props == null) {
                                props = new Hashtable<String, String>();
                            }
                            props.put("felix.fileinstall.poll", "2000");
                            props.put("felix.fileinstall.noInitialDelay", "true");
                            //TODO java.net.URLDecoder.decode(IdentityServer.getFileForPath("workflow").getAbsolutePath(),"UTF-8")
                            props.put("felix.fileinstall.dir", IdentityServer.getFileForInstallPath(workflowDir).getAbsolutePath());
                            props.put("felix.fileinstall.filter", ".*\\.bar|.*\\.xml");
                            props.put("felix.fileinstall.bundles.new.start", "true");
                            props.put("config.factory-pid", "activiti");
                            barInstallerConfiguration.update(props);
                        } catch (IOException ex) {
                            java.util.logging.Logger.getLogger(ActivitiServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    activitiResource = new ActivitiResource(processEngine);
                    logger.debug("Activiti ProcessEngine is enabled");
                    break;
                case //ProcessEngine is connected by @Reference
                local:
                    activitiResource = new ActivitiResource(processEngine);
                    break;
                //                        break;
                default:
                    throw new InvalidException(CONFIG_LOCATION + " invalid, can not start workflow service.");
            }
        }
    } catch (RuntimeException ex) {
        logger.warn("Configuration invalid, can not start Activiti ProcessEngine service.", ex);
        throw ex;
    } catch (Exception ex) {
        logger.warn("Configuration invalid, can not start  Activiti ProcessEngine service.", ex);
        throw new RuntimeException(ex);
    }
}
Example 90
Project: elibrarium-master  File: Librarian.java View source code
/**
	 * Start the h2 database server.
	 * 
	 * @throws Exception
	 * @see {@link #getStorageLocation()}
	 */
protected void doStart() throws Exception {
    LOG.info("Elibrarium server starting");
    JdbcDataSource dataSource = new JdbcDataSource();
    // XXX: This is a workaround for not handling inter-process transactions
    // through CDO. It also solves several other problems, such as what
    // happens when the database server dies.
    //
    // http://h2database.com/html/features.html#auto_mixed_mode
    // String url = "jdbc:h2:" + getStorageLocation() + File.separator +
    // "h2db;AUTO_SERVER=TRUE";
    String url = "jdbc:h2:" + getStorageLocation() + File.separator + "h2db;AUTO_SERVER=TRUE";
    LOG.info("- Hibernate database URL = " + url);
    dataSource.setURL(url);
    // Create one database table per concrete model class
    IMappingStrategy mappingStrategy = CDODBUtil.createHorizontalMappingStrategy(true);
    IDBAdapter dbAdapter = new H2Adapter();
    IDBConnectionProvider dbConnectionProvider = DBUtil.createConnectionProvider(dataSource);
    IStore store = CDODBUtil.createStore(mappingStrategy, dbAdapter, dbConnectionProvider);
    Map<String, String> props = new HashMap<String, String>();
    props.put(IRepository.Props.OVERRIDE_UUID, CDO_REPOSITORY_ID);
    props.put(IRepository.Props.SUPPORTING_AUDITS, "true");
    props.put(IRepository.Props.SUPPORTING_BRANCHES, "false");
    repository = CDOServerUtil.createRepository(CDO_REPOSITORY_ID, store, props);
    CDOServerUtil.addRepository(IPluginContainer.INSTANCE, repository);
    CDONet4jServerUtil.prepareContainer(IPluginContainer.INSTANCE);
    acceptor = (IAcceptor) IPluginContainer.INSTANCE.getElement("org.eclipse.net4j.acceptors", "tcp", getDbServerAddress());
    LOG.info("- CDO acceptor started at " + getDbServerAddress());
    startConsole();
    LOG.info("Elibrarium server started");
}
Example 91
Project: jabylon-master  File: Activator.java View source code
private IStore createStore() {
    final String DATABASE_NAME = ServerConstants.WORKING_DIR + "/cdo/embedded/h2;DB_CLOSE_ON_EXIT=FALSE";
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:" + DATABASE_NAME + ";DB_CLOSE_DELAY=-1");
    // myDataSource.setCreateDatabase("create");
    // myDataSource.setPort(3306);
    // myDataSource.setServerName("localhost");
    IMappingStrategy mappingStrategy = CDODBUtil.createHorizontalMappingStrategy(false);
    // IDBStore store = CDODBUtil.createStore(mappingStrategy,
    // DBUtil.getDBAdapter("derby-embedded"),
    // DBUtil.createConnectionProvider(myDataSource));
    H2Adapter adapter = new H2Adapter();
    new DBMigrator().migrate(dataSource);
    IDBStore store = CDODBUtil.createStore(mappingStrategy, adapter, DBUtil.createConnectionProvider(dataSource));
    mappingStrategy.setStore(store);
    return store;
}
Example 92
Project: ironjacamar-master  File: DataSources20TestCase.java View source code
/**
    * Checks the data source parsed
    * @param result of data source parsing
    */
private void checkDS(DataSources ds) {
    List<DataSource> listDs = ds.getDataSource();
    assertEquals(1, listDs.size());
    DataSource d = listDs.get(0);
    assertFalse(d.isJTA());
    assertTrue(d.isSpy());
    assertFalse(d.isEnabled());
    assertFalse(d.isUseCcm());
    assertTrue(d.isConnectable());
    assertFalse(d.isTracking());
    assertEquals("java:jboss/datasources/complexDs", d.getJndiName());
    assertEquals("complexDs_Pool", d.getId());
    assertEquals("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", d.getConnectionUrl());
    assertEquals("org.hsqldb.jdbcDriver", d.getDriverClass());
    assertEquals("org.pg.JdbcDataSource", d.getDataSourceClass());
    assertEquals("h2", d.getDriver());
    Map<String, String> properties = d.getConnectionProperties();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("select 1", d.getNewConnectionSql());
    assertEquals(":", d.getUrlDelimiter());
    assertEquals("someClass", d.getUrlSelectorStrategyClassName());
    assertEquals(TransactionIsolation.valueOf("2"), d.getTransactionIsolation());
    DsPool pool = d.getPool();
    assertNotNull(pool);
    assertEquals(1, (int) pool.getMinPoolSize());
    assertEquals(2, (int) pool.getInitialPoolSize());
    assertEquals(5, (int) pool.getMaxPoolSize());
    assertTrue(pool.isPrefill());
    assertEquals(FlushStrategy.ALL_CONNECTIONS, pool.getFlushStrategy());
    Capacity cp = pool.getCapacity();
    assertNotNull(cp);
    Extension e = cp.getIncrementer();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("ic", e.getClassName());
    e = cp.getDecrementer();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("dc", e.getClassName());
    DsSecurity s = d.getSecurity();
    assertNotNull(s);
    assertEquals("sa", s.getUserName());
    assertEquals("sa", s.getPassword());
    e = s.getReauthPlugin();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass1", e.getClassName());
    Validation v = d.getValidation();
    assertNotNull(v);
    assertEquals("select 1", v.getCheckValidConnectionSql());
    assertTrue(v.isBackgroundValidation());
    assertTrue(v.isValidateOnMatch());
    assertTrue(v.isUseFastFail());
    assertEquals(2000L, (long) v.getBackgroundValidationMillis());
    e = v.getValidConnectionChecker();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass2", e.getClassName());
    e = v.getStaleConnectionChecker();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass3", e.getClassName());
    e = v.getExceptionSorter();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass4", e.getClassName());
    Timeout t = d.getTimeout();
    assertNotNull(t);
    assertEquals(20000L, (long) t.getBlockingTimeoutMillis());
    assertEquals(4, (int) t.getIdleTimeoutMinutes());
    assertEquals(120L, (long) t.getQueryTimeout());
    assertEquals(100L, (long) t.getUseTryLock());
    assertEquals(2L, (long) t.getAllocationRetry());
    assertEquals(3000L, (long) t.getAllocationRetryWaitMillis());
    assertTrue(t.isSetTxQueryTimeout());
    Statement st = d.getStatement();
    assertNotNull(st);
    assertEquals(30L, (long) st.getPreparedStatementsCacheSize());
    assertTrue(st.isSharePreparedStatements());
    assertEquals(TrackStatementsEnum.NOWARN, st.getTrackStatements());
    List<XaDataSource> xds = ds.getXaDataSource();
    assertEquals(1, xds.size());
    XaDataSource xd = xds.get(0);
    assertFalse(xd.isSpy());
    assertTrue(xd.isEnabled());
    assertTrue(xd.isUseCcm());
    assertFalse(xd.isConnectable());
    assertTrue(xd.isTracking());
    assertEquals("java:jboss/xa-datasources/complexXaDs", xd.getJndiName());
    assertEquals("complexXaDs_Pool", xd.getId());
    assertEquals("org.pg.JdbcXADataSource", xd.getXaDataSourceClass());
    assertEquals("pg", xd.getDriver());
    properties = xd.getXaDataSourceProperty();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("select 1", xd.getNewConnectionSql());
    assertEquals(":", xd.getUrlDelimiter());
    assertEquals("someClass", xd.getUrlSelectorStrategyClassName());
    assertEquals(TransactionIsolation.TRANSACTION_READ_COMMITTED, xd.getTransactionIsolation());
    DsXaPool xpool = xd.getXaPool();
    assertNotNull(xpool);
    assertEquals(1, (int) xpool.getMinPoolSize());
    assertEquals(2, (int) xpool.getInitialPoolSize());
    assertEquals(5, (int) xpool.getMaxPoolSize());
    assertTrue(xpool.isPrefill());
    assertEquals(FlushStrategy.GRACEFULLY, xpool.getFlushStrategy());
    assertTrue(xpool.isIsSameRmOverride());
    assertTrue(xpool.isPadXid());
    assertFalse(xpool.isWrapXaResource());
    cp = xpool.getCapacity();
    assertNotNull(cp);
    e = cp.getIncrementer();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("ic", e.getClassName());
    e = cp.getDecrementer();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("dc", e.getClassName());
    s = xd.getSecurity();
    assertNotNull(s);
    assertEquals("HsqlDbRealm", s.getSecurityDomain());
    e = s.getReauthPlugin();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass1", e.getClassName());
    Recovery r = xd.getRecovery();
    assertNotNull(r);
    assertFalse(r.isNoRecovery());
    Credential c = (Credential) r.getCredential();
    assertNotNull(c);
    assertEquals("RecoveryUser", c.getUserName());
    assertEquals("RecoveryPassword", c.getPassword());
    assertNull(c.getSecurityDomain());
    e = r.getPlugin();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass5", e.getClassName());
    assertEquals("some-module-name", e.getModuleName());
    assertEquals("some-module-slot", e.getModuleSlot());
    v = xd.getValidation();
    assertNotNull(v);
    assertEquals("select 1", v.getCheckValidConnectionSql());
    assertTrue(v.isBackgroundValidation());
    assertTrue(v.isValidateOnMatch());
    assertTrue(v.isUseFastFail());
    assertEquals(2000L, (long) v.getBackgroundValidationMillis());
    e = v.getValidConnectionChecker();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass2", e.getClassName());
    e = v.getStaleConnectionChecker();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass3", e.getClassName());
    e = v.getExceptionSorter();
    properties = e.getConfigPropertiesMap();
    assertEquals(2, properties.size());
    assertEquals("Property1", properties.get("name1"));
    assertEquals("Property2", properties.get("name2"));
    assertEquals("someClass4", e.getClassName());
    t = xd.getTimeout();
    assertNotNull(t);
    assertEquals(20000L, (long) t.getBlockingTimeoutMillis());
    assertEquals(4, (int) t.getIdleTimeoutMinutes());
    assertEquals(120L, (long) t.getQueryTimeout());
    assertEquals(100L, (long) t.getUseTryLock());
    assertEquals(2L, (long) t.getAllocationRetry());
    assertEquals(3000L, (long) t.getAllocationRetryWaitMillis());
    assertTrue(t.isSetTxQueryTimeout());
    st = xd.getStatement();
    assertNotNull(st);
    assertEquals(30L, (long) st.getPreparedStatementsCacheSize());
    assertTrue(st.isSharePreparedStatements());
    assertEquals(TrackStatementsEnum.TRUE, st.getTrackStatements());
    List<Driver> drivers = ds.getDrivers();
    assertEquals(2, drivers.size());
    Driver driver = ds.getDriver("h2");
    assertTrue(drivers.contains(driver));
    assertNotNull(driver);
    assertEquals("h2", driver.getName());
    assertEquals(null, driver.getMajorVersion());
    assertEquals(null, driver.getMinorVersion());
    assertEquals("com.h2database.h2", driver.getModule());
    assertEquals(null, driver.getDriverClass());
    assertEquals(null, driver.getXaDataSourceClass());
    assertEquals("org.h2.jdbcx.JdbcDataSource", driver.getDataSourceClass());
    driver = ds.getDriver("pg");
    assertNotNull(driver);
    assertTrue(drivers.contains(driver));
    assertEquals(9, (int) driver.getMajorVersion());
    assertEquals(1, (int) driver.getMinorVersion());
    assertEquals("org.pg.postgres", driver.getModule());
    assertEquals("org.pg.Driver", driver.getDriverClass());
    assertEquals("org.pg.JdbcDataSource", driver.getXaDataSourceClass());
    assertEquals(null, driver.getDataSourceClass());
}
Example 93
Project: openengsb-master  File: AbstractExamTestHelper.java View source code
private static Option[] getDefaultEDBConfiguration() {
    String cfg = "etc/org.openengsb.infrastructure.jpa.cfg";
    return new Option[] { editConfigurationFilePut(cfg, "url", "jdbc:h2:mem:itests"), editConfigurationFilePut(cfg, "driverClassName", "org.h2.jdbcx.JdbcDataSource"), editConfigurationFilePut(cfg, "username", ""), editConfigurationFilePut(cfg, "password", "") };
}
Example 94
Project: teiid-master  File: TestRelate.java View source code
@BeforeClass
public static void oneTimeSetUp() throws Exception {
    server = new FakeServer(true);
    JdbcDataSource h2ds = new JdbcDataSource();
    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);
    }
}
Example 95
Project: taplib-master  File: TestConfigurableTAPFactory.java View source code
private static void setJNDIDatasource() throws NamingException {
    // Create an initial JNDI context:
    /* note: this requires that the simple-jndi jar is in the classpath. (https://code.google.com/p/osjava/downloads/detail?name=simple-jndi-0.11.4.1.zip&can=2&q=) */
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    // memory shared between all instances of InitialContext
    System.setProperty("org.osjava.sj.jndi.shared", "true");
    // Context initialization:
    InitialContext ic = new InitialContext();
    // Creation of a reference on a DataSource:
    JdbcDataSource datasource = new JdbcDataSource();
    datasource.setUrl(DBTools.DB_TEST_URL);
    datasource.setUser(DBTools.DB_TEST_USER);
    datasource.setPassword(DBTools.DB_TEST_PWD);
    // Link the datasource with the context:
    ic.rebind("jdbc/MyDataSource", datasource);
}
Example 96
Project: siena-master  File: H2Test.java View source code
@Override
public PersistenceManager createPersistenceManager(List<Class<?>> classes) throws Exception {
    if (pm == null) {
        Properties p = new Properties();
        String driver = "org.h2.Driver";
        String url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
        String username = "sa";
        String password = "";
        p.setProperty("driver", driver);
        p.setProperty("url", url);
        p.setProperty("user", username);
        p.setProperty("password", password);
        DdlGenerator generator = new DdlGenerator();
        for (Class<?> clazz : classes) {
            generator.addTable(clazz);
        }
        // get the Database model
        Database database = generator.getDatabase();
        Platform platform = PlatformFactory.createNewPlatformInstance("mysql");
        Class.forName(driver);
        //JdbcDataSource ds = new JdbcDataSource();
        //ds.setURL(url);
        //Connection connection = ds.getConnection();
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(platform.getAlterTablesSql(connection, database));
        // this will perform the database changes
        platform.alterTables(connection, database, true);
        connection.close();
        pm = new H2PersistenceManager();
        pm.init(p);
    }
    return pm;
}
Example 97
Project: jxta-master  File: H2AdvertisementCache.java View source code
@Override
protected ConnectionPoolDataSource createDataSource() {
    if (!loadDbDriver("org.h2.Driver")) {
        throw new RuntimeException("Unable to loadDB driver: org.h2.Driver");
    }
    JdbcDataSource source = new JdbcDataSource();
    source.setURL("jdbc:h2:" + dbDir.getAbsolutePath());
    return source;
}
Example 98
Project: ultm-master  File: H2DemoDatabase.java View source code
public void setup() throws SQLException {
    h2DataSource = new JdbcDataSource();
    h2DataSource.setURL("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
    try (Connection conn = h2DataSource.getConnection()) {
        conn.createStatement().execute("create table PERSONS (ID int, NAME varchar);");
    }
}
Example 99
Project: jxse-master  File: H2AdvertisementCache.java View source code
@Override
protected ConnectionPoolDataSource createDataSource() {
    if (!loadDbDriver("org.h2.Driver")) {
        throw new RuntimeException("Unable to loadDB driver: org.h2.Driver");
    }
    JdbcDataSource source = new JdbcDataSource();
    source.setURL("jdbc:h2:" + dbDir.getAbsolutePath());
    return source;
}
Example 100
Project: brainslug-master  File: TestDataSourceConfiguration.java View source code
private XADataSource createH2Datasource() {
    JdbcDataSource jdbcDataSource = new JdbcDataSource();
    jdbcDataSource.setURL(getJdbcUrl());
    jdbcDataSource.setUser(getDbUser());
    jdbcDataSource.setPassword(getDbPassword());
    return jdbcDataSource;
}
Example 101
Project: embedded-db-junit-master  File: EmbeddedDataSourceTest.java View source code
@Test
public void testIsWrapperFor() throws Exception {
    assertFalse(dataSource.isWrapperFor(JdbcDataSource.class));
}