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:org.mule.module.db.internal.domain.connection.TransactionalDbConnectionFactory.java

private Connection getConnectionFromTransaction(Transaction tx, DataSource dataSource) throws SQLException {
    Connection con;

    if (tx.hasResource(dataSource)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Retrieving connection from current transaction: " + tx);
        }/*from  w  ww.  j av  a  2 s.c om*/
        con = (Connection) tx.getResource(dataSource);
    } else {
        con = connectionFactory.create(dataSource);

        try {
            tx.bindResource(dataSource, con);
        } catch (TransactionException e) {
            if (con != null && !con.isClosed()) {
                con.close();
            }

            throw new ConnectionBindingException("Could not bind connection to current transaction: " + tx, e);
        }
    }

    return con;
}

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

@RequestMapping(value = "/types", method = RequestMethod.POST)
public String performTypeAction(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 {/* w ww.  j a  va  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;
            }
        }

    }

    int startAtIndex = 0, endAtIndex = 0;
    String schema = null;
    Result result = new Result();
    List<Type> types = null;
    String ddlString = null;

    logger.debug("Received request to perform an action on the types");

    TypeDAO typeDAO = GemFireXDWebDAOFactory.getTypeDAO();

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

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

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

    if (request.getParameter("search") != null) {
        types = typeDAO.retrieveTypeList(schema, (String) request.getParameter("search"),
                (String) session.getAttribute("user_key"));

        model.addAttribute("search", (String) request.getParameter("search"));
    } else {
        String[] tableList = request.getParameterValues("selected_type[]");
        String commandStr = request.getParameter("submit_mult");

        logger.debug("tableList = " + Arrays.toString(tableList));
        logger.debug("command = " + commandStr);

        // start actions now if tableList is not null

        if (tableList != null) {
            List al = new ArrayList<Result>();
            List<String> al2 = new ArrayList<String>();

            for (String type : tableList) {
                if (commandStr.equalsIgnoreCase("DDL") || commandStr.equalsIgnoreCase("DDL_FILE")) {
                    ddlString = typeDAO.generateDDL(schema, type, (String) session.getAttribute("user_key"));
                    al2.add(ddlString);
                } else {
                    result = null;
                    result = typeDAO.simpletypeCommand(schema, type, commandStr,
                            (String) session.getAttribute("user_key"));
                    al.add(result);
                }
            }

            if (commandStr.equalsIgnoreCase("DDL")) {
                request.setAttribute("arrayresultddl", al2);
            } else if (commandStr.equalsIgnoreCase("DDL_FILE")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, "TypeDDL"));

                ServletOutputStream out = response.getOutputStream();
                for (String ddl : al2) {
                    out.println(ddl);
                }

                out.close();
                return null;
            } else {
                model.addAttribute("arrayresult", al);
            }
        }

        types = typeDAO.retrieveTypeList(schema, null, (String) session.getAttribute("user_key"));
    }

    model.addAttribute("records", types.size());
    model.addAttribute("estimatedrecords", types.size());

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

    if (types.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("types", types);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > types.size()) {
                endAtIndex = types.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();
        }

        List subList = types.subList(startAtIndex, endAtIndex);
        model.addAttribute("types", subList);
    }

    model.addAttribute("startAtIndex", startAtIndex);
    model.addAttribute("endAtIndex", endAtIndex);

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

    model.addAttribute("chosenSchema", schema);

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

From source file:com.github.shynixn.blockball.bukkit.logic.persistence.context.SqlDbContextImpl.java

/**
 * Executes a preparedStatement and sets the given parameters to the statement
 *
 * @param sql        sql//from w  w  w. j  a v  a  2  s  . com
 * @param connection connection
 * @param parameters parameters
 * @return id
 * @throws SQLException exception
 */
public int executeInsert(String sql, Connection connection, Object... parameters) throws SQLException {
    if (sql == null)
        throw new IllegalArgumentException("Sql cannot be null!");
    if (connection == null)
        throw new IllegalArgumentException("Connection cannot be null!");
    if (connection.isClosed())
        throw new IllegalArgumentException("Connection is closed. Cannot create statement!");
    try (final PreparedStatement preparedStatement = connection.prepareStatement(sql,
            Statement.RETURN_GENERATED_KEYS)) {
        this.setParameters(preparedStatement, parameters);
        preparedStatement.executeUpdate();
        try (final ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
            resultSet.next();
            return resultSet.getInt(1);
        }
    }
}

From source file:org.jxstar.dao.pool.PooledConnection.java

/**
 * ????/*from  w  w w .  j  a  va2 s  .co m*/
 * 
 * @param dsName   -- ????
 * @param iTranLevel      -- 
 * @return
 */
private Connection getConnectionFromContext(DataSourceConfig dsConfig) {
    Connection conn = null;
    String jndiName = dsConfig.getJndiName();
    boolean catchError = dsConfig.isCatchError();

    try {
        DataSource ds = (DataSource) _context.lookup(dsConfig.getJndiName());

        conn = ds.getConnection();
        //_log.showDebug("getConnection: " + conn);

        if (conn == null || conn.isClosed()) {
            String dsName = dsConfig.getDataSourceName();
            _log.showError("datasource [{0}] get connection is null!", dsName);
            return null;
        }

        int iTranLevel = getTranLevelConstant(dsConfig.getTranLevel());
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(iTranLevel);
    } catch (NamingException e) {
        if (catchError) {
            _log.showError("error get jndi name is: " + jndiName);
            _log.showError(e);
        }
    } catch (SQLException e) {
        if (catchError) {
            _log.showError("error get jndi name is: " + jndiName);
            _log.showError(e);
        }
    }

    return conn;
}

From source file:com.github.shynixn.blockball.bukkit.logic.persistence.context.SqlDbContextImpl.java

/**
 * Executes a preparedStatement and sets the given parameters to the statement
 *
 * @param sql        sql/* w  w  w  . j a  v  a 2 s  .com*/
 * @param connection connection
 * @param parameters parameters
 * @return resultSet
 * @throws SQLException exception
 */
public PreparedStatement executeQuery(String sql, Connection connection, Object... parameters)
        throws SQLException {
    if (sql == null)
        throw new IllegalArgumentException("Sql cannot be null!");
    if (connection == null)
        throw new IllegalArgumentException("Connection cannot be null!");
    if (connection.isClosed())
        throw new IllegalArgumentException("Connection is closed. Cannot create statement!");
    final PreparedStatement preparedStatement = connection.prepareStatement(sql);
    this.setParameters(preparedStatement, parameters);
    return preparedStatement;
}

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

@RequestMapping(value = "/procs", method = RequestMethod.GET)
public String showProcs(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {
    int startAtIndex = 0, endAtIndex = 0;
    javax.servlet.jsp.jstl.sql.Result procPermissionsResult;
    String schema = null;/*  w w w  .  j  a  v a  2  s . c o m*/

    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 {
        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 show procs");

    StoredProcDAO procDAO = GemFireXDWebDAOFactory.getStoredProcDAO();
    Result result = new Result();

    String procType = request.getParameter("procType");
    logger.debug("procType = " + procType);
    String procAction = request.getParameter("procAction");
    String selectedSchema = request.getParameter("selectedSchema");
    logger.debug("selectedSchema = " + selectedSchema);

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

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

    if (procAction != null) {
        logger.debug("procAction = " + procAction);
        if (procAction.equalsIgnoreCase("DESC")) {
            List<ProcedureParameter> procParams = procDAO.describeProcedure(schema,
                    (String) request.getParameter("procName"), procType,
                    (String) session.getAttribute("user_key"));

            model.addAttribute("procParams", procParams);
            logger.debug("procParamsRows = " + procParams.size());
            model.addAttribute("procParamsRows", procParams.size());
            model.addAttribute("procName", (String) request.getParameter("procName"));
        } else if (procAction.equalsIgnoreCase("PRIVS")) {
            procPermissionsResult = procDAO.getProcPrivs(schema, (String) request.getParameter("procName"),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("procPermissionsResult", procPermissionsResult);
            model.addAttribute("procName", (String) request.getParameter("procName"));

        } else if (procAction.equalsIgnoreCase("ADDORREVOKE")) {

            // do command here
            result = procDAO.performPrivilege(schema, (String) request.getParameter("procName"), procType,
                    (String) request.getParameter("privType"), (String) request.getParameter("privTo"),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

            procPermissionsResult = procDAO.getProcPrivs(schema, (String) request.getParameter("procName"),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("procPermissionsResult", procPermissionsResult);
            model.addAttribute("procName", (String) request.getParameter("procName"));
        } else {
            result = null;
            result = procDAO.simpleprocCommand(schema, (String) request.getParameter("procName"), procAction,
                    request.getParameter("procType").equals("P") ? "procedure" : "function",
                    (String) session.getAttribute("user_key"));

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

    List<StoredProc> procs = procDAO.retrieveProcList(schema, null, (String) request.getParameter("procType"),
            (String) session.getAttribute("user_key"));

    model.addAttribute("procType", procType);
    model.addAttribute("records", procs.size());
    model.addAttribute("estimatedrecords", procs.size());

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

    if (procs.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("procs", procs);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > procs.size()) {
                endAtIndex = procs.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();
        }

        List subList = procs.subList(startAtIndex, endAtIndex);
        model.addAttribute("procs", subList);
    }

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

    model.addAttribute("chosenSchema", schema);

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

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

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

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

    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);
        stmt = sqlConn.prepareCall("{CALL getApplicationData(?)}");
        stmt.setString(1, value);

        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), // APPLICATION_GUID
                        resultSet.getString(2), // APPLICATION_NAME
                        resultSet.getDouble(3), // APPLICATION_VERSION
                        resultSet.getString(4), // INSTALLATION_PATH
                        resultSet.getString(5), // PACKAGE_LOCATION
                        resultSet.getString(6), // PACKAGE_INSTALLER
                        resultSet.getString(7), // INSTALLER_OPTIONS
                        resultSet.getString(8), // LOGS_DIRECTORY
                        resultSet.getString(9) // PLATFORM_GUID
                ));

                if (DEBUG) {
                    DEBUGGER.debug("data: {}", 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.ApplicationDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#listApplications(int)
 *///from  w w w .  j  av a  2  s.  c  o m
public synchronized List<String[]> listApplications(final int startRow) throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#listApplications(final int startRow) throws SQLException";

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

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

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL listApplications(?, ?)}");
        stmt.setInt(1, startRow);
        stmt.registerOutParameter(2, Types.INTEGER);

        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<String[]>();

                while (resultSet.next()) {
                    String[] data = new String[] { resultSet.getString(1), // APPLICATION_GUID
                            resultSet.getString(2), // APPLICATION_NAME
                    };

                    if (DEBUG) {
                        DEBUGGER.debug("Value: {}", (Object[]) 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:com.cws.esolutions.security.dao.userauth.impl.SQLAuthenticator.java

/**
 * @see com.cws.esolutions.security.dao.userauth.interfaces.Authenticator#performLogon(java.lang.String, java.lang.String)
 *///from   ww w. j  a va  2s.  com
public synchronized List<Object> performLogon(final String username, final String password)
        throws AuthenticatorException {
    final String methodName = SQLAuthenticator.CNAME
            + "#performLogon(final String user, final String password) throws AuthenticatorException";

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

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

    try {
        sqlConn = SQLAuthenticator.dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL performAuthentication(?, ?)}");
        stmt.setString(1, username); // username
        stmt.setString(2, password); // password

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

        if (!(stmt.execute())) {
            throw new AuthenticatorException("No user was found for the provided user information");
        }

        resultSet = stmt.getResultSet();

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

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

            userAccount = new ArrayList<Object>();

            for (String returningAttribute : userAttributes.getReturningAttributes()) {
                if (DEBUG) {
                    DEBUGGER.debug("returningAttribute: {}", returningAttribute);
                }

                userAccount.add(resultSet.getString(returningAttribute));
            }

            if (DEBUG) {
                DEBUGGER.debug("List<Object>: {}", userAccount);
            }
        }
    } catch (SQLException sqx) {
        throw new AuthenticatorException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

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

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new AuthenticatorException(sqx.getMessage(), sqx);
        }
    }

    return userAccount;
}

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

@RequestMapping(value = "/tables", method = RequestMethod.POST)
public String performTableAction(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  ww. j  a  v  a2s .  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;
            }
        }

    }

    int startAtIndex = 0, endAtIndex = 0;
    String schema = null;
    Result result = new Result();
    List<Table> tbls = null;

    logger.debug("Received request to perform an action on the tables");

    TableDAO tableDAO = GemFireXDWebDAOFactory.getTableDAO();

    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 viewType = request.getParameter("viewType");
    if (viewType == null) {
        viewType = "ORDINARY";
    }

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

    if (request.getParameter("search") != null) {
        tbls = tableDAO.retrieveTableList(schema, (String) request.getParameter("search"),
                (String) session.getAttribute("user_key"), viewType);

        model.addAttribute("search", (String) request.getParameter("search"));
    } else {
        String[] tableList = request.getParameterValues("selected_tbl[]");
        String commandStr = request.getParameter("submit_mult");

        logger.debug("tableList = " + Arrays.toString(tableList));
        logger.debug("command = " + commandStr);

        // start actions now if tableList is not null

        if (tableList != null) {
            List al = new ArrayList<Result>();
            for (String table : tableList) {
                result = null;
                result = tableDAO.simpletableCommand(schema, table, commandStr,
                        (String) session.getAttribute("user_key"));
                al.add(result);
            }

            model.addAttribute("arrayresult", al);
        }

        tbls = tableDAO.retrieveTableList(schema, null, (String) session.getAttribute("user_key"), viewType);
    }

    model.addAttribute("records", tbls.size());
    model.addAttribute("estimatedrecords", tbls.size());

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

    if (tbls.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("tables", tbls);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > tbls.size()) {
                endAtIndex = tbls.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();

        }

        List subList = tbls.subList(startAtIndex, endAtIndex);
        model.addAttribute("tables", subList);
    }

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

    model.addAttribute("chosenSchema", schema);
    model.addAttribute("viewType", viewType);

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