Search in sources :

Example 26 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class JDBCStore method remove.

/**
     * Remove the Session with the specified session identifier from
     * this Store, if present.  If no such Session is present, this method
     * takes no action.
     *
     * @param id Session identifier of the Session to be removed
     *
     * @exception IOException if an input/output error occurs
     */
@Override
public void remove(String id) throws IOException {
    synchronized (this) {
        int numberOfTries = 2;
        while (numberOfTries > 0) {
            Connection _conn = getConnection();
            if (_conn == null) {
                return;
            }
            try {
                remove(id, _conn);
                // Break out after the finally block
                numberOfTries = 0;
            } catch (SQLException e) {
                manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
                if (dbConnection != null)
                    close(dbConnection);
            } finally {
                release(_conn);
            }
            numberOfTries--;
        }
    }
    if (manager.getContext().getLogger().isDebugEnabled()) {
        manager.getContext().getLogger().debug(sm.getString(getStoreName() + ".removing", id, sessionTable));
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Example 27 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class JDBCStore method keys.

/**
     * Return an array containing the session identifiers of all Sessions
     * currently saved in this Store.  If there are no such Sessions, a
     * zero-length array is returned.
     *
     * @param expiredOnly flag, whether only keys of expired sessions should
     *        be returned
     * @return array containing the list of session IDs
     *
     * @exception IOException if an input/output error occurred
     */
private String[] keys(boolean expiredOnly) throws IOException {
    String[] keys = null;
    synchronized (this) {
        int numberOfTries = 2;
        while (numberOfTries > 0) {
            Connection _conn = getConnection();
            if (_conn == null) {
                return new String[0];
            }
            try {
                String keysSql = "SELECT " + sessionIdCol + " FROM " + sessionTable + " WHERE " + sessionAppCol + " = ?";
                if (expiredOnly) {
                    keysSql += " AND (" + sessionLastAccessedCol + " + " + sessionMaxInactiveCol + " * 1000 < ?)";
                }
                try (PreparedStatement preparedKeysSql = _conn.prepareStatement(keysSql)) {
                    preparedKeysSql.setString(1, getName());
                    if (expiredOnly) {
                        preparedKeysSql.setLong(2, System.currentTimeMillis());
                    }
                    try (ResultSet rst = preparedKeysSql.executeQuery()) {
                        ArrayList<String> tmpkeys = new ArrayList<>();
                        if (rst != null) {
                            while (rst.next()) {
                                tmpkeys.add(rst.getString(1));
                            }
                        }
                        keys = tmpkeys.toArray(new String[tmpkeys.size()]);
                        // Break out after the finally block
                        numberOfTries = 0;
                    }
                }
            } catch (SQLException e) {
                manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
                keys = new String[0];
                // Close the connection so that it gets reopened next time
                if (dbConnection != null)
                    close(dbConnection);
            } finally {
                release(_conn);
            }
            numberOfTries--;
        }
    }
    return keys;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement)

Example 28 with SQLException

use of java.sql.SQLException in project tomcat by apache.

the class JDBCStore method load.

/**
     * Load the Session associated with the id <code>id</code>.
     * If no such session is found <code>null</code> is returned.
     *
     * @param id a value of type <code>String</code>
     * @return the stored <code>Session</code>
     * @exception ClassNotFoundException if an error occurs
     * @exception IOException if an input/output error occurred
     */
@Override
public Session load(String id) throws ClassNotFoundException, IOException {
    StandardSession _session = null;
    org.apache.catalina.Context context = getManager().getContext();
    Log contextLog = context.getLogger();
    synchronized (this) {
        int numberOfTries = 2;
        while (numberOfTries > 0) {
            Connection _conn = getConnection();
            if (_conn == null) {
                return null;
            }
            ClassLoader oldThreadContextCL = context.bind(Globals.IS_SECURITY_ENABLED, null);
            try {
                if (preparedLoadSql == null) {
                    String loadSql = "SELECT " + sessionIdCol + ", " + sessionDataCol + " FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?";
                    preparedLoadSql = _conn.prepareStatement(loadSql);
                }
                preparedLoadSql.setString(1, id);
                preparedLoadSql.setString(2, getName());
                try (ResultSet rst = preparedLoadSql.executeQuery()) {
                    if (rst.next()) {
                        try (ObjectInputStream ois = getObjectInputStream(rst.getBinaryStream(2))) {
                            if (contextLog.isDebugEnabled()) {
                                contextLog.debug(sm.getString(getStoreName() + ".loading", id, sessionTable));
                            }
                            _session = (StandardSession) manager.createEmptySession();
                            _session.readObjectData(ois);
                            _session.setManager(manager);
                        }
                    } else if (context.getLogger().isDebugEnabled()) {
                        contextLog.debug(getStoreName() + ": No persisted data object found");
                    }
                    // Break out after the finally block
                    numberOfTries = 0;
                }
            } catch (SQLException e) {
                contextLog.error(sm.getString(getStoreName() + ".SQLException", e));
                if (dbConnection != null)
                    close(dbConnection);
            } finally {
                context.unbind(Globals.IS_SECURITY_ENABLED, oldThreadContextCL);
                release(_conn);
            }
            numberOfTries--;
        }
    }
    return _session;
}
Also used : Log(org.apache.juli.logging.Log) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ObjectInputStream(java.io.ObjectInputStream)

Example 29 with SQLException

use of java.sql.SQLException in project zeppelin by apache.

the class SqlCompleter method getSqlKeywordsCompletions.

public static Set<String> getSqlKeywordsCompletions(Connection connection) throws IOException, SQLException {
    // Add the default SQL completions
    String keywords = new BufferedReader(new InputStreamReader(SqlCompleter.class.getResourceAsStream("/ansi.sql.keywords"))).readLine();
    Set<String> completions = new TreeSet<>();
    if (null != connection) {
        DatabaseMetaData metaData = connection.getMetaData();
        // Add the driver specific SQL completions
        String driverSpecificKeywords = "/" + metaData.getDriverName().replace(" ", "-").toLowerCase() + "-sql.keywords";
        logger.info("JDBC DriverName:" + driverSpecificKeywords);
        try {
            if (SqlCompleter.class.getResource(driverSpecificKeywords) != null) {
                String driverKeywords = new BufferedReader(new InputStreamReader(SqlCompleter.class.getResourceAsStream(driverSpecificKeywords))).readLine();
                keywords += "," + driverKeywords.toUpperCase();
            }
        } catch (Exception e) {
            logger.debug("fail to get driver specific SQL completions for " + driverSpecificKeywords + " : " + e, e);
        }
        // Add the keywords from the current JDBC connection
        try {
            keywords += "," + metaData.getSQLKeywords();
        } catch (Exception e) {
            logger.debug("fail to get SQL key words from database metadata: " + e, e);
        }
        try {
            keywords += "," + metaData.getStringFunctions();
        } catch (Exception e) {
            logger.debug("fail to get string function names from database metadata: " + e, e);
        }
        try {
            keywords += "," + metaData.getNumericFunctions();
        } catch (Exception e) {
            logger.debug("fail to get numeric function names from database metadata: " + e, e);
        }
        try {
            keywords += "," + metaData.getSystemFunctions();
        } catch (Exception e) {
            logger.debug("fail to get system function names from database metadata: " + e, e);
        }
        try {
            keywords += "," + metaData.getTimeDateFunctions();
        } catch (Exception e) {
            logger.debug("fail to get time date function names from database metadata: " + e, e);
        }
        // Set all keywords to lower-case versions
        keywords = keywords.toLowerCase();
    }
    StringTokenizer tok = new StringTokenizer(keywords, ", ");
    while (tok.hasMoreTokens()) {
        completions.add(tok.nextToken());
    }
    return completions;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) DatabaseMetaData(java.sql.DatabaseMetaData) IOException(java.io.IOException) SQLException(java.sql.SQLException)

Example 30 with SQLException

use of java.sql.SQLException in project hive by apache.

the class Utilities method executeWithRetry.

/**
   * Retry SQL execution with random backoff (same as the one implemented in HDFS-767).
   * This function only retries when the SQL query throws a SQLTransientException (which
   * might be able to succeed with a simple retry). It doesn't retry when the exception
   * is a SQLRecoverableException or SQLNonTransientException. For SQLRecoverableException
   * the caller needs to reconnect to the database and restart the whole transaction.
   *
   * @param cmd the SQL command
   * @param stmt the prepared statement of SQL.
   * @param baseWindow  The base time window (in milliseconds) before the next retry.
   * see {@link #getRandomWaitTime} for details.
   * @param maxRetries the maximum # of retries when getting a SQLTransientException.
   * @throws SQLException throws SQLRecoverableException or SQLNonTransientException the
   * first time it is caught, or SQLTransientException when the maxRetries has reached.
   */
public static <T> T executeWithRetry(SQLCommand<T> cmd, PreparedStatement stmt, long baseWindow, int maxRetries) throws SQLException {
    Random r = new Random();
    T result = null;
    // retry with # of maxRetries before throwing exception
    for (int failures = 0; ; failures++) {
        try {
            result = cmd.run(stmt);
            return result;
        } catch (SQLTransientException e) {
            LOG.warn("Failure and retry #" + failures + " with exception " + e.getMessage());
            if (failures >= maxRetries) {
                throw e;
            }
            long waitTime = getRandomWaitTime(baseWindow, failures, r);
            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException iex) {
            }
        } catch (SQLException e) {
            // throw other types of SQLExceptions (SQLNonTransientException / SQLRecoverableException)
            throw e;
        }
    }
}
Also used : Random(java.util.Random) SQLException(java.sql.SQLException) SQLTransientException(java.sql.SQLTransientException)

Aggregations

SQLException (java.sql.SQLException)17708 PreparedStatement (java.sql.PreparedStatement)7646 ResultSet (java.sql.ResultSet)6472 Connection (java.sql.Connection)6226 Statement (java.sql.Statement)3089 ArrayList (java.util.ArrayList)2495 Test (org.junit.Test)1525 IOException (java.io.IOException)1220 List (java.util.List)760 HashMap (java.util.HashMap)633 CallableStatement (java.sql.CallableStatement)506 Map (java.util.Map)471 Properties (java.util.Properties)426 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)387 Timestamp (java.sql.Timestamp)363 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)328 DatabaseMetaData (java.sql.DatabaseMetaData)326 ResultSetMetaData (java.sql.ResultSetMetaData)301 DataSource (javax.sql.DataSource)295 File (java.io.File)280