Example usage for java.sql ResultSet isClosed

List of usage examples for java.sql ResultSet isClosed

Introduction

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

Prototype

boolean isClosed() throws SQLException;

Source Link

Document

Retrieves whether this ResultSet object has been closed.

Usage

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

/**
 * Get the domains that belong to a cluster.
 * /* www . j  a  v  a  2  s  .com*/
 * @param logdate the run date of the cluster
 * @param clusterId the cluster's id
 * @return the set of domain names addresses belonging to the cluster
 * @throws SQLException
 */
private Set<String> getClusterDomains(Date logdate, int clusterId) throws SQLException {
    Set<String> retval = new HashSet<String>();
    String logDateTable = dateFormatTable.format(logdate);
    String query = "select domains.domain_name from clusters_" + logDateTable + " as clusters, domains_"
            + logDateTable + " as domains where " + "clusters.cluster_id = " + clusterId
            + " and clusters.domain_id = " + "domains.domain_id";
    ResultSet rs = executeQueryWithResult(query);
    try {
        while (rs.next()) {
            retval.add(DomainNameUtils.reverseDomainName(rs.getString(1)));
        }
    } catch (SQLException e) {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        throw e;
    }
    return retval;
}

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

/**
 * Get the features needed for cluster classification.
 * //from  ww  w  . java  2s. co  m
 * @param logdate the run date of the cluster
 * @param clusterId the cluster's id
 * @return the cluster features
 * @throws SQLException 
 */
private List<Double> getClusterFeatures(Date logdate, int clusterId) throws SQLException {
    List<Double> retval = new ArrayList<Double>();
    String tabDateStr = dateFormatTable.format(logdate);
    String query = "SELECT network_cardinality, ip_diversity, domains_per_network, "
            + "number_of_domains, ttl_per_domain, ip_growth_ratio FROM " + "cluster_feature_vectors_"
            + tabDateStr + " WHERE cluster_id = " + clusterId;
    ResultSet rs = this.executeQueryWithResult(query);
    try {
        if (rs.next()) {
            for (int i = 1; i <= 6; i++) {
                retval.add(rs.getDouble(i));
            }
        }
    } catch (SQLException e) {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        throw e;
    }
    return retval;
}

From source file:org.dspace.storage.rdbms.DatabaseUtils.java

/**
 * Determine if a particular database column exists in our database
 *
 * @param connection//from w  w  w.j  a  v  a 2 s .com
 *          Current Database Connection
 * @param tableName
 *          The name of the table
 * @param columnName
 *          The name of the column in the table
 * @return true if column of that name exists, false otherwise
 */
public static boolean tableColumnExists(Connection connection, String tableName, String columnName) {
    boolean exists = false;
    ResultSet results = null;

    try {
        // Get the name of the Schema that the DSpace Database is using
        // (That way we can search the right schema)
        String schema = getSchemaName(connection);

        // Canonicalize everything to the proper case based on DB type
        schema = canonicalize(connection, schema);
        tableName = canonicalize(connection, tableName);
        columnName = canonicalize(connection, columnName);

        // Get information about our database.
        DatabaseMetaData meta = connection.getMetaData();

        // Search for a column of that name in the specified table & schema
        results = meta.getColumns(null, schema, tableName, columnName);
        if (results != null && results.next()) {
            exists = true;
        }
    } catch (SQLException e) {
        log.error("Error attempting to determine if column " + columnName + " exists", e);
    } finally {
        try {
            // ensure the ResultSet gets closed
            if (results != null && !results.isClosed())
                results.close();
        } catch (SQLException e) {
            // ignore it
        }
    }

    return exists;
}

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

/**
 * Get a clusters classification.//www.  ja va2 s  .c o  m
 * 
 * @param logdate the run date of the cluster
 * @param clusterId the cluster's id
 * @return the clusters classification
 * @throws SQLException
 */
private ClusterClass getClusterClass(Date logdate, int clusterId) throws SQLException {
    String logDateTable = dateFormatTable.format(logdate);
    String query = "select class from cluster_classes_" + logDateTable + " where cluster_id = " + clusterId;
    ResultSet rs = executeQueryWithResult(query);
    try {
        if (rs.next()) {
            return ClusterClass.valueOf(rs.getString(1).toUpperCase());
        } else {
            return ClusterClass.NONE;
        }
    } catch (SQLException e) {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        throw e;
    }
}

From source file:rapture.repo.jdbc.JDBCStructuredStore.java

private List<Map<String, Object>> getCursorResult(String cursorId, int count, boolean isForward) {
    ResultSet rs = cache.getCursor(cursorId);
    if (rs == null) {
        throw RaptureExceptionFactory.create(
                String.format("Invalid cursorId [%s] provided.  No existing cursor in cache.", cursorId));
    }/*from w  w  w  . j  av a 2s .  c  o  m*/
    try {
        int currentCount = 0;
        ResultSetMetaData rsmd = rs.getMetaData();
        int numColumns = rsmd.getColumnCount();
        List<Map<String, Object>> ret = new ArrayList<>();
        while (currentCount++ < count && !rs.isClosed() && (isForward ? rs.next() : rs.previous())) {
            Map<String, Object> row = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
            for (int i = 1; i <= numColumns; i++) {
                row.put(rsmd.getColumnLabel(i), rs.getObject(i));
            }
            ret.add(row);
        }
        return ret.isEmpty() ? null : ret;
    } catch (SQLException e) {
        log.error(ExceptionToString.format(e));
        throw RaptureExceptionFactory
                .create(String.format("SQL Exception while traversing ResultSet: [%s]", e.getMessage()));
    }
}

From source file:org.dspace.storage.rdbms.DatabaseUtils.java

/**
 * Determine if a particular database table exists in our database
 *
 * @param connection//from   www  .j a  va2 s . c o  m
 *          Current Database Connection
 * @param tableName
 *          The name of the table
 * @param caseSensitive
 *          When "true", the case of the tableName will not be changed.
 *          When "false, the name may be uppercased or lowercased based on DB type.
 * @return true if table of that name exists, false otherwise
 */
public static boolean tableExists(Connection connection, String tableName, boolean caseSensitive) {
    boolean exists = false;
    ResultSet results = null;

    try {
        // Get the name of the Schema that the DSpace Database is using
        // (That way we can search the right schema)
        String schema = getSchemaName(connection);

        // Get information about our database.
        DatabaseMetaData meta = connection.getMetaData();

        // If this is not a case sensitive search
        if (!caseSensitive) {
            // Canonicalize everything to the proper case based on DB type
            schema = canonicalize(connection, schema);
            tableName = canonicalize(connection, tableName);
        }

        // Search for a table of the given name in our current schema
        results = meta.getTables(null, schema, tableName, null);
        if (results != null && results.next()) {
            exists = true;
        }
    } catch (SQLException e) {
        log.error("Error attempting to determine if table " + tableName + " exists", e);
    } finally {
        try {
            // ensure the ResultSet gets closed
            if (results != null && !results.isClosed())
                results.close();
        } catch (SQLException e) {
            // ignore it
        }
    }

    return exists;
}

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

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#getClusterIds(java.util.Date)
 *//*from   w ww.j  av  a  2  s  .c o  m*/
@Override
public List<Integer> getClusterIds(Date logdate) {
    ArrayList<Integer> retval = new ArrayList<Integer>();
    String logDateTable = dateFormatTable.format(logdate);
    String query = "select distinct cluster_id from clusters_" + logDateTable;
    ResultSet rs = executeQueryWithResult(query);
    try {
        while (rs.next()) {
            retval.add(rs.getInt(1));
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error retrieving cluster ids.", e);
        }
    } finally {
        try {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        }
    }
    return retval;
}

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

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#getClusterIds(java.util.Date, int)
 */// w ww  . j  av a 2s  . c  om
@Override
public List<Integer> getClusterIds(Date logdate, int minCardinality) {
    List<Integer> retval = new ArrayList<Integer>();
    String tabDateStr = dateFormatTable.format(logdate);
    String query = "SELECT cluster_id FROM cluster_feature_vectors_" + tabDateStr
            + " WHERE network_cardinality >= " + minCardinality;
    ResultSet rs = executeQueryWithResult(query);
    try {
        while (rs.next()) {
            retval.add(rs.getInt(1));
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error retrieving cluster ids.", e);
        }
    } finally {
        try {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        }
    }
    return retval;
}

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

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#getClusterIds(java.util.Date, edu.uga.cs.fluxbuster.classification.ClusterClass)
 *//*w w w.ja va  2  s  .co  m*/
@Override
public List<Integer> getClusterIds(Date logdate, ClusterClass cls) {
    List<Integer> retval = new ArrayList<Integer>();
    String logDateTable = dateFormatTable.format(logdate);
    String query;
    if (cls != ClusterClass.NONE) {
        query = "select cluster_id from cluster_classes_" + logDateTable + " where class = '" + cls + "'";
    } else {
        query = "select distinct clusters.cluster_id from clusters_" + logDateTable
                + " as clusters left outer join cluster_classes_" + logDateTable
                + " as cluster_classes on clusters.cluster_id = "
                + "cluster_classes.cluster_id where cluster_classes.class is NULL";
    }
    ResultSet rs = executeQueryWithResult(query);
    try {
        while (rs.next()) {
            retval.add(rs.getInt(1));
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error retrieving cluster ids.", e);
        }
    } finally {
        try {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        }
    }
    return retval;
}

From source file:com.flexoodb.engines.FlexJAXBDBDataEngine2.java

public Collection<Object> runQuery(String query, Class c, boolean usedefaultimplementation) throws Exception {
    Vector v = new Vector();
    Connection conn = null;// w w w. java2  s.c om
    try {
        conn = (Connection) _pool.getConnection();
        String tablename = query.split("\\s")[3]; // always search the index!

        if (checkTable(tablename, conn, false)) {
            StringBuffer q = new StringBuffer("where ");

            if (query.toUpperCase().indexOf("WHERE") > 0) {
                String sub = query.substring(query.toUpperCase().indexOf("WHERE") + 5);

                sub = sub.replaceAll("<=", " &lteq; ");
                sub = sub.replaceAll(">=", " &gteq; ");
                sub = sub.replaceAll("<>", " &nteq; ");
                sub = sub.replaceAll("=", " = ");
                sub = sub.replaceAll(">", " > ");
                sub = sub.replaceAll("<", " < ");
                sub = sub.replaceAll("&lteq;", "<=");
                sub = sub.replaceAll("&gteq;", ">=");
                sub = sub.replaceAll("&nteq;", "<>").trim();

                //System.out.println("from:"+sub);
                boolean done = false;
                boolean id = false;
                int seq = 0;
                String col = null;
                String condition = null;
                while (!done) {
                    int x = sub.indexOf(" ");
                    String word = sub.substring(0, x < 0 ? sub.length() : x);
                    int wlen = word.length();

                    if (word.startsWith("'")) {
                        word = sub.substring(1, sub.indexOf("'", 1));
                        wlen = word.length() + 2;
                    }

                    //System.out.println("w:"+word+"< "+wlen+" wl:"+word.length());

                    // check if its a predicate
                    if (":like:=:>:<:<=:>=:<>:".indexOf(":" + word.toLowerCase() + ":") > -1) {
                        condition = word;
                        seq = 2;
                    } else if (":and:or:not:".indexOf(":" + word.toLowerCase() + ":") > -1) {
                        q.append(" " + word.trim() + " ");
                        seq = 0;
                    } else if (seq == 0)// it must be a field!
                    {
                        seq = 1; // fields sequence
                        if (word.trim().equalsIgnoreCase("parentid") || word.trim().equalsIgnoreCase("id")) {
                            q.append(" " + word.trim());
                            id = true;
                        } else if (word.trim().equalsIgnoreCase("order")) {
                            String[] order = sub.split("\\s");
                            if (!order[2].equalsIgnoreCase("id") && !order[2].equalsIgnoreCase("parentid")) {
                                // get the 3rd word -- ie the field
                                if (!q.toString().toUpperCase().endsWith("WHERE")) {
                                    q.append(" and ");
                                }

                                q.append(" (element='" + order[2] + "')");

                                q.append(" " + order[0] + " by value "
                                        + sub.substring(sub.indexOf(order[2]) + order[2].length()).trim());
                            } else {
                                q.append(" " + sub);
                            }
                            done = true;
                        } else if (word.trim().equalsIgnoreCase("element")
                                || word.trim().equalsIgnoreCase("limit") || word.trim().equalsIgnoreCase("desc")
                                || word.trim().equalsIgnoreCase("asc")) {
                            q.append(" " + sub);
                            done = true;
                        } else {

                            word = word.replaceAll("'", "\'").trim();
                            //q.append(" (element='"+word.trim().replaceAll("'","")+"'");
                            q.append(" (element='" + word + "'");
                            //col = word.trim().replaceAll("'","");
                            col = word;
                        }
                    } else if (seq == 2) {
                        //word = word.replaceAll("'"," ");
                        word = word.replaceAll("'", "\'");
                        if (id) {
                            q.append("" + condition + "'" + word.trim() + "'");
                        } else {
                            boolean valchanged = false;
                            try {
                                // we look for dates!
                                if (col != null) {
                                    Method met = c.getMethod(
                                            "get" + col.substring(0, 1).toUpperCase() + col.substring(1),
                                            (Class[]) null);
                                    Class c1 = (Class) met.getGenericReturnType();

                                    if (c1.getSimpleName().equalsIgnoreCase("XMLGregorianCalendar")
                                            && !word.isEmpty()) {
                                        //q.append(" and str_to_date(value,\"%Y-%m-%d\") "+condition+" '"+word.trim().replaceAll("'","")+"')");
                                        q.append(" and str_to_date(value,\"%Y-%m-%d\") " + condition + " '"
                                                + word.trim() + "')");
                                        valchanged = true;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            if (!valchanged) {
                                //q.append(" and value "+condition+" '"+word.trim().replaceAll("'","")+"')");
                                q.append(" and value " + condition + " '" + word.trim() + "')");
                            }
                            col = null;
                        }

                        seq = 0;
                        condition = null;
                        id = false;
                    }

                    sub = sub.substring(wlen).trim();
                    if (x < 0 || sub.length() == 0) {
                        done = true;
                    }
                }

            } else {
                int tl = tablename.length();
                q = new StringBuffer(query.substring(query.indexOf(tablename) + tl));
            }

            PreparedStatement ps = null;
            boolean searchindex = false;
            if (!usedefaultimplementation) {
                ps = (PreparedStatement) conn.prepareStatement(
                        "select distinct id from " + tablename.toLowerCase() + " " + q.toString());
            } else {
                ps = (PreparedStatement) conn.prepareStatement(
                        "select distinct id from " + tablename.toLowerCase() + "_index " + q.toString());
                searchindex = true;
            }

            System.out.println(">>>Query:" + ps.toString() + "<<< " + usedefaultimplementation);
            ResultSet rec = ps.executeQuery();
            // check if a record was found
            while (rec != null && !rec.isClosed() && rec.next()) {
                String id = rec.getString("id");
                try {
                    Object o = null;
                    PreparedStatement ps2 = (PreparedStatement) conn
                            .prepareStatement("select id,parentid,content from " + tablename.toLowerCase()
                                    + " where id='" + id + "'");
                    ResultSet res = ps2.executeQuery();
                    // check if a record was found
                    if (res != null && res.next()) {
                        String i = res.getString("id");
                        String p = res.getString("parentid");
                        o = new FlexContainer(_flexutils.getObject(res.getString("content"), c));
                        ((FlexContainer) o).setId(i);
                        ((FlexContainer) o).setParentId(p);

                        ps2.close();
                    } else {
                        ps2.close();
                        if (searchindex) {
                            // then the values found must be orphans! we delete the index contents
                            removeValues(id, tablename, conn);
                        }
                    }

                    if (o != null) {
                        v.add(o);
                        Enumeration en = v.elements();
                        while (en.hasMoreElements()) {
                            en.nextElement();
                        }
                    }
                } catch (Exception g) {
                    throw g;
                }
            }
        }
    } catch (Exception f) {
        throw f;
    } finally {
        try {
            if (conn != null) {
                _pool.releaseConnection(conn);
            }

        } catch (Exception g) {
        }
    }
    return v;
}