Example usage for java.sql Connection TRANSACTION_READ_COMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_COMMITTED

Introduction

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

Prototype

int TRANSACTION_READ_COMMITTED

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

Click Source Link

Document

A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

Usage

From source file:sf.net.experimaestro.scheduler.Scheduler.java

/**
 * Initialise the task manager/*from  w w  w  .  j a v  a  2s.c o  m*/
 *
 * @param baseDirectory The directory where the XPM database will be stored
 */
public Scheduler(File baseDirectory) throws IOException {
    if (INSTANCE != null) {
        throw new XPMRuntimeException("Only one scheduler instance should be created");
    }

    INSTANCE = this;

    // Initialise the database
    LOGGER.info("Initialising database in directory %s", baseDirectory);
    HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.connection.url",
            format("jdbc:hsqldb:file:%s/xpm;shutdown=true;hsqldb.tx=mvcc", baseDirectory));
    properties.put("hibernate.connection.username", "");
    properties.put("hibernate.connection.password", "");

    /* From HSQLDB http://hsqldb.org/doc/guide/sessions-chapt.html#snc_tx_mvcc
            
    In MVCC mode
    - locks are at the row level
    - no shared (i.e. read) locks
    - in TRANSACTION_READ_COMMITTED mode: if a session wants to read/write a row that was written by another one => wait
    - in TRANSACTION_REPEATABLE_READ: if a session wants to write the same row than another one => exception
    */
    properties.put("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_COMMITTED));

    ArrayList<Class<?>> loadedClasses = new ArrayList<>();
    ServiceLoader<PersistentClassesAdder> services = ServiceLoader.load(PersistentClassesAdder.class);
    for (PersistentClassesAdder service : services) {
        service.add(loadedClasses);
    }

    properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES, loadedClasses);

    entityManagerFactory = Persistence.createEntityManagerFactory("net.bpiwowar.experimaestro", properties);

    // Add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(Scheduler.this::close));

    // Create reused criteria queries
    CriteriaBuilder builder = entityManagerFactory.getCriteriaBuilder();
    readyJobsQuery = builder.createQuery(Long.TYPE);
    Root<Job> root = readyJobsQuery.from(Job.class);
    readyJobsQuery.orderBy(builder.desc(root.get("priority")));
    readyJobsQuery.where(root.get("state").in(ResourceState.READY));
    readyJobsQuery.select(root.get(Resource_.resourceID));

    // Initialise the running resources so that they can retrieve their state
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    TypedQuery<Resource> query = entityManager.createQuery("from resources r where r.state = :state",
            Resource.class);
    query.setParameter("state", ResourceState.RUNNING);
    for (Resource resource : query.getResultList()) {
        LOGGER.info("Job %s is running: starting a watcher", resource);
        Job job = (Job) resource;
        if (job.process != null) {
            job.process.init(job);
        } else {
            Transaction.run(em -> {
                // Set the job state to ERROR (and update the state in case it was finished)
                // The job should take care of setting a new process if the job is still running
                Job _job = em.find(Job.class, job.getId());
                _job.setState(ResourceState.ERROR);
                _job.updateStatus();
                LOGGER.error("No process attached to a running job. New status is: %s", _job.getState());
            });
        }
        resource.updateStatus();
    }

    // Start the thread that notify dependencies
    LOGGER.info("Starting the notifier thread");
    notifier = new Notifier();
    notifier.start();
    runningThreadsCounter.add();

    // Start the thread that notify dependencies
    LOGGER.info("Starting the messager thread");
    messengerThread = new MessengerThread();
    messengerThread.start();
    runningThreadsCounter.add();

    // Start the thread that start the jobs
    LOGGER.info("Starting the job runner thread");
    readyJobSemaphore.setValue(true);
    runner = new JobRunner("JobRunner");
    runner.start();
    runningThreadsCounter.add();

    executorService = Executors.newFixedThreadPool(1);

    LOGGER.info("Done - ready status work now");
}

From source file:org.wso2.carbon.identity.thrift.authentication.internal.persistance.ThriftAuthenticationJDBCPersistenceManager.java

/**
 * Returns an database connection for Identity data source.
 *
 * @return Database connection//from   w  w w.j  a v a 2 s  . co m
 * @throws AuthenticationException Exception occurred when getting the data source.
 */
public Connection getDBConnection() throws AuthenticationException {
    try {
        Connection dbConnection = dataSource.getConnection();
        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return dbConnection;
    } catch (SQLException e) {
        String errMsg = "Error when getting a database connection object from the Thrift Authentication data source.";
        log.error(errMsg, e);
        throw new AuthenticationException(errMsg);
    }
}

From source file:org.wso2.carbon.identity.application.common.persistence.JDBCPersistenceManager.java

/**
 * Returns a database connection for Identity Application Management data store.
 *
 * @return Database connection//from   w w w .  ja v a  2s  .  c o m
 * @throws IdentityApplicationManagementException Error when getting DB connection
 *         on the Identity Provider Management data source
 */
public Connection getDBConnection() throws IdentityApplicationManagementException {

    Connection dbConnection = null;
    try {
        dbConnection = dataSource.getConnection();
        if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        dbConnection.setAutoCommit(false);
        return dbConnection;
    } catch (SQLException e) {
        String errorMsg = "Error occurred while trying to get a database connection on "
                + "Identity Application Management data source";
        log.error(errorMsg, e);
        if (dbConnection != null) {
            IdentityApplicationManagementUtil.closeConnection(dbConnection);
        }
        throw new IdentityApplicationManagementException(errorMsg);
    }
}

From source file:org.rimudb.C3P0PoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-c3p0-2-jdbcconfig.xml", true);

    cdb.connect("dbid-1");
    Database db = cdb.getDatabase("dbid-1");
    Connection conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();//from  w  w  w  .  j a  va2  s.  c o  m

    cdb.connect("dbid-2");
    db = cdb.getDatabase("dbid-2");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-3");
    db = cdb.getDatabase("dbid-3");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-4");
    db = cdb.getDatabase("dbid-4");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.disconnectAllNoException();
}

From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java

private SQLPersistenceManagerImpl() {
    loadUsernamePassword();/*from w w w  .j a v a2s . c o  m*/
    constructDatabaseURL();

    // define transaction isolation
    if ("TRANSACTION_READ_COMMITTED".equalsIgnoreCase(
            RegistryProperties.getInstance().getProperty("omar.persistence.rdb.transactionIsolation"))) {
        transactionIsolation = Connection.TRANSACTION_READ_COMMITTED;
    } else {
        transactionIsolation = Connection.TRANSACTION_READ_UNCOMMITTED;
    }

    useConnectionPool = Boolean.valueOf(
            RegistryProperties.getInstance().getProperty("omar.persistence.rdb.useConnectionPooling", "true"))
            .booleanValue();
    skipReferenceCheckOnRemove = Boolean.valueOf(RegistryProperties.getInstance()
            .getProperty("omar.persistence.rdb.skipReferenceCheckOnRemove", "false")).booleanValue();
    dumpStackOnQuery = Boolean.valueOf(
            RegistryProperties.getInstance().getProperty("omar.persistence.rdb.dumpStackOnQuery", "false"))
            .booleanValue();
    boolean debugConnectionPool = Boolean
            .valueOf(RegistryProperties.getInstance().getProperty("omar.persistence.rdb.pool.debug", "false"))
            .booleanValue();

    //Create JNDI context
    if (useConnectionPool) {
        if (!debugConnectionPool) {
            // Use Container's connection pooling
            String omarName = RegistryProperties.getInstance().getProperty("omar.name", "omar");
            String envName = "java:comp/env";
            String dataSourceName = "jdbc/" + omarName + "-registry";
            Context ctx = null;

            try {
                ctx = new InitialContext();
                if (null == ctx) {
                    log.info(ServerResourceBundle.getInstance().getString("message.UnableToGetInitialContext"));
                }
            } catch (NamingException e) {
                log.info(ServerResourceBundle.getInstance().getString("message.UnableToGetInitialContext"), e);
                ctx = null;
            }

            /* HIEOS/BHT: DISABLED
            if (null != ctx) {
            try {
            ctx = (Context)ctx.lookup(envName);
            if (null == ctx) {
            log.info(ServerResourceBundle.getInstance().
            getString("message.UnableToGetJNDIContextForDataSource",
            new Object[]{envName}));
            }
            } catch (NamingException e) {
            log.info(ServerResourceBundle.getInstance().
            getString("message.UnableToGetJNDIContextForDataSource",
            new Object[]{envName}), e);
            ctx = null;
            }
            }
             */

            if (null != ctx) {
                try {
                    ds = (DataSource) ctx.lookup(dataSourceName);
                    if (null == ds) {
                        log.info(ServerResourceBundle.getInstance().getString(
                                "message.UnableToGetJNDIContextForDataSource",
                                new Object[] { envName + "/" + dataSourceName }));
                    }
                } catch (NamingException e) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.UnableToGetJNDIContextForDataSource",
                            new Object[] { envName + "/" + dataSourceName }), e);
                    ds = null;
                }
            }

            if (null != ds) {
                // Create a test connection to make sure all is well with DataSource
                Connection connection = null;
                try {
                    connection = ds.getConnection();
                } catch (Exception e) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.UnableToCreateTestConnectionForDataSource",
                            new Object[] { envName + "/" + dataSourceName }), e);
                    ds = null;
                } finally {
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (Exception e1) {
                            //Do nothing.
                        }
                    }
                }
            }
        }

        if (ds == null) {
            // No DataSource available so create our own ConnectionPool
            loadDatabaseDriver();
            createConnectionPool();
        }
    } else {
        loadDatabaseDriver();
    }
}

From source file:org.rimudb.DBCPPoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-dbcp-2-jdbcconfig.xml", true);

    cdb.connect("dbid-1");
    Database db = cdb.getDatabase("dbid-1");
    Connection conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();/* w w w . j av a  2 s. co  m*/

    cdb.connect("dbid-2");
    db = cdb.getDatabase("dbid-2");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-3");
    db = cdb.getDatabase("dbid-3");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-4");
    db = cdb.getDatabase("dbid-4");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.disconnectAllNoException();
}

From source file:org.wso2.carbon.appfactory.core.util.AppFactoryDBUtil.java

public static synchronized Connection getConnection() throws SQLException {
    Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);/*from   w w  w.  jav  a2  s .  co m*/
    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return connection;
}

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

public int[] count(Query[] queries) {
    if (queries == null)
        throw new IllegalArgumentException("expected non-null 'queries' argument");
    Connection con = null;//from www .j a  va 2s  . c o m
    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 multi count query");
            con.setAutoCommit(false);
        }
        // TODO: make transaction isolation configurable
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        default:
        }
        if (log.isDebugEnabled())
            log.debug("using transaction isolation level " + con.getTransactionIsolation()
                    + " for multi 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);
    int[] counts = new int[queries.length];
    try {
        for (int i = 0; i < queries.length; i++)
            counts[i] = dispatcher.count(queries[i]);
        return counts;
    } 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.wso2.carbon.datasource.ui.DataSourceManagementHelper.java

/**
 * Factory method to create a DataSourceInformation from HttpServletResuet
 *
 * @param request HttpServletRequest instance
 * @return A DataSourceInformation/* ww w. java  2  s . co 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: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());
    }/*w ww .  ja  v 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);
    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());
}