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.cws.esolutions.core.dao.impl.ServerDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServerDataDAO#getServer(java.lang.String)
 *//* w  ww  .  j a va2 s  .co m*/
public synchronized List<Object> getServer(final String attribute) throws SQLException {
    final String methodName = IServerDataDAO.CNAME + "#getServer(final String attribute) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("attribute: {}", attribute);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        // we dont know what we have here - it could be a guid or it could be a hostname
        // most commonly it'll be a guid, but we're going to search anyway
        stmt = sqlConn.prepareCall("{ CALL retrServerData(?) }");
        stmt.setString(1, attribute);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.first();

                responseData = new ArrayList<Object>(Arrays.asList(resultSet.getString(1), // T1.SYSTEM_GUID
                        resultSet.getString(2), // T1.SYSTEM_OSTYPE
                        resultSet.getString(3), // T1.SYSTEM_STATUS
                        resultSet.getString(4), // T1.SYSTEM_REGION
                        resultSet.getString(5), // T1.NETWORK_PARTITION
                        resultSet.getString(6), // T1.SYSTEM_TYPE
                        resultSet.getString(7), // T1.DOMAIN_NAME
                        resultSet.getString(8), // T1.CPU_TYPE
                        resultSet.getInt(9), // T1.CPU_COUNT
                        resultSet.getString(10), // T1.SERVER_RACK
                        resultSet.getString(11), // T1.RACK_POSITION
                        resultSet.getString(12), // T1.SERVER_MODEL
                        resultSet.getString(13), // T1.SERIAL_NUMBER
                        resultSet.getInt(14), // T1.INSTALLED_MEMORY
                        resultSet.getString(15), // T1.OPER_IP
                        resultSet.getString(16), // T1.OPER_HOSTNAME
                        resultSet.getString(17), // T1.MGMT_IP
                        resultSet.getString(18), // T1.MGMT_HOSTNAME
                        resultSet.getString(19), // T1.BKUP_IP
                        resultSet.getString(20), // T1.BKUP_HOSTNAME
                        resultSet.getString(21), // T1.NAS_IP
                        resultSet.getString(22), // T1.NAS_HOSTNAME
                        resultSet.getString(23), // T1.NAT_ADDR
                        resultSet.getString(24), // T1.COMMENTS
                        resultSet.getString(25), // T1.ASSIGNED_ENGINEER
                        resultSet.getTimestamp(26), // T1.ADD_DATE
                        resultSet.getTimestamp(27), // T1.DELETE_DATE
                        resultSet.getInt(28), // T1.DMGR_PORT
                        resultSet.getString(29), // T1.OWNING_DMGR
                        resultSet.getString(30), // T1.MGR_ENTRY
                        resultSet.getString(31), // T2.GUID
                        resultSet.getString(32))); // T2.NAME

                if (DEBUG) {
                    DEBUGGER.debug("responseData: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

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

    return responseData;
}

From source file:com.cws.esolutions.core.dao.impl.ServerDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServerDataDAO#getServersByAttribute(java.lang.String, int)
 *//*from  www. j ava 2s . c  o m*/
public synchronized List<Object[]> getServersByAttribute(final String value, final int startRow)
        throws SQLException {
    final String methodName = IServerDataDAO.CNAME
            + "#getServersByAttribute(final String value, final int startRow) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", value);
        DEBUGGER.debug("Value: {}", startRow);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(value, " ").length >= 2) {
            for (String str : StringUtils.split(value, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + value);
        }

        stmt = sqlConn.prepareCall("{CALL getServerByAttribute(?, ?)}");
        stmt.setString(1, sBuilder.toString().trim());
        stmt.setInt(2, startRow);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                responseData = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // GUID
                            resultSet.getString(2), // OPER_HOSTNAME
                            resultSet.getInt(3) / 0 * 100 // score
                    };

                    if (DEBUG) {
                        DEBUGGER.debug("Value: {}", data);
                    }

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

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

    return responseData;
}

From source file:org.atricore.idbus.idojos.dbsessionstore.DbSessionStore.java

/**
 * Close the given db connection./*ww  w  .  j  ava2  s.co  m*/
 *
 * @param dbConnection
 */
protected void close(Connection dbConnection) throws SSOSessionException {
    try {
        if (dbConnection != null && !dbConnection.isClosed()) {
            dbConnection.close();
        }
    } catch (SQLException se) {
        if (__log.isDebugEnabled())
            __log.debug("Error while clossing connection");

        throw new SSOSessionException("Error while clossing connection\n" + se.getMessage());
    } catch (Exception e) {
        if (__log.isDebugEnabled())
            __log.debug("Error while clossing connection");

        throw new SSOSessionException("Error while clossing connection\n" + e.getMessage());
    }

}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#getMessagesByAttribute(String)
 *//*from  w ww.j ava2  s. co  m*/
public synchronized List<Object[]> getMessagesByAttribute(final String value) throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME
            + "#getMessagesByAttribute(final String value) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(value, " ").length >= 2) {
            for (String str : StringUtils.split(value, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + value);
        }

        stmt = sqlConn.prepareCall("{CALL getMessagesByAttribute(?)}");
        stmt.setString(1, sBuilder.toString().trim());

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                responseData = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] messageData = new Object[] { resultSet.getString(1), // svc_message_id
                            resultSet.getString(2), // svc_message_title
                            resultSet.getString(3), // svc_message_txt
                            resultSet.getString(4), // svc_message_author
                            resultSet.getTimestamp(5), // svc_message_submitdate
                            resultSet.getBoolean(6), // svc_message_active
                            resultSet.getBoolean(7), // svc_message_alert
                            resultSet.getBoolean(8), // svc_message_expires
                            resultSet.getTimestamp(9), // svc_message_expirydate
                            resultSet.getTimestamp(10), // svc_message_modifiedon
                            resultSet.getString(11) // svc_message_modifiedby
                    };

                    if (DEBUG) {
                        for (Object obj : messageData) {
                            DEBUGGER.debug("Value: {}", obj);
                        }
                    }

                    responseData.add(messageData);
                }

                if (DEBUG) {
                    for (Object[] str : responseData) {
                        for (Object obj : str) {
                            DEBUGGER.debug("Value: {}", obj);
                        }
                    }
                }
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

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

    return responseData;
}

From source file:org.apache.hadoop.raid.DBUtils.java

public static void close(ResultSet generatedKeys, PreparedStatement[] pstmts, Connection conn) {
    if (generatedKeys != null) {
        try {/*from  w  w  w.  j  a  va  2s .  c  o  m*/
            generatedKeys.close();
        } catch (Exception e) {
            LOG.warn("Error to close ResultSet", e);
        } finally {
            try {
                if (!generatedKeys.isClosed()) {
                    LOG.warn("ResultSet is not closed");
                    DBUtils.numDBOpenObjects++;
                }
            } catch (Exception ignore) {
                DBUtils.numDBOpenObjects++;
            }
        }
    }
    if (pstmts != null && pstmts.length > 0) {
        for (PreparedStatement pstmt : pstmts) {
            if (pstmt == null) {
                continue;
            }
            try {
                pstmt.close();
            } catch (Exception e) {
                LOG.warn("Error to close PreparedStatement", e);
            } finally {
                try {
                    if (!pstmt.isClosed()) {
                        LOG.warn("PreparedStatement is not closed");
                        DBUtils.numDBOpenObjects++;
                    }
                } catch (Exception ignore) {
                    DBUtils.numDBOpenObjects++;
                }
            }
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (Exception e) {
            LOG.warn("Error to close Connection", e);
        } finally {
            try {
                if (!conn.isClosed()) {
                    LOG.warn("Connection is not closed");
                    DBUtils.numDBOpenObjects++;
                }
            } catch (Exception ignore) {
                DBUtils.numDBOpenObjects++;
            }
        }
    }
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateTableController.java

@RequestMapping(value = "/createtable", method = RequestMethod.POST)
public String createTableAction(@ModelAttribute("tableAttribute") NewTable tableAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from   w  w w. j  av  a  2  s  .co  m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create table");

    String tabName = tableAttribute.getTableName();

    String[] columnNames = request.getParameterValues("column_name[]");
    String[] columnTypes = request.getParameterValues("column_type[]");
    String[] columnPrecision = request.getParameterValues("column_precision[]");
    String[] columnDefaultValues = request.getParameterValues("column_default_value[]");
    String[] columnSelectedNulls = request.getParameterValues("column_selected_null[]");
    String[] columnSelectedPrimaryKeys = request.getParameterValues("column_selected_primary_key[]");
    String[] columnSelectedAutoIncrements = request.getParameterValues("column_selected_auto_increment[]");

    logger.debug("New Table Name = " + tabName);
    logger.debug("columnNames = " + Arrays.toString(columnNames));
    logger.debug("columnTypes = " + Arrays.toString(columnTypes));
    logger.debug("columnPrecision = " + Arrays.toString(columnPrecision));
    logger.debug("columnDefaultValues = " + Arrays.toString(columnDefaultValues));
    logger.debug("columnSelectedNulls = " + Arrays.toString(columnSelectedNulls));
    logger.debug("columnSelectedPrimaryKeys = " + Arrays.toString(columnSelectedPrimaryKeys));
    logger.debug("columnSelectedAutoIncrements = " + Arrays.toString(columnSelectedAutoIncrements));

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    DiskStoreDAO dsDAO = GemFireXDWebDAOFactory.getDiskStoreDAO();
    HdfsStoreDAO hdfsDAO = GemFireXDWebDAOFactory.getHdfsStoreDAO();

    List<DiskStore> dsks = dsDAO.retrieveDiskStoreForCreateList((String) session.getAttribute("user_key"));

    List<HdfsStore> hdfs = hdfsDAO.retrieveHdfsStoreForCreateList((String) session.getAttribute("user_key"));

    model.addAttribute("diskstores", dsks);
    model.addAttribute("hdfsstores", hdfs);

    if (submit != null) {

        if (submit.equalsIgnoreCase("Column(s)")) {
            TypeDAO typeDAO = GemFireXDWebDAOFactory.getTypeDAO();
            List<Type> types = typeDAO.retrieveTypeList((String) session.getAttribute("schema"), null,
                    (String) session.getAttribute("user_key"));

            model.addAttribute("types", types);

            int cols = Integer.parseInt(request.getParameter("numColumns"));
            int numColumns = Integer.parseInt((String) session.getAttribute("numColumns"));

            numColumns = numColumns + cols;

            session.setAttribute("numColumns", "" + numColumns);
            session.setAttribute("tabName", tableAttribute.getTableName());

            model.addAttribute("numColumns", numColumns);
            model.addAttribute("tabName", tableAttribute.getTableName());
            model.addAttribute("hdfsStore", tableAttribute.getHdfsStore());
            model.addAttribute("diskStore", tableAttribute.getDiskStore());
        } else {
            // build create table SQL 
            StringBuffer createTable = new StringBuffer();
            String schema = tableAttribute.getSchemaName();
            if (schema.length() == 0) {
                schema = (String) session.getAttribute("schema");
            }

            createTable.append("create table " + schema + "." + tabName + " \n");
            createTable.append("(");

            int i = 0;
            String val = null;

            if (columnNames != null) {
                int size = columnNames.length;
                for (String columnName : columnNames) {
                    createTable.append(columnName + " ");
                    createTable.append(columnTypes[i]);

                    // doing precision / size
                    val = checkIfEntryExists(columnPrecision, i);
                    if (val != null) {
                        createTable.append("(" + columnPrecision[i] + ")");
                    }
                    val = null;

                    // doing auto increment check here
                    val = checkIfEntryExists(columnSelectedAutoIncrements, i);
                    if (val != null) {
                        // should check for column type here
                        if (val.equalsIgnoreCase("Y")) {
                            createTable.append(" generated always as identity");
                        }
                    }
                    val = null;

                    // doing default value
                    val = checkIfEntryExists(columnDefaultValues, i);
                    if (val != null) {
                        // should check for column type here
                        createTable.append(" default " + columnDefaultValues[i]);
                    }
                    val = null;

                    // doing not null check here
                    val = checkIfEntryExists(columnSelectedNulls, i);
                    if (val != null) {
                        if (val.equalsIgnoreCase("Y")) {
                            createTable.append(" NOT NULL");
                        }
                    }
                    val = null;

                    // doing primary key check here
                    val = checkIfEntryExists(columnSelectedPrimaryKeys, i);
                    if (val != null) {
                        if (val.equalsIgnoreCase("Y")) {
                            createTable.append(" CONSTRAINT " + tabName + "_PK Primary Key");
                        }
                    }
                    val = null;

                    int j = size - 1;
                    if (i < j) {
                        createTable.append(",\n");
                    }

                    i++;
                }

            }

            createTable.append(")\n");

            if (request.getParameter("dataPolicy").equalsIgnoreCase("REPLICATE")) {
                createTable.append("REPLICATE\n");
            }

            if (!checkIfParameterEmpty(request, "serverGroups")) {
                createTable.append("SERVER GROUPS (" + tableAttribute.getServerGroups() + ")\n");
            }

            if (!checkIfParameterEmpty(request, "persistant")) {
                if (tableAttribute.getPersistant().equalsIgnoreCase("Y")) {
                    createTable.append("PERSISTENT ");
                    if (!checkIfParameterEmpty(request, "diskStore")) {
                        createTable.append("'" + tableAttribute.getDiskStore() + "' ");
                        if (!checkIfParameterEmpty(request, "persistenceType")) {
                            createTable.append(tableAttribute.getPersistenceType() + "\n");
                        } else {
                            createTable.append("\n");
                        }

                    }
                }
            }

            if (request.getParameter("dataPolicy").equalsIgnoreCase("PARTITION")) {
                if (!checkIfParameterEmpty(request, "partitionBy")) {
                    createTable.append("PARTITION BY " + tableAttribute.getPartitionBy() + "\n");
                }

                if (!checkIfParameterEmpty(request, "colocateWith")) {
                    createTable.append("COLOCATE WITH (" + tableAttribute.getColocateWith() + ")\n");
                }

                if (!checkIfParameterEmpty(request, "redundancy")) {
                    createTable.append("REDUNDANCY " + tableAttribute.getRedundancy() + "\n");
                }
            }

            if (!checkIfParameterEmpty(request, "hdfsStore")) {
                createTable.append("HDFSSTORE (" + tableAttribute.getHdfsStore() + ") ");
                if (request.getParameter("writeonly").equalsIgnoreCase("Y")) {
                    createTable.append("WRITEONLY\n");
                } else {
                    // need to ad eviction properties here
                    if (!checkIfParameterEmpty(request, "evictionbycriteria")) {
                        createTable.append(
                                "EVICTION BY CRITERIA (" + tableAttribute.getEvictionbycriteria() + ")\n");
                    }

                    if (!checkIfParameterEmpty(request, "evictionfrequency")) {
                        createTable
                                .append("EVICTION FREQUENCY " + tableAttribute.getEvictionfrequency() + "\n");
                    } else {
                        if (request.getParameter("evictincoming").equalsIgnoreCase("Y")) {
                            createTable.append("EVICT INCOMING\n");
                        }
                    }
                }

            }

            if (!checkIfParameterEmpty(request, "gatewaysender")) {
                createTable.append("GATEWAYSENDER (" + tableAttribute.getGatewaysender() + ")\n");
            }

            if (!checkIfParameterEmpty(request, "asynceventlistener")) {
                createTable.append("ASYNCEVENTLISTENER (" + tableAttribute.getAsynceventlistener() + ")\n");
            }

            if (!checkIfParameterEmpty(request, "offheap")) {
                if (request.getParameter("offheap").equalsIgnoreCase("Y")) {
                    createTable.append("OFFHEAP\n");
                }
            }

            if (!checkIfParameterEmpty(request, "other")) {
                createTable.append(tableAttribute.getOther() + "\n");
            }

            if (submit.equalsIgnoreCase("create")) {
                Result result = new Result();

                logger.debug("Creating table as -> " + createTable.toString());

                result = GemFireXDWebDAOUtil.runCommand(createTable.toString(),
                        (String) session.getAttribute("user_key"));

                model.addAttribute("result", result);
                model.addAttribute("hdfsStore", tableAttribute.getHdfsStore());
                model.addAttribute("diskStore", tableAttribute.getDiskStore());

            } else if (submit.equalsIgnoreCase("Show SQL")) {
                logger.debug("Table SQL as follows as -> " + createTable.toString());
                model.addAttribute("sql", createTable.toString());
                model.addAttribute("hdfsStore", tableAttribute.getHdfsStore());
                model.addAttribute("diskStore", tableAttribute.getDiskStore());
            } else if (submit.equalsIgnoreCase("Save to File")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, tabName));

                ServletOutputStream out = response.getOutputStream();
                out.println(createTable.toString());
                out.close();
                return null;
            }
        }
    }

    // This will resolve to /WEB-INF/jsp/create-table.jsp
    return "create-table";
}

From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java

private void closeConnection(Connection conn) {
    try {/*from  w w  w . j  a  v a2s  .c o  m*/
        if ((conn != null) && !conn.isClosed()) {
            conn.close();
        }
    } catch (SQLException e) {
        logger.error("Could not close connection");
    }
}

From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java

/**
 * close the connection./*from   w w w .  j av  a  2 s.  co m*/
 *
 * @param connection The connection to be closed
 * @param task       The task which was running
 */
private void close(Connection connection, String task) {
    try {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    } catch (SQLException e) {
        logger.error("Failed to close connection after " + task, e);
    }
}

From source file:com.tacitknowledge.util.migration.jdbc.SqlScriptMigrationTaskTest.java

/**
 * Test that sybase database patches are committed when illegal multi
 * statement transaction commands are used.
 * //from  w w  w.j a  v  a 2 s .com
 * @throws IOException
 *                 if an unexpected error occurs
 * @throws MigrationException
 *                 if an unexpected error occurs
 * @throws SQLException
 *                 if an unexpected error occurs
 */
public void testSybasePatchesCommitsOnEveryStatement() throws IOException, MigrationException, SQLException {
    InputStream is = getClass().getResourceAsStream("test/sybase_tsql.sql");
    assertNotNull(is);
    task = new SqlScriptMigrationTask("sybase_tsql.sql", 1, is);

    MockDatabaseType dbType = new MockDatabaseType("sybase");
    dbType.setMultipleStatementsSupported(false);
    context.setDatabaseType(dbType);
    int numStatements = task.getSqlStatements(context).size();

    // setup mocks to verify commits are called
    MockControl dataSourceControl = MockControl.createControl(DataSource.class);
    DataSource dataSource = (DataSource) dataSourceControl.getMock();
    context.setDataSource(dataSource);

    MockControl connectionControl = MockControl.createControl(Connection.class);
    Connection connection = (Connection) connectionControl.getMock();

    dataSourceControl.expectAndReturn(dataSource.getConnection(), connection);

    MockControl statementControl = MockControl.createControl(Statement.class);
    Statement statement = (Statement) statementControl.getMock();
    statement.execute("");
    statementControl.setMatcher(MockControl.ALWAYS_MATCHER);
    statementControl.setReturnValue(true, MockControl.ONE_OR_MORE);
    statement.close();
    statementControl.setVoidCallable(MockControl.ONE_OR_MORE);

    connectionControl.expectAndReturn(connection.isClosed(), false, MockControl.ONE_OR_MORE);
    connectionControl.expectAndReturn(connection.createStatement(), statement, numStatements);
    connectionControl.expectAndReturn(connection.getAutoCommit(), false, MockControl.ONE_OR_MORE);
    connection.commit();
    /*
     * Magic Number 4 derived from the assumption that the fixture sql
     * contains only one statement that is not allowed in a multi statement
     * transaction: commit at beginning of migrate method commit prior to
     * running the command not allowed in multi statement transaction to
     * clear the transaction state. commit after running the multi statement
     * transaction to clear transaction state for upcoming statements.
     * commit at end of migrate method once all statements executed.
     * 
     * Therefore, if you add more illegal statements to the fixture, add 2
     * more commit call's for each illegal statement.
     */
    connectionControl.setVoidCallable(4);

    dataSourceControl.replay();
    connectionControl.replay();
    statementControl.replay();

    // run tests
    task.migrate(context);
    dataSourceControl.verify();
    connectionControl.verify();
}

From source file:pivotal.au.se.gemfirexdweb.controller.TableViewerController.java

@RequestMapping(value = "/tableviewer", method = RequestMethod.GET)
public String browseTable(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {
    int startAtIndex = 0, endAtIndex = 0;
    javax.servlet.jsp.jstl.sql.Result asyncEventListeners, tableStructure, datalocations, sampledata,
            allTableInfoResult, tableGatewaySenders, tableTriggersResult, tablePrivsResult = null;
    String schema = null;//from   ww  w.  j a  v a2 s  .c o m
    Connection conn = null;

    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {
        conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to show table viewer");

    TableDAO tableDAO = GemFireXDWebDAOFactory.getTableDAO();
    AsynceventDAO asyncDAO = GemFireXDWebDAOFactory.getAsynceventDAO();
    ConstraintDAO conDAO = GemFireXDWebDAOFactory.getConstraintDAO();
    GatewaySenderDAO gsDAO = GemFireXDWebDAOFactory.getGatewaySenderDAO();

    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    JavaCodeReader jcReader = JavaCodeReader.getInstance();

    String tabName = request.getParameter("tabName");
    logger.debug("tableName = " + tabName);
    String selectedSchema = request.getParameter("selectedSchema");
    logger.debug("selectedSchema = " + selectedSchema);

    if (selectedSchema != null) {
        schema = selectedSchema;
    } else {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("schema = " + schema);

    String addasync = request.getParameter("addasync");
    if (addasync == null) {
        addasync = "N";
    }

    logger.debug("addasync = " + addasync);

    String addgateway = request.getParameter("addgateway");
    if (addgateway == null) {
        addgateway = "N";
    }

    logger.debug("addgateway = " + addgateway);

    String clearasync = request.getParameter("clearasync");
    if (clearasync == null) {
        clearasync = "N";
    }

    logger.debug("clearasync = " + clearasync);

    String cleargatewaysender = request.getParameter("cleargatewaysender");
    if (cleargatewaysender == null) {
        cleargatewaysender = "N";
    }

    logger.debug("cleargatewaysender = " + cleargatewaysender);

    String addpriv = request.getParameter("addpriv");
    if (addpriv == null) {
        addpriv = "N";
    }

    logger.debug("addpriv = " + addpriv);

    Result result;

    if (addasync.equals("Y")) {
        result = tableDAO.addAsyncEventListener(schema, tabName, (String) request.getParameter("asynceventid"),
                (String) request.getParameter("curasynclisteners"), (String) session.getAttribute("user_key"));

        model.addAttribute("result", result);
    } else if (clearasync.equals("Y")) {
        result = tableDAO.simpletableCommand(schema, tabName, "REMOVEALLASYNC",
                (String) session.getAttribute("user_key"));

        model.addAttribute("result", result);
    } else if (addgateway.equals("Y")) {
        result = tableDAO.addGatewaySender(schema, tabName, (String) request.getParameter("gatewaysender"),
                (String) request.getParameter("curgatewaysenders"), (String) session.getAttribute("user_key"));

        model.addAttribute("result", result);
    } else if (cleargatewaysender.equals("Y")) {
        result = tableDAO.simpletableCommand(schema, tabName, "REMOVEALLGATEWAYSENDERS",
                (String) session.getAttribute("user_key"));

        model.addAttribute("result", result);
    } else if (addpriv.equals("Y")) {
        result = tableDAO.performPrivilege(schema, tabName, (String) request.getParameter("privType"),
                (String) request.getParameter("privOption"), (String) request.getParameter("privTo"),
                (String) session.getAttribute("user_key"));

        model.addAttribute("result", result);
    }

    datalocations = tableDAO.getDataLocations(schema, tabName, (String) session.getAttribute("user_key"));

    tableStructure = tableDAO.getTableStructure(schema, (String) request.getParameter("tabName"),
            (String) session.getAttribute("user_key"));

    asyncEventListeners = tableDAO.getTableAsyncListeners(tabName, (String) session.getAttribute("user_key"));

    allTableInfoResult = tableDAO.getAllTableInfo(schema, (String) request.getParameter("tabName"),
            (String) session.getAttribute("user_key"));

    String querysql = String.format("select * from %s.%s FETCH FIRST 10 ROWS ONLY", schema, tabName);

    sampledata = QueryUtil.runQuery(conn, querysql, userPrefs.getMaxRecordsinSQLQueryWindow());

    List<Asyncevent> asyncevents = asyncDAO
            .retrieveAsynceventListForAdd((String) session.getAttribute("user_key"));

    List<Constraint> cons = conDAO.retrieveTableConstraintList(schema, tabName,
            (String) session.getAttribute("user_key"));

    tableGatewaySenders = gsDAO.getGatewaySendersForTable((String) request.getParameter("tabName"),
            (String) session.getAttribute("user_key"));

    List<GatewaySender> gatewaysenders = gsDAO
            .retrieveGatewaySenderForAdd((String) session.getAttribute("user_key"));

    tableTriggersResult = tableDAO.getTableTriggers(schema, (String) request.getParameter("tabName"),
            (String) session.getAttribute("user_key"));

    tablePrivsResult = tableDAO.getTablePrivs(schema, (String) request.getParameter("tabName"),
            (String) session.getAttribute("user_key"));

    model.addAttribute("schemas", GemFireXDWebDAOUtil.getAllSchemas((String) session.getAttribute("user_key")));

    model.addAttribute("tablePrivsResult", tablePrivsResult);
    model.addAttribute("tableTriggersResult", tableTriggersResult);
    model.addAttribute("tableGatewaySenders", tableGatewaySenders);
    model.addAttribute("gatewaySendersForAdd", gatewaysenders);

    model.addAttribute("cons", cons);
    model.addAttribute("asyncEventListenersForAdd", asyncevents);

    model.addAttribute("tableStructure", tableStructure);
    model.addAttribute("asyncEventListeners", asyncEventListeners);
    model.addAttribute("allTableInfoResult", allTableInfoResult);
    model.addAttribute("sampledata", sampledata);
    model.addAttribute("querysql", querysql);
    model.addAttribute("tablename", (String) request.getParameter("tabName"));

    model.addAttribute("dataLocationResults", datalocations);
    model.addAttribute("chosenSchema", schema);

    model.addAttribute("eventListener", String.format(jcReader.getJavaCodeBean("callbackListener").getCode(),
            initCap((String) request.getParameter("tabName"))));

    model.addAttribute("asyncListener", String.format(jcReader.getJavaCodeBean("asyncListener").getCode(),
            initCap((String) request.getParameter("tabName"))));

    // This will resolve to /WEB-INF/jsp/tableviewer.jsp
    return "tableviewer";
}