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:pivotal.au.se.gemfirexdweb.controller.QueryController.java

@RequestMapping(value = "/query", method = RequestMethod.GET)
public String worksheet(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  w w.  ja  va  2  s.  c o 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 show query worksheet");
    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    String action = request.getParameter("action");
    if (action != null) {

        CommandResult result = new CommandResult();
        ConnectionManager cm = ConnectionManager.getInstance();
        Connection conn = cm.getConnection(session.getId());

        if (action.trim().equals("commit")) {
            logger.debug("commit action requested");
            result = QueryUtil.runCommitOrRollback(conn, true, "N");
            addCommandToHistory(session, userPrefs, "commit");

            model.addAttribute("result", result);
        } else if (action.trim().equals("rollback")) {
            logger.debug("rollback action requested");
            result = QueryUtil.runCommitOrRollback(conn, false, "N");
            addCommandToHistory(session, userPrefs, "rollback");

            model.addAttribute("result", result);
        } else if (action.trim().equals("export")) {
            logger.debug("export data to CSV action requested");
            String query = request.getParameter("query");
            String exportDataCSV = QueryUtil.runQueryForCSV(conn, query);

            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME_EXPORT);

            ServletOutputStream out = response.getOutputStream();
            out.println(exportDataCSV);
            out.close();
            return null;
        } else if (action.trim().equals("export_json")) {
            logger.debug("export data to JSON action requested");
            String query = request.getParameter("query");
            String exportDataJSON = QueryUtil.runQueryForJSON(conn, query);

            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME_EXPORT_JSON);

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

    }

    // Create new QueryWindow and add to model
    // This is the formBackingObject
    model.addAttribute("queryAttribute", new QueryWindow());

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

From source file:org.wso2.ws.dataservice.DBUtils.java

private static Connection checkDBConnectionStatus(AxisService axisService, Connection conn) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("checking database connection status");
    }//from ww w.  j  a  v a  2 s  .  co m
    if (DBConstants.DATASOURCE_TYPE_RDBMS
            .equals((String) axisService.getParameterValue(DBConstants.DATASOURCE_TYPE))
            || DBConstants.DATASOURCE_TYPE_JNDI
                    .equals((String) axisService.getParameterValue(DBConstants.DATASOURCE_TYPE))) {
        try {
            if (conn == null || conn.isClosed()) {
                if (log.isDebugEnabled()) {
                    log.debug("Database connection is closed.Trying to re-establish.");
                }
                Config config = (Config) axisService.getParameterValue(DBConstants.CONNECTION_CONFIG);
                return createConnection(axisService, config);
            } else {
                //existing connection is not closed. Return it.
                return conn;
            }
        } catch (SQLException e) {
            log.error("Error occurred while trying to re-establish the database connection.", e);
            throw new AxisFault("Error occurred while trying to re-establish the database connection.", e);
        }
    }
    return null;
}

From source file:gsn.storage.StorageManager.java

public void close(Connection conn) {
    try {/*from  w w w.  j  av  a 2s.c om*/
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    } catch (SQLException e) {
        logger.debug(e.getMessage(), e);
    }
}

From source file:updatePledge.java

/**
 * Creates new form updatePledge//from   ww  w.  ja  va  2  s  .co m
 */
public updatePledge() throws IOException {
    initComponents();

    //setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    jTextField1.setColumns(8);
    jTextField2.setColumns(8);

    jTextField1.setText("MM/DD/YYYY");
    jTextField2.setText("MM/DD/YYYY");

    jComboBox1.removeAllItems();
    jComboBox1.addItem("Item 1");

    jComboBox2.removeAllItems();
    jComboBox2.addItem("Item 1");

    jComboBox2.setBackground(Color.lightGray);
    jComboBox2.setEditable(false);
    jComboBox2.setEnabled(false);

    jComboBox4.setBackground(Color.lightGray);
    jComboBox4.setEditable(false);
    jComboBox4.setEnabled(false);

    //Getting Donor Names and ID's
    try {
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(viewDonors.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection con;
        con = DriverManager.getConnection(DBcon.Connect(), DBcon.Login(), DBcon.Pass()); //(file path, db login, db password) - since it doesnt have a login, leave it blank

        Statement s = con.createStatement();
        System.out.println("Connection to DB established...");

        ResultSet rs = s.executeQuery("SELECT Fname, Minit, Lname, " + "DonorID FROM Individual");

        System.out.println("Is connection closed: " + con.isClosed());
        System.out.println("Connection to DB established...");
        while (rs.next()) {

            //Fname, Minit, Lname
            System.out.print(rs.getString(1) + " ");
            jComboBox1.addItem(rs.getString(1) + ", " + rs.getString(2) + " " + rs.getString(3));
            System.out.print(rs.getString(4));
            jComboBox2.addItem(rs.getString(4));
        }

        con.close();
        System.out.println("Is connection closed: " + con.isClosed());
    } catch (SQLException ex) {
        Logger.getLogger(userLogin.class.getName()).log(Level.SEVERE, null, ex);
    }

    jComboBox5.removeAllItems();
    jComboBox5.addItem("Item 1");

    jComboBox5.addItem("Weekly");
    jComboBox5.addItem("Biweekly");
    jComboBox5.addItem("Monthly");

}

From source file:jongo.jdbc.JDBCExecutor.java

/**
 * Executes the given stored procedure or function in the RDBMS using the given List 
 * of {@link jongo.jdbc.StoredProcedureParam}.
 * @param database database name or schema where to execute the stored procedure or function
 * @param queryName the name of the stored procedure or function. This gets converted to a {call foo()} statement.
 * @param params a List of {@link jongo.jdbc.StoredProcedureParam} used by the stored procedure or function.
 * @return a List of {@link jongo.rest.xstream.Row} with the results of the stored procedure (if out parameters are given)
 * or the results of the function.// w w w.  j ava2  s . com
 * @throws SQLException
 */
public static List<Row> executeQuery(final String database, final String queryName,
        final List<StoredProcedureParam> params) throws SQLException {
    l.debug("Executing stored procedure " + database + "." + queryName);

    DatabaseConfiguration dbconf = conf.getDatabaseConfiguration(database);
    QueryRunner run = JDBCConnectionFactory.getQueryRunner(dbconf);
    final String call = JongoUtils.getCallableStatementCallString(queryName, params.size());
    List<Row> rows = new ArrayList<Row>();

    Connection conn = null;
    CallableStatement cs = null;
    try {
        l.debug("Obtain connection from datasource");
        conn = run.getDataSource().getConnection();

        l.debug("Create callable statement for " + call);
        cs = conn.prepareCall(call);

        l.debug("Add parameters to callable statement");
        final List<StoredProcedureParam> outParams = addParameters(cs, params);

        l.debug("Execute callable statement");
        if (cs.execute()) {
            l.debug("Got a result set " + queryName);
            ResultSet rs = cs.getResultSet();
            JongoResultSetHandler handler = new JongoResultSetHandler(true);
            rows = handler.handle(rs);
        } else if (!outParams.isEmpty()) {
            l.debug("No result set, but we are expecting OUT values from " + queryName);
            Map<String, String> results = new HashMap<String, String>();
            for (StoredProcedureParam p : outParams) {
                results.put(p.getName(), cs.getString(p.getIndex())); // thank $deity we only return strings
            }
            rows.add(new Row(0, results));
        }
    } catch (SQLException ex) {
        l.debug(ex.getMessage());
        throw ex;
    } finally {
        try {
            if (cs != null && !cs.isClosed())
                cs.close();
        } catch (SQLException ex) {
            l.debug(ex.getMessage());
        }
        try {
            if (conn != null && !conn.isClosed())
                conn.close();
        } catch (SQLException ex) {
            l.debug(ex.getMessage());
        }
    }
    l.debug("Received " + rows.size() + " results.");
    return rows;
}

From source file:plum.mybatis.PaginationInterceptor.java

/**
 * perform paging intercetion.//from www .  j ava  2  s.c  o m
 *
 * @param queryArgs Executor.query params.
 */
private void processIntercept(final Object[] queryArgs) {
    //queryArgs = query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler)
    final MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];

    final Object parameter = queryArgs[PARAMETER_INDEX];
    //the need for paging intercept.
    boolean interceptor = ms.getId().matches(_sql_regex);
    //obtain paging information.
    final PageQuery pageQuery = interceptor ? PagingParametersFinder.getInstance().findCriteria(parameter)
            : new PageQuery(PageQuery.DEFAULT_PAGE_SIZE);
    if (interceptor) {
        PAGINATION_CRITERIA_THREAD_LOCAL.set(pageQuery);
    }
    final RowBounds rowBounds = (interceptor) ? offset_paging((RowBounds) queryArgs[ROWBOUNDS_INDEX])
            : (RowBounds) queryArgs[ROWBOUNDS_INDEX];
    int offset = rowBounds.getOffset();
    int limit = rowBounds.getLimit();

    if (_dialect.supportsLimit() && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) {
        final BoundSql boundSql = ms.getBoundSql(parameter);
        String sql = boundSql.getSql().trim();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Pagination sql is <" + sql + ">");
        }
        //implementation of the access to the total number of SQL,to obtain  the total number and stored in the thread location

        Connection connection = null;
        try {
            //get connection
            connection = ms.getConfiguration().getEnvironment().getDataSource().getConnection();
            int count = SQLHelp.getCount(sql, connection, ms, parameter, boundSql, _dialect);
            final Pager pager = new Pager(pageQuery.getPage(), pageQuery.getPageSize(), count);
            PAGINATION_COUNT.set(pager);
        } catch (SQLException e) {
            LOG.error("The total number of access to the database failure.", e);
            PAGINATION_COUNT.set(null);
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException e) {
                LOG.error("Close the database connection error.", e);
            }
        }
        if (_dialect.supportsLimit()) {
            sql = _dialect.getLimitString(sql, offset, limit);
            offset = RowBounds.NO_ROW_OFFSET;
        } else {
            sql = _dialect.getLimitString(sql, 0, limit);
        }
        limit = RowBounds.NO_ROW_LIMIT;

        queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);

        BoundSql newBoundSql = copyFromBoundSql(ms, boundSql, sql);

        MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
        queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
    }
}

From source file:tinygsn.storage.StorageManager.java

public void close(Connection conn) {
    try {// w ww  .j a  v a 2s  .  c  o  m
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    } catch (SQLException e) {
        // logger.debug(e.getMessage(), e);
    }
}

From source file:org.openbravo.database.ConnectionProviderImpl.java

public boolean releaseConnection(Connection conn) {
    if (conn == null)
        return false;
    try {//from   www .j  a v  a2s  .c om
        // Set autocommit, this makes not necessary to explicitly commit, all prepared statements are
        // commited
        conn.setAutoCommit(true);
        if (SessionInfo.getSessionConnection() == null) {
            // close connection if it's not attached to session, other case it will be closed when the
            // request is done
            log4j.debug("close connection directly (no connection in session)");
            if (!conn.isClosed()) {
                conn.close();
            }
        }
    } catch (Exception ex) {
        log4j.error("Error on releaseConnection", ex);
        return false;
    }
    return true;
}

From source file:kenh.xscript.database.elements.Execute.java

/**
 * Execute sql./*from  ww w .ja  va  2s  .  c om*/
 * @param sql  
 * @param parameter
 * @param var   variable name of result
 * @param conn
 */
private int executeSQL(SQLBean sqlBean, String var, java.sql.Connection conn)
        throws UnsupportedScriptException {
    if (sqlBean == null || StringUtils.isBlank(sqlBean.getSql())) {
        UnsupportedScriptException ex = new UnsupportedScriptException(this, "Can't find the sql to execute.");
        throw ex;
    }

    if (conn == null) {
        throw new UnsupportedScriptException(this, "Connection is empty.");
    }

    var = StringUtils.trimToNull(var);

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        if (conn.isClosed()) {
            throw new UnsupportedScriptException(this, "Connection is closed.");
        }

        StringBuffer traceInfo = new StringBuffer();
        traceInfo.append("Execute SQL: \n" + StringUtils.trim(sqlBean.getSql()));

        pstmt = conn.prepareStatement(sqlBean.getSql());
        Map<String, String> parameters = getParameters(sqlBean);

        Iterator<String> elements = parameters.values().iterator();

        // set the Paramter for PreparedStatement
        int i = 1;
        while (elements.hasNext()) {
            String str = elements.next();
            Object obj = this.getEnvironment().parse(str);
            traceInfo.append("\nParam " + i + ": " + obj.toString());
            pstmt.setObject(i, obj);
            i++;
        }

        logger.trace(traceInfo.toString());

        boolean result = false;

        result = pstmt.execute();

        if (result) {
            rs = pstmt.getResultSet();

            if (StringUtils.isNotBlank(var)) {
                ResultSetBean bean = new ResultSetBean(rs);
                this.saveVariable(var, bean, null);
            }

        } else {
            int count = pstmt.getUpdateCount();
            if (StringUtils.isNotBlank(var))
                this.saveVariable(var, count, null);
        }

    } catch (java.sql.SQLException | IllegalAccessException | InstantiationException e) {
        this.getEnvironment().setVariable(Constant.VARIABLE_EXCEPTION, e);
        return EXCEPTION;

    } catch (UnsupportedExpressionException e) {
        throw new UnsupportedScriptException(this, e);
    } finally {

        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
            rs = null;
        }

        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (Exception e) {
            }
            pstmt = null;
        }
    }

    return NONE;

}

From source file:net.ymate.platform.persistence.jdbc.impl.DefaultSession.java

public <T extends IEntity> T insert(T entity, Fields filter, IShardingable shardingable) throws Exception {
    EntityMeta _meta = EntityMeta.createAndGet(entity.getClass());
    PairObject<Fields, Params> _entity = __doGetEntityFieldAndValues(_meta, entity, filter, true);
    String _insertSql = __dialect.buildInsertSQL(entity.getClass(), __tablePrefix, shardingable,
            _entity.getKey());//  w ww  .  ja  va  2  s. com
    IUpdateOperator _opt = new DefaultUpdateOperator(_insertSql, this.__connectionHolder);
    if (_meta.hasAutoincrement()) {
        // Oracle??
        if (__connectionHolder.getDialect() instanceof OracleDialect) {
            final String[] _ids = _meta.getAutoincrementKeys()
                    .toArray(new String[_meta.getAutoincrementKeys().size()]);
            _opt.setAccessorConfig(new EntityAccessorConfig(_meta, __connectionHolder, entity) {
                @Override
                public PreparedStatement getPreparedStatement(Connection conn, String sql) throws SQLException {
                    if (conn != null && !conn.isClosed()) {
                        return conn.prepareStatement(sql, _ids);
                    }
                    return __conn.getConnection().prepareStatement(sql, _ids);
                }
            });
        } else {
            _opt.setAccessorConfig(new EntityAccessorConfig(_meta, __connectionHolder, entity));
        }
    }
    // ?
    for (Object _param : _entity.getValue().params()) {
        _opt.addParameter(_param);
    }
    if (__sessionEvent != null) {
        __sessionEvent.onInsertBefore(new SessionEventContext(_opt));
    }
    _opt.execute();
    if (__sessionEvent != null) {
        __sessionEvent.onInsertAfter(new SessionEventContext(_opt));
    }
    if (_opt.getEffectCounts() > 0) {
        return entity;
    }
    return null;
}