javax.sql.CommonDataSource Java Examples

The following examples show how to use javax.sql.CommonDataSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DbcpDataSourceCreator.java    From tomee with 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 #2
Source File: TimeConversionsTest.java    From requery with 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 #3
Source File: JPAModelTest.java    From requery with 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 #4
Source File: DataSourceUtils.java    From clearpool with 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 #5
Source File: SchemaModifierTest.java    From requery with 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 #6
Source File: UpsertTest.java    From requery with 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 #7
Source File: ReactorTest.java    From requery with 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 #8
Source File: StatelessTest.java    From requery with 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 #9
Source File: AutoValueModelTest.java    From requery with 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 #10
Source File: ReactiveTest.java    From requery with 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 #11
Source File: TomEEDataSourceCreator.java    From tomee with 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 #12
Source File: DbcpManagedDataSource.java    From tomee with 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 #13
Source File: TomEEDataSourceCreator.java    From tomee with 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 #14
Source File: ManagedDataSource.java    From tomee with 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 #15
Source File: ConnectionPool.java    From clearpool with 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 File: JacksonTest.java    From requery with 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 #17
Source File: PersistenceUnitInfoImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void setNonJtaDataSource(final CommonDataSource nonJtaDataSource) {
    if (XADataSource.class.isInstance(nonJtaDataSource)) {
        this.nonJtaDataSource = new DataSourceXADataSource(
                nonJtaDataSource, OpenEJB.getTransactionManager(), SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    } else {
        this.nonJtaDataSource = DataSource.class.cast(nonJtaDataSource);
    }
}
 
Example #18
Source File: PersistenceUnitInfoImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void setJtaDataSource(final CommonDataSource jtaDataSource) {
    if (XADataSource.class.isInstance(jtaDataSource)) {
        this.jtaDataSource = new DataSourceXADataSource(
                jtaDataSource, OpenEJB.getTransactionManager(), SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
    } else {
        this.jtaDataSource = DataSource.class.cast(jtaDataSource);
    }
}
 
Example #19
Source File: Wrapper41DataSource.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public CommonDataSource   getWrappedObject() throws SQLException
{
    if ( _embedded != null ) { return _embedded; }
    else if ( _netclient != null ) { return _netclient; }
    else if ( _ecpds != null ) { return _ecpds; }
    else if ( _exads != null ) { return _exads; }
    else if ( _ccpds != null ) { return _ccpds; }
    else if ( _cxads != null ) { return _cxads; }
    else { throw nothingWrapped(); }
}
 
Example #20
Source File: ParameterizedFunctionalTest.java    From requery with 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 #21
Source File: SimpleDataSourceCreator.java    From tomee with 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 #22
Source File: DbcpDataSourceCreator.java    From tomee with 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 #23
Source File: DataSourceHelper.java    From tomee with 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 #24
Source File: DataSourceNameResolver.java    From spring-boot-data-source-decorator with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: FlushableDataSourceHandlerTest.java    From tomee with 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 File: PoolDataSourceCreator.java    From tomee with 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 #27
Source File: PoolDataSourceCreator.java    From tomee with 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 #28
Source File: ResettableDataSourceHandler.java    From tomee with 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 #29
Source File: FlushableDataSourceHandler.java    From tomee with 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 #30
Source File: FlushableDataSourceHandler.java    From tomee with 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
        }
    }
}