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:com.dominion.salud.pedicom.negocio.service.impl.PedidosExtServiceImpl.java

@Override
public void sendByMailByPDF(List<Pedidos> listPedidos) {
    Connection con = null;
    try {//from w w  w .j a v a2 s . co m
        con = routingDataSource.getConnection();
        logger.debug("     Conexion obtenida de bd con username " + con.getMetaData().getUserName());
        logger.debug("     Agrupando pedidos: " + listPedidos.size());
        Map<Integer, List<Pedidos>> map = sortPedidos(listPedidos);
        logger.debug("     Pedidos correctamente agrupados: " + map.size());
        Iterator<Integer> itMap = map.keySet().iterator();
        while (itMap.hasNext()) {
            Integer key = itMap.next();
            List<Pedidos> listPedsProveedor = new ArrayList<>();
            try {
                listPedsProveedor = map.get(key);
                prepararYenviarEmail(listPedsProveedor, con);
            } catch (Exception e) {
                logger.error("     Error", e);
                logger.error(e.toString());
                logger.debug("     Actualizando pedidos a error");
                errorPedido(listPedsProveedor, e);
            }
        }
        logger.debug("ENVIOS FINALIZADOS");
    } catch (SQLException ex) {
        logger.error("     Error", ex);
    } finally {
        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException ex) {
            logger.error("Error :" + ex.getMessage());
        }
    }
}

From source file:org.talend.core.model.metadata.builder.database.ExtractMetaDataUtils.java

/**
 * DOC cantoine. Method to return DatabaseMetaData of a DB connection.
 * //from   ww w .j a va  2s  .co  m
 * @param Connection conn
 * @param isSqlMode whether is sqlMode
 * @param String dbType
 * @return DatabaseMetaData
 * 
 * 
 */
public DatabaseMetaData getDatabaseMetaData(Connection conn, String dbType, boolean isSqlMode,
        String database) {
    DatabaseMetaData dbMetaData = null;
    try {
        if (conn != null && !conn.isClosed()) {
            // MOD sizhaoliu 2012-5-21 TDQ-4884
            if (MSSQL_CONN_CLASS.equals(conn.getClass().getName())) {
                dbMetaData = createJtdsDatabaseMetaData(conn);
            } else if (EDatabaseTypeName.IBMDB2ZOS.getXmlName().equals(dbType)) {
                dbMetaData = createDB2ForZosFakeDatabaseMetaData(conn);
            } else if (EDatabaseTypeName.TERADATA.getXmlName().equals(dbType) && isSqlMode) {
                dbMetaData = createTeradataFakeDatabaseMetaData(conn);
                // add by wzhang for bug 8106. set database name for teradata.
                TeradataDataBaseMetadata teraDbmeta = (TeradataDataBaseMetadata) dbMetaData;
                teraDbmeta.setDatabaseName(database);
            } else if (EDatabaseTypeName.SAS.getXmlName().equals(dbType)) {
                dbMetaData = createSASFakeDatabaseMetaData(conn);
            } else if (EDatabaseTypeName.SYBASEASE.getDisplayName().equals(dbType)
                    || SYBASE_DATABASE_PRODUCT_NAME.equals(dbType)) {
                // TDQ-8300 make sybaseIQ work well,currently,the dbType of sybaseIQ is still
                // "Sybase (ASE and IQ)",so use dbMetaData.getDatabaseProductName() to judge if it is sybaseIQ .
                dbMetaData = conn.getMetaData();
                if (dbMetaData != null && EDatabaseTypeName.SYBASEIQ.getDisplayName()
                        .equals(dbMetaData.getDatabaseProductName())) {
                    dbMetaData = createSybaseIQFakeDatabaseMetaData(conn);
                } else {
                    dbMetaData = createSybaseFakeDatabaseMetaData(conn);
                }
            } else if (EDatabaseTypeName.HIVE.getDisplayName().equals(dbType) && isHiveEmbeddedConn(conn)) {
                // dbMetaData = new EmbeddedHiveDataBaseMetadata(conn);
            } else if (EDatabaseTypeName.AS400.getXmlName().equals(dbType)) {
                dbMetaData = createAS400FakeDatabaseMetaData(conn);
            } else {
                dbMetaData = conn.getMetaData();
            }
        }
    } catch (SQLException e) {
        log.error(e.toString());
        throw new RuntimeException(e);
    } catch (Exception e) {
        log.error(e.toString());
        throw new RuntimeException(e);
    }
    return dbMetaData;
}

From source file:org.georchestra.urbanisme.RenseignUrbaBackend.java

/**
 * Get renseignement d'urbanisme for the given parcelle.
 *
 * @param parcelle Parcelle ID/*from   w ww .java 2 s .c o m*/
 * @return RenseignUrba instance containing the libelles
 * @throws SQLException
 */
public RenseignUrba getParcelle(String parcelle) throws SQLException {

    Connection connection = null;
    PreparedStatement queryLibellesByParcelle = null;

    List<String> libellesVal;
    libellesVal = new ArrayList<String>();

    try {
        connection = this.basicDataSource.getConnection();
        String query = "SELECT " + "     libelle " + "FROM " + "(  SELECT " + "       ru.libelle AS libelle,"
                + "       theme.ventilation_ddc AS ventilation_ddc," + "       ru.numero AS numero "
                + "   FROM " + this.table + " AS ru " + "LEFT OUTER JOIN " + this.tableTheme + " AS theme "
                + "ON " + "  ru.nom_theme = theme.nom " + "WHERE " + "  id_parc = ?) AS libelles "
                + "LEFT JOIN (VALUES " + this.ordreTheme + ") AS ordre(code, priorite) "
                + "ON libelles.ventilation_ddc = ordre.code " + "ORDER BY ordre.priorite ASC, numero ASC ;";

        queryLibellesByParcelle = connection.prepareStatement(query);
        queryLibellesByParcelle.setString(1, parcelle);
        ResultSet rs = queryLibellesByParcelle.executeQuery();

        while (rs.next()) {
            String libelle = rs.getString("libelle");
            libellesVal.add(libelle);
        }
        RenseignUrba renseign = new RenseignUrba(parcelle, libellesVal);
        return renseign;
    } finally {
        if ((queryLibellesByParcelle != null) && (!queryLibellesByParcelle.isClosed())) {
            queryLibellesByParcelle.close();
        }
        if ((connection != null) && (!connection.isClosed())) {
            connection.close();
        }
    }
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

private static Connection getConnection(String postfix) throws SQLException {
    Connection con1;
    if (standAloneServer) {
        // get connection
        con1 = DriverManager.getConnection("jdbc:hive2://localhost:10000/" + postfix, "", "");
    } else {/*from  w w w.  j  a  v  a  2s .c o  m*/
        con1 = DriverManager.getConnection("jdbc:hive2:///" + postfix, "", "");
    }
    assertNotNull("Connection is null", con1);
    assertFalse("Connection should not be closed", con1.isClosed());

    return con1;
}

From source file:org.geowebcache.storage.jdbc.jobstore.JDBCJobWrapper.java

public void destroy() {
    Connection conn = null;
    try {//  ww  w.  j av  a 2  s.c o  m
        conn = getConnection();
        this.closing = true;
        try {
            conn.createStatement().execute("SHUTDOWN");
        } catch (SQLException se) {
            log.warn("SHUTDOWN call to JDBC resulted in: " + se.getMessage());
        }
    } catch (SQLException e) {
        log.error("Couldn't obtain JDBC Connection to perform database shut down", e);
    } finally {
        if (conn != null) {
            // should be already closed after SHUTDOWN
            boolean closed = false;
            try {
                closed = conn.isClosed();
            } catch (SQLException e) {
                log.error(e);
            }
            if (!closed) {
                close(conn);
            }
        }
    }

    try {
        Thread.sleep(250);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.gc();
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.gc();
}

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

/**
 * Executes a prepared statement with no result.
 * /*w w w . j a  va  2s  . co  m*/
 * @param con the connection to the database
 * @param stmt the prepared statement to execute
 */
private void executePreparedStatementNoResult(Connection con, PreparedStatement stmt) {
    try {
        con.setAutoCommit(false);
        stmt.execute();
        con.commit();
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("", e);
        }
        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                if (log.isErrorEnabled()) {
                    log.error("Error during rollback.", e1);
                }
            }
        }
    } finally {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("Error setting auto commit.", e);
            }
        }
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static void runChannelTest(String testMessage, final String testName, final Integer testSize,
        Integer testMillis, Integer warmupMillis, Channel[] channels) throws Exception {
    TestSourceConnector[] sourceConnectors = new TestSourceConnector[channels.length];
    List<List<Long>> sentMessageIds = new ArrayList<List<Long>>();
    boolean isPostgres = getDatabaseType().equals("postgres");

    for (int i = 0; i < channels.length; i++) {
        ChannelController.getInstance().deleteAllMessages(channels[i].getChannelId());
        long localChannelId = ChannelController.getInstance().getLocalChannelId(channels[i].getChannelId());

        if (isPostgres) {
            System.out.print("Vacuuming tables for channel: " + channels[i].getChannelId() + "...");
            Connection connection = null;
            Statement statement = null;

            try {
                connection = getConnection();
                connection.setAutoCommit(true);
                statement = connection.createStatement();
                statement.execute("VACUUM ANALYZE d_m" + localChannelId);
                statement.execute("VACUUM ANALYZE d_mm" + localChannelId);
                statement.execute("VACUUM ANALYZE d_mc" + localChannelId);
                statement.execute("VACUUM ANALYZE d_mcm" + localChannelId);
                statement.execute("VACUUM ANALYZE d_ms" + localChannelId);
                statement.execute("VACUUM ANALYZE d_ma" + localChannelId);
            } finally {
                close(statement);/*from w w  w  .  j  a v a2s  .  c om*/

                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }

            System.out.println("done");
        }

        sourceConnectors[i] = (TestSourceConnector) channels[i].getSourceConnector();
        sentMessageIds.add(new ArrayList<Long>());
    }

    for (Channel channel : channels) {
        channel.deploy();
        channel.start(null);
    }

    List<Long> times = new ArrayList<Long>();
    long testStartTime = System.currentTimeMillis();
    long duration = 0;

    if (testMillis != null) {
        if (warmupMillis == null) {
            warmupMillis = 0;
        }

        testMillis += warmupMillis;
        long testBeginTime = testStartTime + warmupMillis;
        long testEndTime = testStartTime + testMillis;

        while (System.currentTimeMillis() < testEndTime) {
            for (int j = 0; j < channels.length; j++) {
                logger.debug("Sending message");
                long msgStartTime = System.currentTimeMillis();
                sentMessageIds.get(j).add(sourceConnectors[j].readTestMessage(testMessage).getMessageId());
                long totalTime = System.currentTimeMillis() - msgStartTime;

                if (System.currentTimeMillis() > testBeginTime) {
                    times.add(totalTime);
                }
            }
        }

        for (Channel channel : channels) {
            channel.stop();
        }

        for (Channel channel : channels) {
            channel.undeploy();
        }

        duration = System.currentTimeMillis() - testBeginTime;
    } else {
        for (int i = 0; i < testSize; i++) {
            for (int j = 0; j < channels.length; j++) {
                logger.debug("Sending message");
                long msgStartTime = System.currentTimeMillis();
                sentMessageIds.get(j).add(sourceConnectors[j].readTestMessage(testMessage).getMessageId());
                long totalTime = System.currentTimeMillis() - msgStartTime;
                times.add(totalTime);
            }
        }

        for (Channel channel : channels) {
            channel.processSourceQueue(0);
            channel.stop();
        }

        for (Channel channel : channels) {
            channel.undeploy();
        }

        duration = System.currentTimeMillis() - testStartTime;
    }

    if (testName != null) {
        System.out.println(testName);
    }

    System.out.println(TestUtils.getPerformanceText(channels[0].getDestinationCount(), duration, times));

    long size = 0;

    for (Channel channel : channels) {
        size += TestUtils.getChannelStorageSize(channel.getChannelId());
    }

    System.out.println("Total Storage Used: " + Precision.round((((float) size) / 1048576f), 2) + " MB");

    for (int i = 0; i < channels.length; i++) {
        List<Long> channelSentMessageIds = sentMessageIds.get(i);
        assertTrue(channelSentMessageIds.size() > 0);

        for (DestinationChainProvider chain : channels[i].getDestinationChainProviders()) {
            for (DestinationConnector destinationConnector : chain.getDestinationConnectors().values()) {
                List<Long> receivedMessageIds = ((TestDestinationConnector) destinationConnector)
                        .getMessageIds();

                // test that the number of messages processed by this destination connector
                // is equal to the number of messages sent to the channel
                assertEquals(channelSentMessageIds.size(), receivedMessageIds.size());

                for (int j = 0; j < channelSentMessageIds.size(); j++) {
                    assertTrue(channelSentMessageIds.get(j) > 0);

                    // test that the messages were processed by the destination in the correct order
                    assertEquals(channelSentMessageIds.get(j), receivedMessageIds.get(j));
                }
            }
        }
    }
}

From source file:org.opencms.db.generic.CmsSqlManager.java

/**
 * Attempts to close the connection, statement and result set after a statement has been executed.<p>
 * /*  ww w  . j a va2s  .  c o m*/
 * @param dbc the current database context
 * @param con the JDBC connection
 * @param stmnt the statement
 * @param res the result set
 */
public void closeAll(CmsDbContext dbc, Connection con, Statement stmnt, ResultSet res) {

    // NOTE: we have to close Connections/Statements that way, because a dbcp PoolablePreparedStatement
    // is not a DelegatedStatement; for that reason its not removed from the trace of the connection when it is closed.
    // So, the connection tries to close it again when the connection is closed itself; 
    // as a result there is an error that forces the connection to be destroyed and not pooled

    if (dbc == null) {
        LOG.error(Messages.get().getBundle().key(Messages.LOG_NULL_DB_CONTEXT_0));
    }

    try {
        // first, close the result set          
        if (res != null) {
            res.close();
        }
    } catch (SQLException e) {
        LOG.debug(e.getLocalizedMessage(), e);
    } finally {
        res = null;
    }

    try {
        // close the statement
        if (stmnt != null) {
            stmnt.close();
        }
    } catch (SQLException e) {
        LOG.debug(e.getLocalizedMessage(), e);
    } finally {
        stmnt = null;
    }

    try {
        // close the connection
        if ((con != null) && !con.isClosed()) {
            con.close();
        }
    } catch (SQLException e) {
        LOG.debug(e.getLocalizedMessage(), e);
    } finally {
        con = null;
    }

}

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

/**
 * Executes a prepared statement with a result.
 * //from  ww w .  jav a2 s .c  o  m
 * @param con the connection to the database
 * @param stmt the prepared statement to execute
 * @return the result of the query
 */
private ResultSet executePreparedStatementWithResult(Connection con, PreparedStatement stmt) {
    ResultSet retval = null;
    try {
        con.setAutoCommit(false);
        retval = stmt.executeQuery();
        con.commit();
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("", e);
        }
        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                if (log.isErrorEnabled()) {
                    log.error("Error during rollback.", e1);
                }
            }
        }
    } finally {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("Error setting auto commit.", e);
            }
        }
    }
    return retval;
}

From source file:com.openddal.test.BaseTestCase.java

public void close(Connection connection, Statement statement, ResultSet rs) {
    if (rs != null) {
        try {/*  w ww.  ja va 2 s . c  om*/
            if (!rs.isClosed())
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            if (!statement.isClosed())
                statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (connection != null) {
        try {
            if (!connection.isClosed())
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}