Java Code Examples for javax.sql.CommonDataSource

The following examples show how to use javax.sql.CommonDataSource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: requery   Source File: TimeConversionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    Platform platform = new HSQL();
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = Models.MODEL2;

    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new EmptyEntityCache())
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    data = new EntityDataStore<>(configuration);
}
 
Example 2
Source Project: requery   Source File: JPAModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(new H2());
    EntityModel model = Models.JPA;

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build())
        .build();
    data = new EntityDataStore<>(configuration);
    SchemaModifier tables = new SchemaModifier(configuration);
    tables.dropTables();
    TableCreationMode mode = TableCreationMode.CREATE;
    System.out.println(tables.createTablesString(mode));
    tables.createTables(mode);
}
 
Example 3
Source Project: requery   Source File: UpsertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = Models.MODEL3;

    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new EmptyEntityCache())
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    System.out.println(tables.createTablesString(TableCreationMode.DROP_CREATE));
    data = new EntityDataStore<>(configuration);
}
 
Example 4
Source Project: requery   Source File: ReactorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    Platform platform = new HSQL();
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = io.requery.test.model.Models.DEFAULT;

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    data = new ReactorEntityStore<>(new EntityDataStore<Persistable>(configuration));
}
 
Example 5
Source Project: requery   Source File: StatelessTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = Models.STATELESS;

    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new EmptyEntityCache())
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    System.out.println(tables.createTablesString(TableCreationMode.DROP_CREATE));
    data = new EntityDataStore<>(configuration);
}
 
Example 6
Source Project: requery   Source File: AutoValueModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(new SQLite());
    EntityModel model = Models.AUTOVALUE;
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .build())
        .build();
    data = new EntityDataStore<>(configuration);
    SchemaModifier tables = new SchemaModifier(configuration);
    tables.dropTables();
    TableCreationMode mode = TableCreationMode.CREATE_NOT_EXISTS;
    System.out.println(tables.createTablesString(mode));
    tables.createTables(mode);
}
 
Example 7
Source Project: requery   Source File: ReactiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    Platform platform = new HSQL();
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = io.requery.test.model.Models.DEFAULT;

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    data = ReactiveSupport.toReactiveStore(new EntityDataStore<Persistable>(configuration));
}
 
Example 8
Source Project: requery   Source File: SchemaModifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = io.requery.test.model.Models.DEFAULT;

    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setStatementCacheSize(10)
        .setBatchUpdateSize(50)
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .build();

    schemaModifier = new SchemaModifier(configuration);
    try {
        schemaModifier.dropTables();
    } catch (Exception e) {
        // expected if 'drop if exists' not supported (so ignore in that case)
        if (!platform.supportsIfExists()) {
            throw e;
        }
    }
    schemaModifier.createTables(TableCreationMode.CREATE);
}
 
Example 9
Source Project: clearpool   Source File: DataSourceUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static CommonDataSource getJDBCDataSource(String clazz, String url, String user,
    String password) {
  if (url == null) {
    throw new ConnectionPoolException("url is null");
  }
  Driver driver;
  try {
    if (clazz == null) {
      clazz = JdbcUtils.getDriverClassName(url);
    }
    driver = JdbcUtils.createDriver(clazz);
  } catch (SQLException e) {
    throw new ConnectionPoolException(e);
  }
  Properties connectProperties = new Properties();
  if (user != null) {
    connectProperties.put("user", user);
  }
  if (password != null) {
    connectProperties.put("password", password);
  }
  return new JDBCDataSource(clazz, url, driver, connectProperties);
}
 
Example 10
Source Project: tomee   Source File: DbcpDataSourceCreator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CommonDataSource pool(final String name, final String driver, final Properties properties) {
    properties.setProperty("name", name);

    final String xa = String.class.cast(properties.remove("XaDataSource"));
    if (xa == null && !properties.containsKey("JdbcDriver")) {
        properties.setProperty("driverClassName", driver);
    }

    final BasicDataSource ds = build(BasicDataSource.class, properties);
    ds.setDriverClassName(driver);
    if (xa != null) {
        ds.setDelegate(XADataSourceResource.proxy(Thread.currentThread().getContextClassLoader(), xa));
    }
    return ds;
}
 
Example 11
public String resolveDataSourceName(CommonDataSource dataSource) {
    String dataSourceName = cachedNames.get(dataSource);
    if (dataSourceName == null) {
        // even if two threads compute this in parallel result will be the same
        synchronized (cachedNames) {
            if (HIKARI_AVAILABLE && dataSource instanceof HikariDataSource) {
                HikariDataSource hikariDataSource = (HikariDataSource) dataSource;
                if (hikariDataSource.getPoolName() != null && !hikariDataSource.getPoolName().startsWith("HikariPool-")) {
                    return hikariDataSource.getPoolName();
                }
            }
            Map<String, DataSource> dataSources = applicationContext.getBeansOfType(DataSource.class);
            dataSourceName = dataSources.entrySet()
                    .stream()
                    .filter(entry -> {
                        DataSource candidate = entry.getValue();
                        if (candidate instanceof DecoratedDataSource) {
                            return matchesDataSource((DecoratedDataSource) candidate, dataSource);
                        }
                        return candidate == dataSource;
                    })
                    .findFirst()
                    .map(Entry::getKey)
                    .orElse("dataSource");
            cachedNames.put(dataSource, dataSourceName);
        }
    }
    return dataSourceName;
}
 
Example 12
Source Project: requery   Source File: JacksonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(new SQLite());
    EntityModel model = Models.MODEL3;
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new WeakEntityCache())
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    data = new EntityDataStore<>(configuration);
}
 
Example 13
Source Project: requery   Source File: ParameterizedFunctionalTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = Models.DEFAULT;

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        // work around bug reusing prepared statements in xerial sqlite
        .setStatementCacheSize(platform instanceof SQLite ? 0 : 10)
        .setBatchUpdateSize(50)
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build())
        .build();
    data = new EntityDataStore<>(configuration);
    SchemaModifier tables = new SchemaModifier(configuration);
    try {
        tables.dropTables();
    } catch (Exception e) {
        // expected if 'drop if exists' not supported (so ignore in that case)
        if (!platform.supportsIfExists()) {
            throw e;
        }
    }
    TableCreationMode mode = TableCreationMode.CREATE;
    System.out.println(tables.createTablesString(mode));
    tables.createTables(mode);
}
 
Example 14
Source Project: clearpool   Source File: ConnectionPool.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String get03_DriverClassName() {
  CommonDataSource dataSource = this.pool.getCfgVO().getDataSource();
  if (dataSource instanceof JDBCDataSource) {
    JDBCDataSource jdbcDataSource = (JDBCDataSource) dataSource;
    String clazz = jdbcDataSource.getClazz();
    if (clazz != null) {
      return clazz;
    }
  }
  return "-";
}
 
Example 15
Source Project: clearpool   Source File: ConnectionPool.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String get04_Url() {
  CommonDataSource dataSource = this.pool.getCfgVO().getDataSource();
  if (dataSource instanceof JDBCDataSource) {
    JDBCDataSource jdbcDataSource = (JDBCDataSource) dataSource;
    String url = jdbcDataSource.getUrl();
    if (url != null) {
      return url;
    }
  }
  return "-";
}
 
Example 16
Source Project: tomee   Source File: TomEEDataSourceCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CommonDataSource pool(final String name, final String driver, final Properties properties) {
    final PoolConfiguration config = build(TomEEPoolProperties.class, createProperties(name, properties));
    final TomEEDataSource ds = new TomEEDataSource(config, name);
    recipes.put(ds, recipes.remove(config));
    return ds;
}
 
Example 17
Source Project: tomee   Source File: TomEEDataSourceCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doDestroy(final CommonDataSource dataSource) throws Throwable {
    final org.apache.tomcat.jdbc.pool.DataSource ds = (org.apache.tomcat.jdbc.pool.DataSource) dataSource;
    if (ds instanceof TomEEDataSource) {
        ((TomEEDataSource) ds).internalJMXUnregister();
    }
    ds.close(true);
}
 
Example 18
Source Project: tomee   Source File: DbcpDataSourceCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSource managed(final String name, final CommonDataSource ds) {
    final TransactionManager transactionManager = OpenEJB.getTransactionManager();
    if (ds instanceof XADataSource) {
        return new ManagedXADataSource(ds, transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    }
    return new ManagedDataSource(DataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
 
Example 19
Source Project: tomee   Source File: DbcpManagedDataSource.java    License: Apache License 2.0 5 votes vote down vote up
public DbcpManagedDataSource(final String name, final CommonDataSource dataSource) {
    super(name);
    this.ds = dataSource;
    if (XADataSource.class.isInstance(dataSource)) {
        setXaDataSourceInstance(XADataSource.class.cast(ds));
    }
}
 
Example 20
Source Project: tomee   Source File: PoolDataSourceCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSource managed(final String name, final CommonDataSource ds) {
    final TransactionManager transactionManager = OpenEJB.getTransactionManager();
    if (ds instanceof XADataSource) {
        return new ManagedXADataSource(ds, transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    }
    return new ManagedDataSource(DataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
 
Example 21
Source Project: tomee   Source File: PoolDataSourceCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSource poolManagedWithRecovery(final String name, final XAResourceWrapper xaResourceWrapper, final String driver, final Properties properties) {
    final TransactionManager transactionManager = new TransactionManagerWrapper(OpenEJB.getTransactionManager(), name, xaResourceWrapper);
    final CommonDataSource ds = pool(name, driver, properties);
    if (ds instanceof XADataSource) {
        return new ManagedXADataSource(ds, transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    }
    return new ManagedDataSource(DataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
 
Example 22
Source Project: tomee   Source File: FlushableDataSourceHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void createANewDelegate() {
    final CommonDataSource old = delegate.get();
    try {
        final ObjectRecipe recipe = new ObjectRecipe(DataSourceFactory.class.getName(), "create", FACTORY_ARGS);
        recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
        recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
        recipe.allow(Option.NAMED_PARAMETERS);
        recipe.allow(Option.PRIVATE_PROPERTIES);
        recipe.setAllProperties(config.properties);

        recipe.setProperty("resettableHandler", resettableHandler);
        recipe.setProperty("flushableHandler", this);

        updateDataSource(CommonDataSource.class.cast(recipe.create()));
    } catch (final Exception e) {
        LOGGER.error("Can't recreate the datasource, keeping old one", e);
        return;
    }

    if (DataSourceFactory.knows(old)) {
        try {
            DataSourceFactory.destroy(old);
        } catch (final Throwable t) {
            //Ignore
        }
    }
}
 
Example 23
Source Project: tomee   Source File: FlushableDataSourceHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void updateDataSource(final CommonDataSource ds) { // order is important, check DataSourceFactory
    CommonDataSource current = ds;
    while (Proxy.isProxyClass(current.getClass())) {
        final InvocationHandler handler = Proxy.getInvocationHandler(current);
        if (FlushableDataSourceHandler.class.isInstance(handler) ||
            ResettableDataSourceHandler.class.isInstance(handler)) {
            current = DelegatableHandler.class.cast(handler).getDelegate();
        } else {
            break;
        }
    }
    delegate.set(current);
}
 
Example 24
Source Project: tomee   Source File: ResettableDataSourceHandler.java    License: Apache License 2.0 5 votes vote down vote up
public ResettableDataSourceHandler(final CommonDataSource ds, final String value, final String methods) {
    this.delegate.set(ds);

    if (!"*".equals(methods)) {
        this.retryMethods.addAll(asList(methods == null ? new String[]{"getConnection", "getXAConnection"} : methods.split(" *, *")));
    }

    final Runnable recreate = new Runnable() {
        @Override
        public void run() {
            try {
                Flushable.class.cast(delegate.get()).flush();
            } catch (final IOException ioe) {
                LOGGER.error("Can't flush connection pool: " + ioe.getMessage());
            }
        }
    };

    RetryStrategy tmp;
    if (value.equals("true")) {
        tmp = new CountRetryStrategy(recreate, 1);
    } else if (value.startsWith("retry(") && value.endsWith(")")) {
        tmp = new CountRetryStrategy(recreate, Integer.parseInt(value.substring("retry(".length(), value.length() - 1)));
    } else {
        try {
            tmp = new CountRetryStrategy(recreate, Integer.parseInt(value.trim()));
        } catch (final NumberFormatException nfe) {
            try {
                tmp = RetryStrategy.class.cast(Thread.currentThread().getContextClassLoader().loadClass(value)
                    .getConstructor(Runnable.class, String.class).newInstance(recreate, value));
            } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) {
                throw new IllegalArgumentException("Unknown retry strategy: " + value, e);
            }
        }
    }
    strategy = tmp;
}
 
Example 25
Source Project: tomee   Source File: FlushableDataSourceHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void checkIt() throws IOException {
    assertThat(ds, instanceOf(Flushable.class));
    assertThat(ds, instanceOf(DataSource.class));
    final FlushableDataSourceHandler handler = FlushableDataSourceHandler.class.cast(Proxy.getInvocationHandler(ds));
    final CommonDataSource delegate = handler.getDelegate();
    assertNotNull(delegate);
    assertFalse(BasicDataSource.class.cast(delegate).isClosed());
    Flushable.class.cast(ds).flush();
    assertTrue(BasicDataSource.class.cast(delegate).isClosed());
    final CommonDataSource newDelegate = handler.getDelegate();
    assertFalse(BasicDataSource.class.cast(newDelegate).isClosed());
    assertNotSame(newDelegate, delegate);
}
 
Example 26
Source Project: tomee   Source File: DataSourceHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void setUrl(final CommonDataSource dataSource, final String url) throws Exception {
    // TODO This is a big whole and we will need to rework this
    if (url.contains("jdbc:derby:")) {
        DataSourceHelper.setUrl(dataSource, url.replace("jdbc:derby:", ""), dataSource.getClass().getClassLoader(), "org.apache.derby.jdbc.EmbeddedDataSource", "setDatabaseName");
    } else {
        DataSourceHelper.setUrl(dataSource, url, dataSource.getClass().getClassLoader(), "org.hsqldb.jdbc.JDBCDataSource", "setDatabase");
    }
}
 
Example 27
Source Project: tomee   Source File: SimpleDataSourceCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSource managed(final String name, final CommonDataSource ds) {
    final TransactionManager transactionManager = OpenEJB.getTransactionManager();
    if (XADataSource.class.isInstance(ds)) {
        return new ManagedXADataSource(XADataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    }
    return new ManagedDataSource(DataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
 
Example 28
Source Project: tomee   Source File: ManagedDataSource.java    License: Apache License 2.0 5 votes vote down vote up
protected static Connection getTxConnection(final CommonDataSource delegate, final String u, final String p, final TransactionManager transactionManager, final TransactionSynchronizationRegistry registry) {
    try {
        final Transaction transaction = transactionManager.getTransaction();
        if (transaction != null && ManagedConnection.isUnderTransaction(transaction.getStatus())) {
            final Object resource = registry.getResource(new Key(delegate, u, p));
            if (Connection.class.isInstance(resource)) {
                return Connection.class.cast(resource);
            }
        }
    } catch (SystemException e) {
        // we wouldn't expect this to happen, but lets log it and fall through to the previous behaviour
        LOGGER.warning("Attempting to get the current transaction failed with an error: " + e.getMessage(), e);
    }
    return null;
}
 
Example 29
Source Project: tomee   Source File: ManagedConnection.java    License: Apache License 2.0 5 votes vote down vote up
public ManagedConnection(final CommonDataSource ds,
                         final TransactionManager txMgr,
                         final TransactionSynchronizationRegistry txRegistry,
                         final String user, final String password) {
    transactionManager = txMgr;
    registry = txRegistry;
    closed = false;
    key = new Key(ds, user, password);

    if (LOGGER.isDebugEnabled()) {
        createdAt = new Throwable().getStackTrace();
    }
}
 
Example 30
Source Project: tomee   Source File: Key.java    License: Apache License 2.0 5 votes vote down vote up
public Key(final CommonDataSource ds, final String user, final String pwd) {
    this.ds = ds;
    this.user = user;
    this.pwd = pwd;

    int result = ds.hashCode();
    result = 31 * result + (user != null ? user.hashCode() : 0);
    result = 31 * result + (pwd != null ? pwd.hashCode() : 0);
    hash = result;
}