Search in sources :

Example 11 with CommonDataSource

use of javax.sql.CommonDataSource in project tomee by apache.

the class DataSourceFactory method create.

public static CommonDataSource create(final String name, final boolean configuredManaged, final Class impl, final String definition, final Duration maxWaitTime, final Duration timeBetweenEvictionRuns, final Duration minEvictableIdleTime, final boolean useAlternativeDriver) throws IllegalAccessException, InstantiationException, IOException {
    final Properties properties = asProperties(definition);
    final Set<String> originalKeys = properties.stringPropertyNames();
    final String handler = SystemInstance.get().getOptions().get(GLOBAL_HANDLER_PROPERTY, (String) properties.remove(HANDLER_PROPERTY));
    boolean flushable = SystemInstance.get().getOptions().get(GLOBAL_FLUSH_PROPERTY, "true".equalsIgnoreCase((String) properties.remove(FLUSHABLE_PROPERTY)));
    final String forceDifferent = SystemInstance.get().getOptions().get(XA_GLOBAL_FORCE_DIFFERENT, String.class.cast(properties.remove(XA_FORCE_DIFFERENT)));
    convert(properties, maxWaitTime, "maxWaitTime", "maxWait");
    convert(properties, timeBetweenEvictionRuns, "timeBetweenEvictionRuns", "timeBetweenEvictionRunsMillis");
    convert(properties, minEvictableIdleTime, "minEvictableIdleTime", "minEvictableIdleTimeMillis");
    // these can be added and are managed by OpenEJB and not the DataSource itself
    properties.remove("Definition");
    properties.remove("JtaManaged");
    properties.remove("ServiceId");
    boolean managed = configuredManaged;
    if (properties.containsKey("transactional")) {
        managed = Boolean.parseBoolean((String) properties.remove("transactional")) || managed;
    }
    normalizeJdbcUrl(properties);
    final String jdbcUrl = properties.getProperty("JdbcUrl");
    final AlternativeDriver driver;
    if (Driver.class.isAssignableFrom(impl) && jdbcUrl != null && useAlternativeDriver) {
        try {
            driver = new AlternativeDriver((Driver) impl.newInstance(), jdbcUrl);
            driver.register();
        } catch (final SQLException e) {
            throw new IllegalStateException(e);
        }
    } else {
        driver = null;
    }
    final boolean logSql = SystemInstance.get().getOptions().get(GLOBAL_LOG_SQL_PROPERTY, "true".equalsIgnoreCase((String) properties.remove(LOG_SQL_PROPERTY)));
    final String logPackages = SystemInstance.get().getProperty(GLOBAL_LOG_SQL_PACKAGE_PROPERTY, (String) properties.remove(LOG_SQL_PACKAGE_PROPERTY));
    final DataSourceCreator creator = creator(properties.remove(DATA_SOURCE_CREATOR_PROP), logSql);
    final String resetOnError = (String) properties.remove(RESET_PROPERTY);
    // before setProperties()
    final String resetMethods = (String) properties.remove(RESET_METHODS_PROPERTY);
    boolean useContainerLoader = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.resources.use-container-loader", "true")) && impl.getClassLoader() == DataSourceFactory.class.getClassLoader();
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    if (useContainerLoader) {
        final ClassLoader containerLoader = DataSourceFactory.class.getClassLoader();
        Thread.currentThread().setContextClassLoader(containerLoader);
        try {
            useContainerLoader = basicChecksThatDataSourceCanBeCreatedFromContainerLoader(properties, containerLoader);
        } finally {
            Thread.currentThread().setContextClassLoader(oldLoader);
        }
        if (useContainerLoader) {
            Thread.currentThread().setContextClassLoader(containerLoader);
        } else {
            LOGGER.info("Can't use container loader to create datasource " + name + " so using application one");
        }
    }
    try {
        CommonDataSource ds;
        if (createDataSourceFromClass(impl)) {
            // opposed to "by driver"
            trimNotSupportedDataSourceProperties(properties);
            final ObjectRecipe recipe = new ObjectRecipe(impl);
            recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
            recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
            recipe.allow(Option.NAMED_PARAMETERS);
            recipe.allow(Option.PRIVATE_PROPERTIES);
            recipe.setAllProperties(properties);
            if (!properties.containsKey("url") && properties.containsKey("JdbcUrl")) {
                // depend on the datasource class so add all well known keys
                recipe.setProperty("url", properties.getProperty("JdbcUrl"));
            }
            CommonDataSource dataSource = (CommonDataSource) recipe.create();
            final boolean isDs = DataSource.class.isInstance(dataSource);
            if (!isDs && XADataSource.class.isInstance(dataSource) && forceDifferent != null) {
                try {
                    dataSource = CommonDataSource.class.cast(Thread.currentThread().getContextClassLoader().loadClass("true".equals(forceDifferent) ? "org.apache.openejb.resource.jdbc.xa.IsDifferentXaDataSourceWrapper" : forceDifferent).getConstructor(XADataSource.class).newInstance(dataSource));
                } catch (InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {
                    throw new IllegalArgumentException(e);
                }
            }
            if (managed) {
                if (isDs && usePool(properties)) {
                    ds = creator.poolManaged(name, DataSource.class.cast(dataSource), properties);
                } else {
                    ds = creator.managed(name, dataSource);
                }
            } else {
                if (isDs && usePool(properties)) {
                    ds = creator.pool(name, DataSource.class.cast(dataSource), properties);
                } else {
                    ds = dataSource;
                }
            }
        } else {
            // by driver
            if (managed) {
                final XAResourceWrapper xaResourceWrapper = SystemInstance.get().getComponent(XAResourceWrapper.class);
                if (xaResourceWrapper != null) {
                    ds = creator.poolManagedWithRecovery(name, xaResourceWrapper, impl.getName(), properties);
                } else {
                    ds = creator.poolManaged(name, impl.getName(), properties);
                }
            } else {
                ds = creator.pool(name, impl.getName(), properties);
            }
        }
        // ds and creator are associated here, not after the proxying of the next if if active
        setCreatedWith(creator, ds);
        if (driver != null) {
            driverByDataSource.put(ds, driver);
        }
        final boolean doResetOnError = resetOnError != null && !"false".equals(resetOnError);
        if (doResetOnError || logSql || flushable) {
            // will get proxied
            ObjectRecipe objectRecipe = null;
            ResettableDataSourceHandler existingResettableHandler = null;
            FlushableDataSourceHandler flushableDataSourceHandler = null;
            if (ExecutionContext.isContextSet()) {
                final ExecutionContext context = ExecutionContext.getContext();
                final List<Recipe> stack = context.getStack();
                if (stack.size() > 0) {
                    objectRecipe = ObjectRecipe.class.cast(stack.get(0));
                    existingResettableHandler = ResettableDataSourceHandler.class.cast(objectRecipe.getProperty("resettableHandler"));
                    flushableDataSourceHandler = FlushableDataSourceHandler.class.cast(objectRecipe.getProperty("flushableHandler"));
                    final Map<String, Object> props = objectRecipe.getProperties();
                    for (final String key : originalKeys) {
                        props.remove(key);
                    }
                    // meta properties, not needed here so gain few cycles removing them
                    props.remove("properties");
                    props.remove("Definition");
                    props.remove("ServiceId");
                    props.remove("resettableHandler");
                    props.remove("flushableHandler");
                    // we create a proxy so we cant get txmgr etc in another manner or we cant extend (= break) this method
                    new ObjectRecipe(ds.getClass()) {

                        {
                            allow(Option.CASE_INSENSITIVE_PROPERTIES);
                            allow(Option.IGNORE_MISSING_PROPERTIES);
                            allow(Option.NAMED_PARAMETERS);
                            allow(Option.PRIVATE_PROPERTIES);
                            setAllProperties(props);
                        }
                    }.setProperties(ds);
                }
            }
            ds = wrapIfNeeded(handler, ds);
            if (logSql) {
                ds = makeItLogging(ds, logPackages);
            }
            final ResettableDataSourceHandler resettableDataSourceHandler;
            if (doResetOnError) {
                // needs to be done after flushable
                // ensure we reuse the same handle instance otherwise we loose state
                resettableDataSourceHandler = existingResettableHandler != null ? existingResettableHandler : new ResettableDataSourceHandler(ds, resetOnError, resetMethods);
            } else {
                resettableDataSourceHandler = null;
            }
            if (flushable || doResetOnError) {
                if (flushableDataSourceHandler == null) {
                    final FlushableDataSourceHandler.FlushConfig flushConfig;
                    // don't let it wrap the delegate again
                    properties.remove("flushable");
                    final Map<String, Object> recipeProps = new HashMap<>(objectRecipe == null ? new HashMap<>() : objectRecipe.getProperties());
                    recipeProps.remove("properties");
                    recipeProps.put("OpenEJBResourceClasspath", String.valueOf(useAlternativeDriver));
                    flushConfig = new FlushableDataSourceHandler.FlushConfig(recipeProps);
                    flushableDataSourceHandler = new FlushableDataSourceHandler(ds, flushConfig, resettableDataSourceHandler);
                } else {
                    flushableDataSourceHandler.updateDataSource(ds);
                }
                ds = makeSerializableFlushableDataSourceProxy(ds, flushableDataSourceHandler);
            }
            if (doResetOnError) {
                // needs to be done after flushable
                // ensure we reuse the same handle instance otherwise we loose state
                resettableDataSourceHandler.updateDelegate(ds);
                ds = makeSerializableFlushableDataSourceProxy(ds, resettableDataSourceHandler);
            }
        } else {
            ds = wrapIfNeeded(handler, ds);
        }
        return ds;
    } finally {
        if (useContainerLoader) {
            Thread.currentThread().setContextClassLoader(oldLoader);
        }
    }
}
Also used : SQLException(java.sql.SQLException) Recipe(org.apache.xbean.recipe.Recipe) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) HashMap(java.util.HashMap) Driver(java.sql.Driver) AlternativeDriver(org.apache.openejb.resource.jdbc.driver.AlternativeDriver) Properties(java.util.Properties) SuperProperties(org.apache.openejb.util.SuperProperties) DataSourceCreator(org.apache.openejb.resource.jdbc.pool.DataSourceCreator) DefaultDataSourceCreator(org.apache.openejb.resource.jdbc.pool.DefaultDataSourceCreator) DbcpDataSourceCreator(org.apache.openejb.resource.jdbc.dbcp.DbcpDataSourceCreator) XAResourceWrapper(org.apache.openejb.resource.XAResourceWrapper) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) XADataSource(javax.sql.XADataSource) CommonDataSource(javax.sql.CommonDataSource) InvocationTargetException(java.lang.reflect.InvocationTargetException) AlternativeDriver(org.apache.openejb.resource.jdbc.driver.AlternativeDriver) ExecutionContext(org.apache.xbean.recipe.ExecutionContext)

Example 12 with CommonDataSource

use of javax.sql.CommonDataSource in project aries by apache.

the class Activator method start.

public void start(BundleContext ctx) {
    context = ctx;
    // Expose blueprint namespace handler if xbean is present
    try {
        nshReg = JdbcNamespaceHandler.register(ctx);
    } catch (NoClassDefFoundError e) {
        LOGGER.warn("Unable to register JDBC blueprint namespace handler (xbean-blueprint not available).");
    } catch (Exception e) {
        LOGGER.error("Unable to register JDBC blueprint namespace handler", e);
    }
    Filter filter;
    String flt = "(&(|(objectClass=javax.sql.XADataSource)(objectClass=javax.sql.DataSource))(!(aries.managed=true)))";
    try {
        filter = context.createFilter(flt);
    } catch (InvalidSyntaxException e) {
        throw new IllegalStateException(e);
    }
    t = new ServiceTracker<CommonDataSource, ManagedDataSourceFactory>(ctx, filter, this);
    tm = new SingleServiceTracker<AriesTransactionManager>(ctx, AriesTransactionManager.class, this);
    tm.open();
}
Also used : Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) AriesTransactionManager(org.apache.aries.transaction.AriesTransactionManager) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) CommonDataSource(javax.sql.CommonDataSource)

Example 13 with CommonDataSource

use of javax.sql.CommonDataSource in project requery by requery.

the class ReactiveTest method setup.

@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));
}
Also used : ConfigurationBuilder(io.requery.sql.ConfigurationBuilder) Platform(io.requery.sql.Platform) Configuration(io.requery.sql.Configuration) HSQL(io.requery.sql.platform.HSQL) EntityDataStore(io.requery.sql.EntityDataStore) EntityModel(io.requery.meta.EntityModel) CacheManager(javax.cache.CacheManager) EntityCacheBuilder(io.requery.cache.EntityCacheBuilder) CommonDataSource(javax.sql.CommonDataSource) CachingProvider(javax.cache.spi.CachingProvider) SchemaModifier(io.requery.sql.SchemaModifier) Before(org.junit.Before)

Example 14 with CommonDataSource

use of javax.sql.CommonDataSource in project requery by requery.

the class SchemaModifierTest method setup.

@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);
}
Also used : ConfigurationBuilder(io.requery.sql.ConfigurationBuilder) Configuration(io.requery.sql.Configuration) EntityModel(io.requery.meta.EntityModel) CommonDataSource(javax.sql.CommonDataSource) SQLException(java.sql.SQLException) SchemaModifier(io.requery.sql.SchemaModifier) Before(org.junit.Before)

Example 15 with CommonDataSource

use of javax.sql.CommonDataSource in project requery by requery.

the class AutoValueModelTest method setup.

@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);
}
Also used : ConfigurationBuilder(io.requery.sql.ConfigurationBuilder) Configuration(io.requery.sql.Configuration) TableCreationMode(io.requery.sql.TableCreationMode) SQLite(io.requery.sql.platform.SQLite) EntityModel(io.requery.meta.EntityModel) EntityCacheBuilder(io.requery.cache.EntityCacheBuilder) CommonDataSource(javax.sql.CommonDataSource) SchemaModifier(io.requery.sql.SchemaModifier) Before(org.junit.Before)

Aggregations

CommonDataSource (javax.sql.CommonDataSource)23 EntityModel (io.requery.meta.EntityModel)12 Configuration (io.requery.sql.Configuration)12 ConfigurationBuilder (io.requery.sql.ConfigurationBuilder)12 SchemaModifier (io.requery.sql.SchemaModifier)12 Before (org.junit.Before)12 EntityCacheBuilder (io.requery.cache.EntityCacheBuilder)6 Platform (io.requery.sql.Platform)5 HSQL (io.requery.sql.platform.HSQL)5 CacheManager (javax.cache.CacheManager)5 CachingProvider (javax.cache.spi.CachingProvider)5 EntityDataStore (io.requery.sql.EntityDataStore)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 DataSource (javax.sql.DataSource)4 XADataSource (javax.sql.XADataSource)4 EmptyEntityCache (io.requery.cache.EmptyEntityCache)3 TableCreationMode (io.requery.sql.TableCreationMode)3 SQLite (io.requery.sql.platform.SQLite)3 SQLException (java.sql.SQLException)3 Flushable (java.io.Flushable)2