Example usage for java.sql Connection isClosed

List of usage examples for java.sql Connection isClosed

Introduction

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

Prototype

boolean isClosed() throws SQLException;

Source Link

Document

Retrieves whether this Connection object has been closed.

Usage

From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java

public void releaseConnection(ServerRequestContext context, Connection connection) throws RegistryException {
    if (log.isTraceEnabled()) {
        log.debug("SQLPersistenceManagerImpl.releaseConnection");
        numConnectionsOpen--;//ww  w  . ja v a 2  s  .c o m
        log.debug("Number of connections open:" + numConnectionsOpen);
    }
    try {
        if (connection != null) {
            if (!connection.isClosed() && ((!useConnectionPool) || (ds != null))) {
                connection.close();
            } else if (useConnectionPool) {
                connectionPool.freeConnection(connection);
            }
        }
    } catch (Exception e) {
        throw new RegistryException(e);
    }
}

From source file:com.generalbioinformatics.rdf.VirtuosoConnection.java

@Override
public void sparqlConstruct(String query, OutputStream os) throws StreamException {
    Connection con = null;
    Statement st = null;//from w w  w .  j  av  a  2s.  c  om
    RecordStream rs = null;
    try {
        con = getConnection();
        st = con.createStatement();

        //TODO: evaluate
        logEnable(st, true, false);

        rs = new ResultSetRecordStream(executeQuery(st, "SPARQL " + prefixes + " " + query), st,
                isManagedConnection() ? con : null);

        NtWriter nt = new NtWriter(os);

        Record r;
        while ((r = rs.getNext()) != null) {
            String s = "" + r.get("S");
            String p = "" + r.get("P");
            String o = "" + r.get("O");
            nt.writeStatement(s, p, o);
        }
    } catch (SQLException ex) {
        throw new StreamException(ex);
    } catch (IOException ex) {
        throw new StreamException(ex);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (st != null && !st.isClosed())
                st.close();
            if (isManagedConnection() && !con.isClosed())
                con.close();
        } catch (SQLException ex) {
            /* ignore */ }
    }

}

From source file:nz.co.gregs.dbvolution.DBDatabase.java

private DBStatement getLowLevelStatement()
        throws UnableToCreateDatabaseConnectionException, UnableToFindJDBCDriver, SQLException {
    Connection connection = getConnection();
    try {// w  w w  .  j  a  va 2 s.  co  m
        while (connection.isClosed()) {
            discardConnection(connection);
            connection = getConnection();
        }
        return new DBStatement(this, connection);
    } catch (SQLException cantCreateStatement) {
        discardConnection(connection);
        throw new UnableToCreateDatabaseConnectionException(getJdbcURL(), getUsername(), cantCreateStatement);
    }
}

From source file:com.alkacon.opencms.formgenerator.database.CmsFormDataAccess.java

/**
 * This method closes the result sets and statement and connections.<p>
 * /*from  ww  w.ja  v a2 s.c  o m*/
 * @param con The connection.
 * @param statement The statement.
 * @param res The result set.
 */
private void closeAll(Connection con, Statement statement, ResultSet res) {

    // result set
    if (res != null) {
        try {
            res.close();
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(e.getLocalizedMessage());
            }
        }
    }
    // statement
    if (statement != null) {
        try {
            statement.close();
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(e.getLocalizedMessage());
            }
        }
    }
    // connection
    if (con != null) {
        try {
            if (!con.isClosed()) {
                con.close();
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(e.getLocalizedMessage());
            }
        }
    }
}

From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * Execute query with no result.//from www  .  j a  v  a  2 s.c o  m
 *
 * @param query the query
 * @param giveException throws any exception generated if true, 
 *       if false all exceptions are consumed
 * @throws Exception if giveException is true and their is an error executing
 *       the query
 */
public void executeQueryNoResult(String query, boolean giveException) throws Exception {
    Connection con = null;
    Statement stmt = null;
    SQLException exc = null;
    try {
        con = this.getConnection();
        con.setAutoCommit(false);
        stmt = con.createStatement();
        stmt.execute(query);
        con.commit();
    } catch (SQLException e) {
        if (!giveException) {
            if (log.isErrorEnabled()) {
                log.error(query, e);
            }
        }

        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                if (log.isErrorEnabled()) {
                    log.error("Error during rollback.", e1);
                }
            }
        }
        if (giveException) {
            exc = e;
        }
    } finally {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
                con.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("Error during close.", e);
            }
        }
        if (exc != null && giveException) {
            throw exc;
        }
    }
}

From source file:com.ipcglobal.fredimportaws.TsvsToRedshift.java

/**
 * Copy s3 files to redshift table./*from   ww w  .  j av  a 2s.  com*/
 *
 * @throws Exception the exception
 */
private void copyS3FilesToRedshiftTable() throws Exception {
    GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
    GetSessionTokenResult getSessionTokenResult = stsClient.getSessionToken(getSessionTokenRequest);
    Credentials credentialsToken = getSessionTokenResult.getCredentials();
    String jdbcRedshiftUrl = properties.getProperty("jdbcRedshiftUrl");
    String jdbcRedshiftDriverClass = properties.getProperty("jdbcRedshiftDriverClass");
    String jdbcRedshiftLogin = properties.getProperty("jdbcRedshiftLogin");
    String jdbcRedshiftPassword = properties.getProperty("jdbcRedshiftPassword");

    Class.forName(jdbcRedshiftDriverClass);
    Connection con = null;
    Statement statement = null;

    try {
        String tableName = properties.getProperty("tableNameFred").trim();
        con = DriverManager.getConnection(jdbcRedshiftUrl, jdbcRedshiftLogin, jdbcRedshiftPassword);
        statement = con.createStatement();
        createDatabase(statement); // just in case...
        // Drop/Create table (more efficient than deleting all of the rows)
        dropTable(statement, tableName);
        statement.execute(createTableStatement(tableName));

        long beforeCopy = System.currentTimeMillis();
        String s3SourceBucketPrefix = "s3://" + awsBucketName + "/" + awsBucketTsvPrefix + "/";
        String s3Copy = "copy " + tableName + " from '" + s3SourceBucketPrefix + "' "
                + "CREDENTIALS 'aws_access_key_id=" + credentialsToken.getAccessKeyId().replace("\\", "\\\\")
                + ";" + "aws_secret_access_key=" + credentialsToken.getSecretAccessKey().replace("\\", "\\\\")
                + ";" + "token=" + credentialsToken.getSessionToken().replace("\\", "\\\\") + "' "
                + "delimiter '\\t' gzip";
        statement.executeUpdate(s3Copy);

    } catch (Exception e) {
        log.error(e);
        throw e;
    } finally {
        try {
            if (statement != null && !statement.isClosed())
                statement.close();
        } catch (Exception e) {
            log.warn("Exception closing statement: " + e.getMessage());
        }

        try {
            if (con != null && !con.isClosed())
                con.close();
        } catch (Exception e) {
            log.warn("Exception closing connection: " + e.getMessage());
        }
    }
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Return a {@link Connection} to the query pool
 * /* w  w  w  .j  ava  2 s  .  c om*/
 * @param connection
 *            {@link Connection} to return
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_GETTING_CONNECTION} if there was a problem returning a connection to the query pool
 * 
 */
private void returnQueryConnection(Connection connection) throws AnzoException {
    try {
        if (!connection.isClosed()) {
            queryPool.returnObject(connection);
        } else {
            queryPool.invalidateObject(connection);
        }
    } catch (AnzoException ae) {
        throw ae;
    } catch (Exception exception) {
        throw new AnzoException(ExceptionConstants.RDB.FAILED_RETURNING_CONNECTION, exception);
    }
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Return a {@link Connection} to the write pool
 * /* ww w  . ja  v  a2  s .c  om*/
 * @param connection
 *            {@link Connection} to return
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_GETTING_CONNECTION} if there was a problem returning a connection to the write pool
 * 
 */
private void returnWriteConnection(Connection connection) throws AnzoException {
    try {
        if (!connection.isClosed()) {
            if (!connection.getAutoCommit()) {
                abort(connection, false, true);
            }
            writePool.returnObject(connection);
        } else {
            writePool.invalidateObject(connection);
        }

    } catch (AnzoException ae) {
        throw ae;
    } catch (Exception exception) {
        throw new AnzoException(ExceptionConstants.RDB.FAILED_RETURNING_CONNECTION, exception);
    }
}

From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java

public void run() {

    BufferedReader d = null;//from   w w w  .  ja  v  a2 s  .co m
    Connection conn = null;

    if (conn == null) {

        try {
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {

                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                ResultSet rs = null;
                int ServerId = 0;
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                {
                    SoftReference sf = new SoftReference(
                            stmt.executeQuery("show global variables like 'SERVER_ID'"));
                    rs = (ResultSet) sf.get();
                }
                rs.next();
                ServerId = rs.getInt(2);

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval = StressTool.getNumberFromRandom(10).intValue();
                //               intBlobInterval++;
                //IMPLEMENTING lazy

                Vector v = null;
                {
                    SoftReference sf = new SoftReference(this.getTablesValues(lazy, ServerId));
                    v = (Vector) sf.get();
                }
                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=10737418");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        //                      System.out.println("Blob insert value :" + intBlobInterval);
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            //                        intBlobInterval=0;

                        }
                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY1==" + insert1));
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY2==" + insert2));
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());

                    } else {
                        sqle.printStackTrace();
                        System.out.println("FAILED QUERY1==" + insert1);
                        System.out.println("FAILED QUERY2==" + insert2);
                        sqle.printStackTrace();
                        System.exit(1);
                    }
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    rs.close();
                    stmt.close();
                    rs = null;
                    stmt = null;

                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

                conn.close();
                conn = null;
            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            if (StressTool.getErrorLogHandler() != null) {
                StressTool.getErrorLogHandler().appendToFile(ex.toString() + "\n");
            } else
                ex.printStackTrace();

            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                if (StressTool.getErrorLogHandler() != null) {
                    StressTool.getErrorLogHandler().appendToFile(e.toString() + "\n");
                    conn = null;
                } else
                    e.printStackTrace();
            }
        }

    }

}

From source file:org.apache.syncope.core.util.ContentExporter.java

public void export(final OutputStream os, final String wfTablePrefix)
        throws SAXException, TransformerConfigurationException {

    if (StringUtils.isNotBlank(wfTablePrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(wfTablePrefix);
    }/*from   w  w w . j a  v a2 s  .c  o  m*/

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, SyncopeConstants.DEFAULT_ENCODING);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
        final DatabaseMetaData meta = conn.getMetaData();

        final String schema = dbSchema;

        rs = meta.getTables(null, schema, null, new String[] { "TABLE" });

        final Set<String> tableNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            LOG.debug("Found table {}", tableName);
            if (isTableAllowed(tableName)) {
                tableNames.add(tableName);
            }
        }

        LOG.debug("Tables to be exported {}", tableNames);

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames)) {
            try {
                doExportTable(handler, conn, tableName, TABLES_TO_BE_FILTERED.get(tableName.toUpperCase()));
            } catch (Exception e) {
                LOG.error("Failure exporting table {}", tableName, e);
            }
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }

        DataSourceUtils.releaseConnection(conn, dataSource);
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                LOG.error("While releasing connection", e);
            }
        }
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}