Example usage for java.sql Connection isValid

List of usage examples for java.sql Connection isValid

Introduction

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

Prototype

boolean isValid(int timeout) throws SQLException;

Source Link

Document

Returns true if the connection has not been closed and is still valid.

Usage

From source file:com.mnt.base.das.DBFactory.java

private Connection retrieveConnection() {

    Connection connection = null;

    while (connPool.size() > 0 || usingConnPool.size() >= maxPoolSize) {
        connection = connPool.poll();/* ww w .j  a  v a 2  s .co  m*/

        if (connection != null) {
            try {
                if (connection.isValid(0)) {

                    usingConnPool.add(connection);

                    return connection;
                }
            } catch (SQLException e) {
                try {
                    connection.close();
                } catch (SQLException e1) {
                    // ignore
                }
            }
        } else {
            Iterator<Connection> conns = usingConnPool.iterator();
            Connection conn;
            while (conns.hasNext()) {
                conn = conns.next();

                try {
                    if (conn.isClosed()) {
                        usingConnPool.remove(conn);
                    }
                } catch (SQLException e) {

                    try {
                        conn.close();
                    } catch (SQLException e1) {
                        // skip it
                    }

                    usingConnPool.remove(conn);
                }

                if (usingConnPool.size() < maxPoolSize) {
                    break;
                }
            }

            if (usingConnPool.size() >= maxPoolSize) {
                synchronized (connPool) {
                    try {
                        connPool.wait(1000);
                    } catch (InterruptedException e) {
                        log.error("error while wait for the connection.", e);
                    }
                }
            }
        }
    }

    synchronized (connCreationLock) {
        if (usingConnPool.size() < maxPoolSize) {
            try {
                connection = DriverManager.getConnection(prop.getProperty(DB_URL), prop.getProperty(DB_USER),
                        prop.getProperty(DB_PASSWORD));

                usingConnPool.add(connection);
            } catch (SQLException e) {
                log.error("Error when construct the db connection.", e);
                throw new RuntimeException("Error when construct the db connection.", e);
            }
        }
    }

    if (connection == null) {
        synchronized (connPool) {
            try {
                connPool.wait(1000);
            } catch (InterruptedException e) {
                log.error("error while wait for the connection.", e);
            }
        }

        return getConnection();
    }

    return connection;
}

From source file:org.kitodo.data.database.persistence.apache.MySQLHelper.java

/**
 * Get Connection./*from  w  w  w  . ja v a  2 s .  co m*/
 *
 * @return connection
 */
public Connection getConnection() throws SQLException {

    Connection connection = this.cm.getDataSource().getConnection();

    if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) {
        return connection;
    }

    connection.close();

    for (int i = 0; i < MAX_TRIES_NEW_CONNECTION; i++) {

        if (logger.isEnabledFor(Level.WARN)) {
            logger.warn("Connection failed: Trying to get new connection. Attempt:" + i);
        }

        connection = this.cm.getDataSource().getConnection();

        if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) {
            return connection;
        }

        connection.close();
    }

    logger.warn("Connection failed: Trying to get a connection from a new ConnectionManager");
    SqlConfiguration config = SqlConfiguration.getInstance();
    this.cm = new ConnectionManager(config);
    connection = this.cm.getDataSource().getConnection();

    if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) {
        return connection;
    }

    logger.error("Connection failed!");

    return connection;
}

From source file:com.googlecode.fascinator.portal.services.impl.DatabaseServicesImpl.java

private java.sql.Connection connection(String database, boolean create) throws SQLException {

    // Has it already been instantiated this session?
    Connection thisDatabase = null;
    if (dbConnections.containsKey(database)) {
        thisDatabase = dbConnections.get(database);
    }/*  w  ww .j a v  a 2  s  .c om*/

    if (thisDatabase == null || !thisDatabase.isValid(1)) {
        // At least try to close if not null... even though its not valid
        if (thisDatabase != null) {
            log.error("Database connection '{}' has failed, recreating.", database);
            try {
                thisDatabase.close();
            } catch (SQLException ex) {
                log.error("Error closing invalid connection, ignoring: {}", ex.getMessage());
            }
        }

        // Load the JDBC driver
        try {
            Class.forName(DERBY_DRIVER).newInstance();
        } catch (Exception ex) {
            log.error("Driver load failed: ", ex);
            throw new SQLException("Driver load failed: ", ex);
        }

        // Connection string
        String connection = DERBY_PROTOCOL + database;
        if (create) {
            // log.debug("connect() '{}' SETTING CREATION FLAG", database);
            connection += ";create=true";
        }
        // Try to connect
        // log.debug("connect() '{}' ATTEMPTING CONNECTION", connection);
        thisDatabase = DriverManager.getConnection(connection, new Properties());
        dbConnections.put(database, thisDatabase);
    }

    return thisDatabase;
}

From source file:org.rhq.plugins.mysql.MySqlConnectionManager.java

Connection getConnection(MySqlConnectionInfo info) throws SQLException {
    Connection conn = connections.get(info);
    String url = info.buildURL();
    if (conn == null) {
        if (logger.isInfoEnabled()) {
            logger.info("Attemping connection to " + url);
        }/*from   ww w .j av  a  2  s . c om*/
        conn = DriverManager.getConnection(url, info.getUser(), info.getPassword());
        if (logger.isInfoEnabled()) {
            logger.info("Successfully connected to " + url);
        }
        connections.put(info, conn);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Reusing existing connection to " + url);
        }
    }

    // check the validity of the connection
    if (!conn.isValid(0)) {
        // attempt a single reconnect here and now
        conn.close();
        conn = DriverManager.getConnection(url, info.getUser(), info.getPassword());
        connections.put(info, conn);
        logger.info("Refreshed a connection to " + url);
    }
    return conn;
}

From source file:io.starter.datamodel.Sys.java

/**
 * this method checks things and sends back a 200 if all is OK otherwise an
 * error code is sent//w  w  w .  j a v  a  2s .  c om
 * 
 * used for system monitoring
 * 
 * @param query
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws IOException
 * @throws ServletException
 * @throws JSONException
 * @throws SQLException
 */
@GET
@Path("systemcheck")
@Produces(MediaType.APPLICATION_JSON)
public String getSystemCheck(@Context HttpServletRequest servletRequest,
        @Context HttpServletResponse servletResponse)
        throws IOException, ServletException, JSONException, SQLException {

    JSONObject ret = new JSONObject();
    try {
        SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);
        Connection connection = session.getConnection();
        ret.put("MyBatis DB Connection Status", connection.isValid(10000));
        return ret.toString();
    } catch (Exception e) {
        servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:org.codesearch.commons.database.DBAccessImpl.java

@Inject
public DBAccessImpl() {
    Connection testConnection = null;
    try {//from   www  .j  a v a2s.  c om
        InitialContext ic = new InitialContext();
        Context evtContext = (Context) ic.lookup("java:comp/env/");
        dataSource = (DataSource) evtContext.lookup("jdbc/codesearch");
        if (dataSource != null) {
            testConnection = dataSource.getConnection();
            if (testConnection.isValid(3)) {
                LOG.info("Successfully connected to database");
            }
        } else {
            LOG.error("Database is not configured, code analysis will not be available");
        }
    } catch (SQLException ex) {
        LOG.error("Error accessing database, code analysis will not be available:\n", ex);
    } catch (NamingException ex) {
        LOG.error("Error accessing database, code analysis will not be available:\n", ex);
    } finally {
        if (testConnection != null) {
            try {
                testConnection.close();
            } catch (Exception ex) {
                LOG.warn("Could not close test database connection:\n", ex);
            }
        }
    }
}

From source file:com.thinkbiganalytics.nifi.v2.thrift.RefreshableDataSource.java

/**
 * test the connection to see if it can be used to communicate with the JDBC source
 *
 * @param username a username to connect with if needed
 * @param password a password to connect with if needed
 * @return true if the connection is alive
 */// w w  w  . j  av  a 2s . co m
public synchronized boolean testConnection(String username, String password) {
    // Get a connection to test
    final Connection connection;
    try {
        connection = (StringUtils.isNotBlank(username) || StringUtils.isNotBlank(password))
                ? getConnectionForValidation(username, password)
                : getConnectionForValidation();
        log.info("connection obtained by RefreshableDatasource");
    } catch (final SQLException e) {
        log.warn("A database access error occurred when getting a connection for JDBC URL: ", url, e);
        return false;
    }

    // Test the connection using different methods
    boolean asyncCleanup = false;
    Statement statement = null;

    try {
        // Method 1: Test using driver method
        try {
            // can throw "java.sql.SQLException: Method not supported"; ignore and try other methods if so
            final boolean isValid = connection.isValid(validationQueryTimeout.intValue());
            if (!isValid) {
                log.info("Connection obtained for JDBC URL was not valid: {}", url);
                return false;
            }
        } catch (final SQLException e) {
            log.debug("The isValid() method is not supported for the JDBC URL: {}", url);
        }

        // Method 2: Test with a statement and query timeout
        try {
            statement = connection.createStatement();
        } catch (final SQLException e) {
            log.warn("A database access error occurred when getting a statement for JDBC URL: {}", url, e);
            return false;
        }

        try {
            statement.setQueryTimeout(validationQueryTimeout.intValue()); // throws method not supported if Hive driver
            try {
                statement.execute(validationQuery); // executes if no exception from setQueryTimeout
                return true;
            } catch (final SQLException e) {
                log.debug("Failed to execute validation query for JDBC URL: {}", url, e);
                log.info("Connection obtained for JDBC URL was not valid: {}", url);
                return false;
            }
        } catch (final SQLException e) {
            log.warn("The Statement.setQueryTimeout() method is not supported for the JDBC URL: {}", url);
        }

        // Method 3: Test with a statement and a timer
        asyncCleanup = true;
        boolean isValid;

        try {
            isValid = validateQueryWithTimeout(statement, validationQuery, validationQueryTimeout.intValue());
        } catch (final SQLException e) {
            log.debug("Failed to execute validation query for JDBC URL: {}", url, e);
            isValid = false;
        }

        if (!isValid) {
            log.info("Connection obtained for JDBC URL was not valid: {}", url);
        }
        return isValid;
    } finally {
        connectionCleanup(connection, statement, asyncCleanup);
    }
}

From source file:com.cmart.DB.CassandraDBQuery.java

/**
 * As some connections may timeout if left for a long period, we'll go through them all and make sure they all work
 * if we detect any that have timed out.
 * //from  w w w . jav a 2  s. co m
 * We may miss some since we are not locking the connections object, but we don't need to be 100%, and we don't want
 * to freeze out everyone else while we're doing the check. at least we may get some. It is unlikely that all connections
 * have a fault. We may also be checking some twice since other things can be pushing and popping, again, it's not perfect.
 */
protected void checkConnections() {
    for (int i = 0; i < connections.size(); i++) {
        Connection conn = connections.pop();
        try {
            conn.isValid(1000);

            // The connection worked, so readd it
            connections.offerLast(conn);
        } catch (SQLException e) {
            // The connection is closed or bad, so we don't want it
            conn = null;
        }
    }
}