Example usage for java.sql Connection TRANSACTION_NONE

List of usage examples for java.sql Connection TRANSACTION_NONE

Introduction

In this page you can find the example usage for java.sql Connection TRANSACTION_NONE.

Prototype

int TRANSACTION_NONE

To view the source code for java.sql Connection TRANSACTION_NONE.

Click Source Link

Document

A constant indicating that transactions are not supported.

Usage

From source file:org.cloudgraph.rdb.service.RDBGraphService.java

public int count(Query query) {
    if (query == null)
        throw new IllegalArgumentException("expected non-null 'query' argument");
    validate(query);//from w ww  .j  a  va2  s.c  om
    if (log.isDebugEnabled()) {
        log(query);
    }
    Connection con = null;
    try {
        if (log.isDebugEnabled())
            log.debug("getting connection");
        con = ProviderManager.instance().getConnection();
        if (con.getAutoCommit()) {
            if (log.isDebugEnabled())
                log.debug("turning off connection autocommit for count query");
            con.setAutoCommit(false);
        }
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_NONE); // Oracle
            // does
            // not
            // support
            break;
        default:
        }
        // TODO: make transaction isolation configurable
        if (log.isDebugEnabled())
            log.debug(
                    "using transaction isolation level " + con.getTransactionIsolation() + " for count query");
    } catch (SQLException e2) {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        throw new DataAccessException(e2);
    }
    GraphQuery dispatcher = new GraphQuery(con);
    try {
        return dispatcher.count(query);
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
    }
}

From source file:org.libx4j.dbcp.DataSources.java

public static BasicDataSource createDataSource(final $dbcp_dbcp dbcp) throws SQLException {
    if (dbcp.isNull())
        throw new BindingRuntimeException("/dbcp:jdbc is missing");

    final dbcp_dbcp._jdbc jdbc = dbcp._jdbc(0);
    final BasicDataSource dataSource = new BasicDataSource() {
        @Override/*from   ww  w .j a  va 2  s  . c om*/
        public Connection getConnection() throws SQLException {
            //        try {
            return super.getConnection();
            //        }
            //        catch (final SQLException e) {
            //          // TODO: Finish this!
            //          if ("Cannot get a connection, pool error Timeout waiting for idle object".equals(e.getMessage()))
            //            Throwables.set(e, "XX" + e.getMessage());
            //
            //          throw e;
            //        }
        }
    };

    if (jdbc._driverClassName(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:driverClassName is missing");

    dataSource.setDriverClassName(jdbc._driverClassName(0).text());

    //    if (jdbc._loginTimeout() != null && jdbc._loginTimeout().size() != 0 && jdbc._loginTimeout(0).text() != null) {
    // FIXME: This causes a ClassNotFoundException: com.sybase.jdbc3.jdbc.SybDriver
    //      try {
    //        dataSource.setLoginTimeout(jdbc._loginTimeout(0).text());
    //      }
    //      catch(final SQLException e) {
    //        throw new SQLException(e);
    //      }
    //  }

    if (jdbc._url(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:url is missing");

    dataSource.setUrl(jdbc._url(0).text());

    if (jdbc._username(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:username is missing");

    dataSource.setUsername(jdbc._username(0).text());

    if (jdbc._password(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:password is missing");

    dataSource.setPassword(jdbc._password(0).text());
    final dbcp_dbcp._default defaults = dbcp._default(0);
    if (!defaults._connectionProperties(0).isNull())
        for (final dbcp_dbcp._default._connectionProperties._property property : defaults
                ._connectionProperties(0)._property())
            if (property._name$() != null && property._name$().text() != null && property._value$() != null
                    && property._value$().text() != null)
                dataSource.addConnectionProperty(property._name$().text(), property._value$().text());

    if (!defaults._autoCommit(0).isNull())
        dataSource.setDefaultAutoCommit(defaults._autoCommit(0).text());

    if (!defaults._readOnly(0).isNull())
        dataSource.setDefaultReadOnly(defaults._readOnly(0).text());

    if (!defaults._transactionIsolation(0).isNull()) {
        if (dbcp_dbcp._default._transactionIsolation.NONE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FUNCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.REPEATABLE_5FREAD.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if (dbcp_dbcp._default._transactionIsolation.SERIALIZABLE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + defaults._transactionIsolation(0).text());
    }

    final dbcp_dbcp._size size = dbcp._size(0);
    if (!size.isNull()) {
        if (!size._initialSize(0).isNull())
            dataSource.setInitialSize(size._initialSize(0).text().intValue());

        if (!size._maxActive(0).isNull())
            dataSource.setMaxTotal(size._maxActive(0).text().intValue());

        if (!size._maxIdle(0).isNull())
            dataSource.setMaxIdle(size._maxIdle(0).text().intValue());

        if (!size._minIdle(0).isNull())
            dataSource.setMinIdle(size._minIdle(0).text().intValue());

        if (!size._maxWait(0).isNull())
            dataSource.setMaxWaitMillis(size._maxWait(0).text().intValue());
    }

    final dbcp_dbcp._management management = dbcp._management(0);
    if (!management.isNull()) {
        if (!management._validationQuery(0).isNull())
            dataSource.setValidationQuery(management._validationQuery(0).text());

        if (!management._testOnBorrow(0).isNull())
            dataSource.setTestOnBorrow(management._testOnBorrow(0).text());

        if (!management._testOnReturn(0).isNull())
            dataSource.setTestOnReturn(management._testOnReturn(0).text());

        if (!management._testWhileIdle(0).isNull())
            dataSource.setTestWhileIdle(management._testWhileIdle(0).text());

        if (!management._timeBetweenEvictionRuns(0).isNull())
            dataSource
                    .setTimeBetweenEvictionRunsMillis(management._timeBetweenEvictionRuns(0).text().intValue());

        if (!management._numTestsPerEvictionRun(0).isNull())
            dataSource.setNumTestsPerEvictionRun(management._numTestsPerEvictionRun(0).text().intValue());

        if (!management._minEvictableIdleTime(0).isNull())
            dataSource.setMinEvictableIdleTimeMillis(management._minEvictableIdleTime(0).text().intValue());
    }

    final dbcp_dbcp._preparedStatements preparedStatements = dbcp._preparedStatements(0);
    if (!preparedStatements.isNull()) {
        if (!preparedStatements._poolPreparedStatements(0).isNull())
            dataSource.setPoolPreparedStatements(preparedStatements._poolPreparedStatements(0).text());

        if (!preparedStatements._maxOpenPreparedStatements(0).isNull())
            dataSource.setMaxOpenPreparedStatements(
                    preparedStatements._maxOpenPreparedStatements(0).text().intValue());
    }

    final dbcp_dbcp._removal removal = dbcp._removal(0);
    if (!removal.isNull()) {
        if (!removal._removeAbandoned(0).isNull())
            dataSource.setRemoveAbandonedOnBorrow(removal._removeAbandoned(0).text());

        if (!removal._removeAbandonedTimeout(0).isNull())
            dataSource.setRemoveAbandonedTimeout(removal._removeAbandonedTimeout(0).text().intValue());

        if (!removal._logAbandoned(0).isNull())
            dataSource.setLogAbandoned(removal._logAbandoned(0).text());
    }

    final dbcp_dbcp._logging logging = dbcp._logging(0);
    if (!logging.isNull()) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging._level(0).text()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(
                !logging._logExpiredConnections(0).isNull() && logging._logExpiredConnections(0).text());
        if (!logging._logAbandoned(0).isNull() && logging._logAbandoned(0).text()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}

From source file:at.ac.univie.isc.asio.engine.sql.WebRowSetWriter.java

private void properties(final String statement) throws XMLStreamException {
    // @formatter:off
    xml.writeStartElement(WRS, "properties");
    tag("command", statement);
    tag("concurrency", ResultSet.CONCUR_UPDATABLE);
    tag("datasource", null);
    tag("escape-processing", Boolean.TRUE);
    tag("fetch-direction", ResultSet.FETCH_FORWARD);
    tag("fetch-size", 0);
    tag("isolation-level", Connection.TRANSACTION_NONE);
    emptyTag("key-columns");
    emptyTag("map");
    tag("max-field-size", 0);
    tag("max-rows", 0);
    tag("query-timeout", 0);
    tag("read-only", Boolean.TRUE);
    tag("rowset-type", "ResultSet.TYPE_SCROLL_INSENSITIVE"); // must be constant name !
    tag("show-deleted", Boolean.FALSE);
    emptyTag("table-name"); // <null /> would represent java null - but is invalid according to schema
    tag("url", null);
    emptySyncProvider();/*  w ww  .j  a  v a 2  s. c  o m*/
    xml.writeEndElement();
    // @formatter:on
}

From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java

static int mapIsolationLevelToJdbc(IsolationLevel level) {
    switch (level) {
    case NONE:/*from   ww w .j  a v  a  2  s.com*/
    default:
        return Connection.TRANSACTION_NONE;
    case READ_UNCOMMITTED:
        return Connection.TRANSACTION_READ_UNCOMMITTED;
    case READ_COMMITTED:
        return Connection.TRANSACTION_READ_COMMITTED;
    case REPEATABLE_READ:
        return Connection.TRANSACTION_REPEATABLE_READ;
    case SNAPSHOT:
        // TODO: not accurate for all databases.
        return Connection.TRANSACTION_SERIALIZABLE;
    case SERIALIZABLE:
        return Connection.TRANSACTION_SERIALIZABLE;
    }
}

From source file:org.apache.jena.jdbc.remote.connections.RemoteEndpointConnection.java

/**
 * Creates a new remote connection//from   ww w.  j  a  v a2  s. c  o  m
 * 
 * @param queryEndpoint
 *            SPARQL Query Endpoint
 * @param updateEndpoint
 *            SPARQL Update Endpoint
 * @param defaultGraphUris
 *            Default Graph URIs for SPARQL queries
 * @param namedGraphUris
 *            Named Graph URIs for SPARQL queries
 * @param usingGraphUris
 *            Default Graph URIs for SPARQL updates
 * @param usingNamedGraphUris
 *            Named Graph URIs for SPARQL updates
 * @param client
 *            HTTP client
 * @param holdability
 *            Result Set holdability
 * @param compatibilityLevel
 *            JDBC compatibility level, see {@link JdbcCompatibility}
 * @param selectResultsType
 *            Results Type to request for {@code SELECT} queries against the
 *            remote endpoint
 * @param modelResultsType
 *            Results Type to request for {@code CONSTRUCT} and
 *            {@code DESCRIBE} queries against the remote endpoint
 * @throws SQLException
 *             Thrown if there is a problem creating the connection
 */
public RemoteEndpointConnection(String queryEndpoint, String updateEndpoint, List<String> defaultGraphUris,
        List<String> namedGraphUris, List<String> usingGraphUris, List<String> usingNamedGraphUris,
        HttpClient client, int holdability, int compatibilityLevel, String selectResultsType,
        String modelResultsType) throws SQLException {
    super(holdability, true, Connection.TRANSACTION_NONE, compatibilityLevel);
    if (queryEndpoint == null && updateEndpoint == null)
        throw new SQLException("Must specify one/both of a query endpoint and update endpoint");
    this.queryService = queryEndpoint;
    this.updateService = updateEndpoint;
    this.readonly = this.updateService == null;
    this.defaultGraphUris = defaultGraphUris;
    this.namedGraphUris = namedGraphUris;
    this.usingGraphUris = usingGraphUris;
    this.usingNamedGraphUris = usingNamedGraphUris;
    this.client = client;
    this.metadata = new RemoteEndpointMetadata(this);
    this.selectResultsType = selectResultsType;
    this.modelResultsType = modelResultsType;
}

From source file:org.wso2.carbon.datasource.ui.DataSourceManagementHelper.java

/**
 * Factory method to create a DataSourceInformation from HttpServletResuet
 *
 * @param request HttpServletRequest instance
 * @return A DataSourceInformation/*w  w w. ja  v a  2 s.  c o  m*/
 * @throws javax.servlet.ServletException Throws for any error during DataSourceInformation creation
 */
public static DataSourceInformation createDataSourceInformation(HttpServletRequest request)
        throws ServletException {

    ResourceBundle bundle = ResourceBundle.getBundle("org.wso2.carbon.datasource.ui.i18n.Resources",
            request.getLocale());
    String alias = request.getParameter("alias");
    if (alias == null || "".equals(alias)) {
        alias = request.getParameter("alias_hidden");
        if (alias == null || "".equals(alias)) {
            handleException(bundle.getString("ds.name.cannotfound.msg"));
        }
    }

    String diver = request.getParameter("driver");
    if (diver == null || "".equals(diver)) {
        handleException(bundle.getString("ds.driver.cannotfound.msg"));
    }

    String url = request.getParameter("url");
    if (url == null || "".equals(url)) {
        handleException(bundle.getString("ds.url.cannotfound.msg"));
    }
    DataSourceInformation dataSourceInformation = new DataSourceInformation();

    dataSourceInformation.setAlias(alias.trim());
    dataSourceInformation.setDatasourceName(alias.trim());
    dataSourceInformation.setDriver(diver.trim());
    dataSourceInformation.setUrl(url.trim());

    String user = request.getParameter("user");
    if (user != null && !"".equals(user)) {
        SecretInformation secretInfo;
        if (dataSourceInformation.getSecretInformation() == null) {
            secretInfo = new SecretInformation();
        } else {
            secretInfo = dataSourceInformation.getSecretInformation();
        }
        secretInfo.setUser(user.trim());
        dataSourceInformation.setSecretInformation(secretInfo);
    }
    String password = request.getParameter("password");
    if (password != null && !"".equals(password)) {
        SecretInformation secretInfo;
        if (dataSourceInformation.getSecretInformation() == null) {
            secretInfo = new SecretInformation();
        } else {
            secretInfo = dataSourceInformation.getSecretInformation();
        }
        secretInfo.setAliasSecret(password.trim());
        dataSourceInformation.setSecretInformation(secretInfo);
    }
    String dstype = request.getParameter("dstype");
    if ("peruserds".equals(dstype)) {
        dataSourceInformation.setType("PerUserPoolDataSource");
    }
    //        String dsName = request.getParameter("dsName");
    //        if (dsName != null && !"".equals(dsName)) {
    //            dataSourceInformation.setDatasourceName(dsName.trim());
    //        }
    String dsrepotype = request.getParameter("dsrepotype");
    if ("JNDI".equals(dsrepotype)) {
        dataSourceInformation.setRepositoryType(DataSourceConstants.PROP_REGISTRY_JNDI);
        StringBuffer buffer = new StringBuffer();
        buffer.append(DataSourceConstants.PROP_SYNAPSE_PREFIX_DS);
        buffer.append(DataSourceConstants.DOT_STRING);

        buffer.append(alias.trim());
        buffer.append(DataSourceConstants.DOT_STRING);
        // The prefix for root level jndiProperties
        String rootPrefix = buffer.toString();
        // setting naming provider
        Properties jndiEvn = new Properties();

        String icFactory = request.getParameter("icFactory");
        String providerUrl = request.getParameter("providerUrl");
        String providerPort = request.getParameter("providerPort");
        String providerType = request.getParameter("providerType");
        if (icFactory != null && !"".equals(icFactory)) {
            jndiEvn.setProperty(rootPrefix + DataSourceConstants.PROP_IC_FACTORY, icFactory.trim());
        }
        if ("url".equals(providerType)) {
            if (providerUrl != null && !"".equals(providerUrl)) {
                jndiEvn.setProperty(rootPrefix + DataSourceConstants.PROP_PROVIDER_URL, providerUrl.trim());
            }
        } else {
            if (providerPort != null && !"".equals(providerPort)) {
                jndiEvn.setProperty(rootPrefix + DataSourceConstants.PROP_PROVIDER_PORT, providerPort.trim());
            }
        }
        dataSourceInformation.setProperties(jndiEvn);
    }
    String autocommit = request.getParameter("autocommit");
    if (autocommit != null && !"".equals(autocommit)) {
        dataSourceInformation.setDefaultAutoCommit(Boolean.parseBoolean(autocommit.trim()));
    }
    String isolation = request.getParameter("isolation");
    if (isolation != null && !"".equals(isolation)) {
        if ("TRANSACTION_NONE".equals(isolation)) {
            dataSourceInformation.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        } else if ("TRANSACTION_READ_COMMITTED".equals(isolation.trim())) {
            dataSourceInformation.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("TRANSACTION_READ_UNCOMMITTED".equals(isolation.trim())) {
            dataSourceInformation.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("TRANSACTION_REPEATABLE_READ".equals(isolation.trim())) {
            dataSourceInformation.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("TRANSACTION_SERIALIZABLE".equals(isolation.trim())) {
            dataSourceInformation.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        }
    }
    String maxActive = request.getParameter("maxActive");
    if (maxActive != null && !"".equals(maxActive) && !maxActive.contains("int")) {
        try {
            dataSourceInformation.setMaxActive(Integer.parseInt(maxActive.trim()));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.maxActive"));
        }
    }
    String maxIdle = request.getParameter("maxIdle");
    if (maxIdle != null && !"".equals(maxIdle) && !maxIdle.contains("int")) {
        try {
            dataSourceInformation.setMaxIdle(Integer.parseInt(maxIdle.trim()));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.maxidle"));
        }
    }
    String maxopenstatements = request.getParameter("maxopenstatements");
    if (maxopenstatements != null && !"".equals(maxopenstatements) && !maxopenstatements.contains("int")) {
        try {
            dataSourceInformation.setMaxOpenPreparedStatements(Integer.parseInt(maxopenstatements.trim()));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.MaxOpenStatements"));
        }
    }
    String maxWait = request.getParameter("maxWait");
    if (maxWait != null && !"".equals(maxWait) && !maxWait.contains("long")) {
        try {
            dataSourceInformation.setMaxWait(Long.parseLong(maxWait.trim()));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.MaxWait"));
        }
    }
    String minIdle = request.getParameter("minIdle");
    if (minIdle != null && !"".equals(minIdle) && !minIdle.contains("int")) {
        try {
            dataSourceInformation.setMinIdle(Integer.parseInt(minIdle.trim()));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.MinIdle"));
        }
    }
    String initialsize = request.getParameter("initialsize");
    if (initialsize != null && !"".equals(initialsize) && !initialsize.contains("int")) {
        try {
            dataSourceInformation.setInitialSize(Integer.parseInt(initialsize.trim()));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.Initialsize"));
        }
    }
    String poolstatements = request.getParameter("poolstatements");
    if (poolstatements != null && !"".equals(poolstatements)) {
        dataSourceInformation.setPoolPreparedStatements(Boolean.parseBoolean(poolstatements.trim()));
    }
    String removeAbandoned = request.getParameter("removeAbandoned");
    if (removeAbandoned != null && !"".equals(removeAbandoned)) {
        dataSourceInformation.setRemoveAbandoned(Boolean.parseBoolean(removeAbandoned));
    }
    String removeAbandonedTimeout = request.getParameter("removeAbandonedTimeout");
    if (removeAbandonedTimeout != null && !"".equals(removeAbandonedTimeout)) {
        try {
            dataSourceInformation.setRemoveAbandonedTimeout(Integer.parseInt(removeAbandonedTimeout));
        } catch (NumberFormatException e) {
            handleException(bundle.getString("invalid.remove.abandoned.timeout"));
        }
    }
    String logAbandoned = request.getParameter("logAbandoned");
    if (logAbandoned != null && !"".equals(logAbandoned)) {
        dataSourceInformation.setLogAbandoned(Boolean.parseBoolean(logAbandoned));
    }
    String testonborrow = request.getParameter("testonborrow");
    if (testonborrow != null && !"".equals(testonborrow)) {
        dataSourceInformation.setTestOnBorrow(Boolean.parseBoolean(testonborrow.trim()));
    }
    String testwhileidle = request.getParameter("testwhileidle");
    if (testwhileidle != null && !"".equals(testwhileidle)) {
        dataSourceInformation.setTestWhileIdle(Boolean.parseBoolean(testwhileidle.trim()));
    }
    String validationquery = request.getParameter("validationquery");
    if (validationquery != null && !"".equals(validationquery)) {
        dataSourceInformation.setValidationQuery(validationquery.trim());
    }

    return dataSourceInformation;
}

From source file:com.amazon.carbonado.repo.jdbc.LoggingConnection.java

public void setTransactionIsolation(int level) throws SQLException {
    String levelStr;//from w w  w .  j  a  v  a2  s .c om
    switch (level) {
    default:
        levelStr = String.valueOf(level);
        break;
    case Connection.TRANSACTION_NONE:
        levelStr = "TRANSACTION_NONE";
        break;
    case Connection.TRANSACTION_READ_UNCOMMITTED:
        levelStr = "TRANSACTION_READ_UNCOMMITTED";
        break;
    case Connection.TRANSACTION_READ_COMMITTED:
        levelStr = "TRANSACTION_READ_COMMITTED";
        break;
    case Connection.TRANSACTION_REPEATABLE_READ:
        levelStr = "TRANSACTION_REPEATABLE_READ";
        break;
    case Connection.TRANSACTION_SERIALIZABLE:
        levelStr = "TRANSACTION_SERIALIZABLE";
        break;
    }

    mLog.debug("Connection.setTransactionIsolation(" + levelStr + ')');
    mCon.setTransactionIsolation(level);
}

From source file:org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.java

/**
 * Constructor./*from   w  ww  . j  a va2  s .  c o m*/
 *
 * @param derivations whether to apply product derivations
 * @param loadGlobals whether to attempt to load the global properties
 */
public JDBCConfigurationImpl(boolean derivations, boolean loadGlobals) {
    super(false, false);
    String[] aliases;

    schema = addString("jdbc.Schema");
    schemas = addStringList("jdbc.Schemas");

    transactionIsolation = addInt("jdbc.TransactionIsolation");
    aliases = new String[] { "default", String.valueOf(-1), "none", String.valueOf(Connection.TRANSACTION_NONE),
            "read-committed", String.valueOf(Connection.TRANSACTION_READ_COMMITTED), "read-uncommitted",
            String.valueOf(Connection.TRANSACTION_READ_UNCOMMITTED), "repeatable-read",
            String.valueOf(Connection.TRANSACTION_REPEATABLE_READ), "serializable",
            String.valueOf(Connection.TRANSACTION_SERIALIZABLE) };
    transactionIsolation.setAliases(aliases);
    transactionIsolation.setDefault(aliases[0]);
    transactionIsolation.set(-1);
    transactionIsolation.setAliasListComprehensive(true);

    resultSetType = addInt("jdbc.ResultSetType");
    aliases = new String[] { "forward-only", String.valueOf(ResultSet.TYPE_FORWARD_ONLY), "scroll-sensitive",
            String.valueOf(ResultSet.TYPE_SCROLL_SENSITIVE), "scroll-insensitive",
            String.valueOf(ResultSet.TYPE_SCROLL_INSENSITIVE), };
    resultSetType.setAliases(aliases);
    resultSetType.setDefault(aliases[0]);
    resultSetType.set(ResultSet.TYPE_FORWARD_ONLY);
    resultSetType.setAliasListComprehensive(true);

    fetchDirection = addInt("jdbc.FetchDirection");
    aliases = new String[] { "forward", String.valueOf(ResultSet.FETCH_FORWARD), "reverse",
            String.valueOf(ResultSet.FETCH_REVERSE), "unknown", String.valueOf(ResultSet.FETCH_UNKNOWN), };
    fetchDirection.setAliases(aliases);
    fetchDirection.setDefault(aliases[0]);
    fetchDirection.set(ResultSet.FETCH_FORWARD);
    fetchDirection.setAliasListComprehensive(true);

    eagerFetchMode = new FetchModeValue("jdbc.EagerFetchMode");
    eagerFetchMode.setDefault(FetchModeValue.EAGER_PARALLEL);
    eagerFetchMode.set(EagerFetchModes.EAGER_PARALLEL);
    addValue(eagerFetchMode);

    subclassFetchMode = new FetchModeValue("jdbc.SubclassFetchMode");
    subclassFetchMode.setDefault(FetchModeValue.EAGER_JOIN);
    subclassFetchMode.set(EagerFetchModes.EAGER_JOIN);
    addValue(subclassFetchMode);

    lrsSize = addInt("jdbc.LRSSize");
    aliases = new String[] { "query", String.valueOf(LRSSizes.SIZE_QUERY), "unknown",
            String.valueOf(LRSSizes.SIZE_UNKNOWN), "last", String.valueOf(LRSSizes.SIZE_LAST), };
    lrsSize.setAliases(aliases);
    lrsSize.setDefault(aliases[0]);
    lrsSize.set(LRSSizes.SIZE_QUERY);
    lrsSize.setAliasListComprehensive(true);

    synchronizeMappings = addString("jdbc.SynchronizeMappings");
    aliases = new String[] { "false", null };
    synchronizeMappings.setAliases(aliases);
    synchronizeMappings.setDefault(aliases[0]);

    jdbcListenerPlugins = addPluginList("jdbc.JDBCListeners");
    jdbcListenerPlugins.setInstantiatingGetter("getJDBCListenerInstances");

    connectionDecoratorPlugins = addPluginList("jdbc.ConnectionDecorators");
    connectionDecoratorPlugins.setInstantiatingGetter("getConnectionDecoratorInstances");

    dbdictionaryPlugin = addPlugin("jdbc.DBDictionary", true);
    aliases = new String[] { "access", "org.apache.openjpa.jdbc.sql.AccessDictionary", "db2",
            "org.apache.openjpa.jdbc.sql.DB2Dictionary", "derby", "org.apache.openjpa.jdbc.sql.DerbyDictionary",
            "empress", "org.apache.openjpa.jdbc.sql.EmpressDictionary", "foxpro",
            "org.apache.openjpa.jdbc.sql.FoxProDictionary", "h2", "org.apache.openjpa.jdbc.sql.H2Dictionary",
            "hsql", "org.apache.openjpa.jdbc.sql.HSQLDictionary", "informix",
            "org.apache.openjpa.jdbc.sql.InformixDictionary", "ingres",
            "org.apache.openjpa.jdbc.sql.IngresDictionary", "jdatastore",
            "org.apache.openjpa.jdbc.sql.JDataStoreDictionary", "mysql",
            "org.apache.openjpa.jdbc.sql.MySQLDictionary", "oracle",
            "org.apache.openjpa.jdbc.sql.OracleDictionary", "pointbase",
            "org.apache.openjpa.jdbc.sql.PointbaseDictionary", "postgres",
            "org.apache.openjpa.jdbc.sql.PostgresDictionary", "soliddb",
            "org.apache.openjpa.jdbc.sql.SolidDBDictionary", "sqlserver",
            "org.apache.openjpa.jdbc.sql.SQLServerDictionary", "sybase",
            "org.apache.openjpa.jdbc.sql.SybaseDictionary", "maxdb",
            MaxDBDictionary.class.getCanonicalName(), };
    dbdictionaryPlugin.setAliases(aliases);
    dbdictionaryPlugin.setInstantiatingGetter("getDBDictionaryInstance");

    updateManagerPlugin = addPlugin("jdbc.UpdateManager", true);
    aliases = new String[] { "default", BatchingConstraintUpdateManager.class.getName(), "operation-order",
            "org.apache.openjpa.jdbc.kernel.OperationOrderUpdateManager", "constraint",
            "org.apache.openjpa.jdbc.kernel.ConstraintUpdateManager", "batching-constraint",
            BatchingConstraintUpdateManager.class.getName(), "batching-operation-order",
            BatchingOperationOrderUpdateManager.class.getName(), };
    updateManagerPlugin.setAliases(aliases);
    updateManagerPlugin.setDefault(aliases[0]);
    updateManagerPlugin.setString(aliases[0]);
    updateManagerPlugin.setInstantiatingGetter("getUpdateManagerInstance");

    driverDataSourcePlugin = addPlugin("jdbc.DriverDataSource", false);
    aliases = new String[] { "auto", "org.apache.openjpa.jdbc.schema.AutoDriverDataSource", "simple",
            "org.apache.openjpa.jdbc.schema.SimpleDriverDataSource", "dbcp",
            "org.apache.openjpa.jdbc.schema.DBCPDriverDataSource", };
    driverDataSourcePlugin.setAliases(aliases);
    driverDataSourcePlugin.setDefault(aliases[0]);
    driverDataSourcePlugin.setString(aliases[0]);

    schemaFactoryPlugin = addPlugin("jdbc.SchemaFactory", true);
    aliases = new String[] { "dynamic", "org.apache.openjpa.jdbc.schema.DynamicSchemaFactory", "native",
            "org.apache.openjpa.jdbc.schema.LazySchemaFactory", "file",
            "org.apache.openjpa.jdbc.schema.FileSchemaFactory", "table",
            "org.apache.openjpa.jdbc.schema.TableSchemaFactory",
            // deprecated alias
            "db", "org.apache.openjpa.jdbc.schema.TableSchemaFactory", };
    schemaFactoryPlugin.setAliases(aliases);
    schemaFactoryPlugin.setDefault(aliases[0]);
    schemaFactoryPlugin.setString(aliases[0]);
    schemaFactoryPlugin.setInstantiatingGetter("getSchemaFactoryInstance");

    sqlFactoryPlugin = addPlugin("jdbc.SQLFactory", true);
    aliases = new String[] { "default", "org.apache.openjpa.jdbc.sql.SQLFactoryImpl", };
    sqlFactoryPlugin.setAliases(aliases);
    sqlFactoryPlugin.setDefault(aliases[0]);
    sqlFactoryPlugin.setString(aliases[0]);
    sqlFactoryPlugin.setInstantiatingGetter("getSQLFactoryInstance");

    mappingFactoryPlugin = new MappingFactoryValue("jdbc.MappingFactory");
    addValue(mappingFactoryPlugin);

    mappingDefaultsPlugin = addPlugin("jdbc.MappingDefaults", true);
    aliases = new String[] { "default", "org.apache.openjpa.jdbc.meta.MappingDefaultsImpl", };
    mappingDefaultsPlugin.setAliases(aliases);
    mappingDefaultsPlugin.setDefault(aliases[0]);
    mappingDefaultsPlugin.setString(aliases[0]);
    mappingDefaultsPlugin.setInstantiatingGetter("getMappingDefaultsInstance");

    // set up broker factory defaults
    brokerFactoryPlugin.setAlias("jdbc", JDBCBrokerFactory.class.getName());
    brokerFactoryPlugin.setDefault("jdbc");
    brokerFactoryPlugin.setString("jdbc");

    // set new default for mapping repos
    metaRepositoryPlugin.setAlias("default", "org.apache.openjpa.jdbc.meta.MappingRepository");
    metaRepositoryPlugin.setDefault("default");
    metaRepositoryPlugin.setString("default");

    // set new default for lock manager
    lockManagerPlugin.setAlias("pessimistic", PessimisticLockManager.class.getName());
    lockManagerPlugin.setDefault("pessimistic");
    lockManagerPlugin.setString("pessimistic");

    // native savepoint manager options
    savepointManagerPlugin.setAlias("jdbc", "org.apache.openjpa.jdbc.kernel.JDBC3SavepointManager");

    // set new aliases and defaults for sequence
    seqPlugin.setAliases(JDBCSeqValue.ALIASES);
    seqPlugin.setDefault(JDBCSeqValue.ALIASES[0]);
    seqPlugin.setString(JDBCSeqValue.ALIASES[0]);

    // This plug-in is declared in superclass but defined here
    // because PreparedQueryCache is currently available for JDBC
    // backend only
    preparedQueryCachePlugin = addPlugin("jdbc.QuerySQLCache", true);
    aliases = new String[] { "true", "org.apache.openjpa.jdbc.kernel.PreparedQueryCacheImpl", "false", null };
    preparedQueryCachePlugin.setAliases(aliases);
    preparedQueryCachePlugin.setAliasListComprehensive(true);
    preparedQueryCachePlugin.setDefault(aliases[0]);
    preparedQueryCachePlugin.setClassName(aliases[1]);
    preparedQueryCachePlugin.setDynamic(true);
    preparedQueryCachePlugin.setInstantiatingGetter("getQuerySQLCacheInstance");

    finderCachePlugin = addPlugin("jdbc.FinderCache", true);
    aliases = new String[] { "true", "org.apache.openjpa.jdbc.kernel.FinderCacheImpl", "false", null };
    finderCachePlugin.setAliases(aliases);
    finderCachePlugin.setAliasListComprehensive(true);
    finderCachePlugin.setDefault(aliases[0]);
    finderCachePlugin.setClassName(aliases[1]);
    finderCachePlugin.setDynamic(true);
    finderCachePlugin.setInstantiatingGetter("getFinderCacheInstance");

    identifierUtilPlugin = addPlugin("jdbc.IdentifierUtil", true);
    aliases = new String[] { "default", "org.apache.openjpa.jdbc.identifier.DBIdentifierUtilImpl" };
    identifierUtilPlugin.setAliases(aliases);
    identifierUtilPlugin.setDefault(aliases[0]);
    identifierUtilPlugin.setString(aliases[0]);
    identifierUtilPlugin.setInstantiatingGetter("getIdentifierUtilInstance");

    // this static initializer is to get past a weird
    // ClassCircularityError that happens only under IBM's
    // JDK 1.3.1 on Linux from within the JRun ClassLoader;
    // while exact causes are unknown, it is almost certainly
    // a bug in JRun, and we can get around it by forcing
    // Instruction.class to be loaded and initialized
    // before TypedInstruction.class
    try {
        serp.bytecode.lowlevel.Entry.class.getName();
    } catch (Throwable t) {
    }
    try {
        serp.bytecode.Instruction.class.getName();
    } catch (Throwable t) {
    }

    supportedOptions().add(OPTION_QUERY_SQL);
    supportedOptions().add(OPTION_JDBC_CONNECTION);
    supportedOptions().remove(OPTION_VALUE_INCREMENT);
    supportedOptions().remove(OPTION_NULL_CONTAINER);

    if (derivations)
        ProductDerivations.beforeConfigurationLoad(this);
    if (loadGlobals)
        loadGlobals();
}

From source file:org.noerp.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    ManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }//from  w w w  .j  a va 2 s.  c om
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool pool = new GenericObjectPool(factory, poolConfig);
    factory.setPool(pool);

    mds = new ManagedDataSource(pool, xacf.getTransactionRegistry());
    //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.apache.ofbiz.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    DebugManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/* w  ww  .  j  av  a  2 s  . c o m*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    factory.setRollbackOnReturn(false);
    factory.setEnableAutoCommitOnReturn(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
    factory.setPool(pool);

    mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}