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 IP addresses that belong to a cluster.
 * /*from w  w w.  j ava2s  . c  o  m*/
 * @param logdate the run date of the cluster
 * @param clusterId the cluster's id
 * @return the set of ip addresses belonging to the cluster
 * @throws SQLException
 */
private Set<InetAddress> getClusterIps(Date logdate, int clusterId) throws SQLException {
    Set<InetAddress> retval = new HashSet<InetAddress>();
    String logDateTable = dateFormatTable.format(logdate);
    String query = "select distinct cluster_resolved_ips.resolved_ip from " + "clusters_" + logDateTable
            + " as clusters, cluster_resolved_ips_" + logDateTable
            + " as cluster_resolved_ips where clusters.cluster_id = " + clusterId
            + " and clusters.cluster_id = cluster_resolved_ips.cluster_id";
    ResultSet rs = executeQueryWithResult(query);
    try {
        while (rs.next()) {
            try {
                retval.add(InetAddress.getByName(rs.getString(1)));
            } catch (UnknownHostException e) {
                if (log.isErrorEnabled()) {
                    log.error("", e);
                }
            }
        }
    } catch (SQLException e) {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        throw e;
    }
    return retval;
}

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

public Collection<Object> runQuery2(String query, Class c, boolean usedefaultimplementation) throws Exception {
    Vector v = new Vector();
    Connection conn = null;/*from   w w w . ja va  2 s  . co m*/
    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 ");
            boolean hasid = false;
            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(" _a." + word.trim());
                            id = true;
                            hasid = 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(" (_b.element='" + order[2] + "')");

                                q.append(" " + order[0] + " by _b.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(" (_b.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() + "' and _a.id=_b.id ");
                        } 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(_b.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 _b.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;
                    }
                }

                // restructure query with parenthesis
                int i = q.toString().indexOf("_a.id=_b.id  and");
                if (i > 0) {
                    String qf = q.toString();
                    qf = qf.substring(0, i + 16) + " (" + qf.substring(i + 17).trim() + ")";
                    q = new StringBuffer(qf);
                }

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

            PreparedStatement ps = null;
            boolean searchindex = false;

            System.out.println(">>>>111");

            String stmt = "select distinct " + (hasid ? "_a" : "_b") + ".id from " + tablename.toLowerCase()
                    + " _a, " + tablename.toLowerCase() + "_index _b " + q.toString();
            System.out.println(">>>>" + stmt);
            ps = (PreparedStatement) conn.prepareStatement(stmt);

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

            if (_showsql) {
                System.out.println(this.getClass().getName() + " SQL Query:>" + ps.toString() + "<<");
            }
            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;
}

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

public Collection<Object> runQuery(String query, Class c, boolean usedefaultimplementation) throws Exception {
    Vector v = new Vector();
    Connection conn = null;//  w ww. ja  v a2  s . co  m
    try {

        //System.out.println(">>>>orginal:["+query+"]");

        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();
                sub = sub.replaceAll("&lt;", "<");
                sub = sub.replaceAll("&gt;", ">");

                //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;
            }

            ResultSet rec = ps.executeQuery();

            //System.out.println(">>>Query:["+ps.toString()+"]");

            // check if a record was found
            while (rec != null && !rec.isClosed() && rec.next()) {
                String id = rec.getString("id");
                String xml = null;
                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");
                        xml = res.getString("content");
                        o = new FlexContainer(_flexutils.getObject(FlexUtils.stripNonValidChars(xml), 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) {
                    g.printStackTrace();
                    System.out.println(">>>FlexJAXDBDataEngine Error due to XML:" + xml);
                    throw g;
                }
            }
        }
    } catch (Exception f) {
        f.printStackTrace();
        throw f;
    } finally {
        try {
            if (conn != null) {
                _pool.releaseConnection(conn);
            }

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

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the cluster novelty feature for each cluster generated
 * on a specific run date.//from ww  w .j a va  2s . c o  m
 *
 * @param log_date the run date
 * @param window the number of days previous to use in feature calculation
 * @return a table of values where the keys are cluster ids and the values 
 *       are the feature values
 * @throws SQLException if there is an error calculating the feature values
 */
public Map<Integer, Double> calculateNoveltyFeature(Date log_date, int window) throws SQLException {
    HashMap<Integer, Double> retval = new HashMap<Integer, Double>();
    ArrayList<Date> prevDates = getPrevDates(log_date, window);

    if (prevDates.size() > 0) {
        StringBuffer querybuf = new StringBuffer();
        Formatter formatter = new Formatter(querybuf);
        String curdatestr = df.format(log_date);
        formatter.format(properties.getProperty(NOVELTY_QUERY1_1KEY), curdatestr, curdatestr, curdatestr,
                curdatestr);
        for (Date prevDate : prevDates) {
            formatter.format(" " + properties.getProperty(NOVELTY_QUERY1_2KEY) + " ", df.format(prevDate));
        }
        formatter.format(properties.getProperty(NOVELTY_QUERY1_3KEY), curdatestr, curdatestr);

        ResultSet rs2 = null;
        Hashtable<Integer, Hashtable<String, Long>> new_resolved_ips = new Hashtable<Integer, Hashtable<String, Long>>();
        try {
            rs2 = dbi.executeQueryWithResult(querybuf.toString());
            while (rs2.next()) {
                int cluster_id = rs2.getInt(2);
                if (!new_resolved_ips.containsKey(cluster_id)) {
                    new_resolved_ips.put(cluster_id, new Hashtable<String, Long>());
                }
                String secondLevelDomainName = rs2.getString(1);
                long newips = rs2.getLong(3);
                Hashtable<String, Long> clustertable = new_resolved_ips.get(cluster_id);
                clustertable.put(secondLevelDomainName, newips);
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs2 != null && !rs2.isClosed()) {
                rs2.close();
            }
            formatter.close();
        }

        Hashtable<String, List<Integer>> numDays = new Hashtable<String, List<Integer>>();
        for (Date prevDate : prevDates) {
            String prevDateStr = df.format(prevDate);
            querybuf = new StringBuffer();
            formatter = new Formatter(querybuf);
            formatter.format(properties.getProperty(NOVELTY_QUERY2KEY), curdatestr, prevDateStr, curdatestr,
                    prevDateStr);
            ResultSet rs3 = null;
            try {
                rs3 = dbi.executeQueryWithResult(querybuf.toString());
                while (rs3.next()) {
                    String sldn = rs3.getString(1);
                    if (!numDays.containsKey(sldn)) {
                        numDays.put(sldn, new ArrayList<Integer>());
                    }
                    Date pd = rs3.getDate(2);
                    DateTime start = new DateTime(pd.getTime());
                    DateTime end = new DateTime(log_date.getTime());
                    Days d = Days.daysBetween(start, end);
                    int diffDays = d.getDays();
                    numDays.get(sldn).add(diffDays);
                }
            } catch (Exception e) {
                if (log.isErrorEnabled()) {
                    log.error(e);
                }
            } finally {
                if (rs3 != null && !rs3.isClosed()) {
                    rs3.close();
                }
                formatter.close();
            }
        }

        Hashtable<Integer, List<Float>> clusterValues = new Hashtable<Integer, List<Float>>();
        for (int clusterID : new_resolved_ips.keySet()) {
            clusterValues.put(clusterID, new ArrayList<Float>());

            Hashtable<String, Long> sldnValues = new_resolved_ips.get(clusterID);
            for (String sldn : sldnValues.keySet()) {
                if (numDays.keySet().contains(sldn)) {
                    long newIPCount = sldnValues.get(sldn);
                    float f = ((float) newIPCount) / Collections.max(numDays.get(sldn));
                    clusterValues.get(clusterID).add(f);

                }
            }
        }

        for (int clusterID : clusterValues.keySet()) {
            if (clusterValues.get(clusterID) == null) { //I dont think it is possible for this to ever be true
                retval.put(clusterID, null);
            } else {
                double sum = 0;
                for (double d : clusterValues.get(clusterID)) {
                    sum += d;
                }
                double val = 0;
                if (clusterValues.get(clusterID).size() > 0) {
                    val = sum / clusterValues.get(clusterID).size();
                }
                retval.put(clusterID, val);
            }
        }
    }
    return retval;
}

From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java

/**
 * Produce a JDOM Element for an instance of Results object.
 * <br>//w w w  .  j a v  a2s  . com
 * @param object for which the JDOM Element is to be produced.
 * @param beginRow The starting row from which the results are to be converted to XML.
 * @param endRow The row until which the results are to be converted to XML.
 * @return the JDOM element of the results object that was converted to XML.
 * @exception JDOMException if there is an error producing XML.
 * @exception SQLException if there is an error walking through the ResultSet object.
 */
private Element produceResults(ResultSet object, int beginRow, int endRow) throws JDOMException, SQLException {

    if (object.isClosed()) {
        throw new SQLException("ResultSet is closed at this point, unable to product results"); //$NON-NLS-1$

    }

    if (beginRow < START_ROW) {
        throw new IllegalArgumentException("The starting row cannot be less than 1."); //$NON-NLS-1$
    } else if (beginRow > endRow) {
        throw new IllegalArgumentException("The starting row cannot be less than the ending row."); //$NON-NLS-1$
    }

    int currentRow = object.getRow() + 1;

    if (beginRow > currentRow) {
        while (!object.isLast() && currentRow != beginRow) {
            object.next();
            currentRow++;
        }

    } else if (beginRow < currentRow) {
        while (!object.isFirst() && currentRow != beginRow) {
            object.previous();
            currentRow--;
        }
    }

    return produceMsg(object, endRow);
}

From source file:fetchBooks.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w ww  . j a v  a  2  s. c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    try {

        System.out.println("Inside try 1");
        Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
        //setting up the connection
        String dbURL = "jdbc:derby://localhost:1527/autolib_db_test";
        Connection conn = DriverManager.getConnection(dbURL, "ishtiaq", "ishtiaq");
        Statement stmt = null;
        ResultSet rslt = null;

        if (conn == null) {
            System.out.println("Connection Failed");
        }

        stmt = conn.createStatement();

        String searchTopic = request.getParameter("topic");

        //running a select query in the underlying database on table named books_tbl.
        System.out.println("SEARCH TOPIC   " + searchTopic);
        String sqlQry = "SELECT * FROM  books_tbl where topic = '" + searchTopic.toUpperCase() + "'";
        rslt = stmt.executeQuery(sqlQry); //query is executed by the statement.

        JSONObject jObj = new JSONObject(); //new jsonobject is created

        JSONArray bookArr = new JSONArray(); //new json array is created
        JSONObject book;

        try {
            System.out.println("Inside Try");

            while (rslt.next()) {
                book = new JSONObject();
                book.put("id", rslt.getInt("id")); //put the id of the book converted into Integer in "id"               
                book.put("name", rslt.getString("bookname")); //put the bookname into "name"           
                bookArr.put(book); //bookArr[] is inserted with book ID and bookname which are mandatory fields.
            }

            jObj.put("Books", bookArr); //maps bookArr content to String name "Books"
        } catch (JSONException jse) {

        }
        response.setContentType("application/json");
        response.getWriter().write(jObj.toString()); //toString confirms to JSON syntax rules and converts the jObj content to json text.
        //System.out.println("after json");

        if (!stmt.isClosed())
            stmt.close();
        //closing connection
        if (!rslt.isClosed())
            rslt.close();
    } catch (Exception e) {
        //return null;
    }

}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private List<AbstractEntity> read(final String query, final Class<?> type, final int limit,
        final Connection conn) throws Exception {
    // Make sure the type for the class is available.
    StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type);
    boolean joinedList = AbstractJoinGraph.hasJoinedList(enref);

    SQLQuery parser = new SQLQuery(type);

    String selectsql = parser.parse(query, limit);
    Statement stmnt = conn.createStatement();
    List<AbstractEntity> entities = new ArrayList<AbstractEntity>();
    HashMap<String, AbstractEntity> refindx = null;

    try {/* w w  w .j a v  a2s.c  om*/
        log.debug("SELECT SQL [" + selectsql + "]");
        ResultSet rs = stmnt.executeQuery(selectsql);
        try {
            if (joinedList) {
                refindx = new HashMap<String, AbstractEntity>();
            }

            while (rs.next()) {

                if (!joinedList) {
                    AbstractJoinGraph gr = AbstractJoinGraph.lookup(type);

                    Object obj = type.newInstance();
                    if (!(obj instanceof AbstractEntity))
                        throw new Exception("Unsupported Entity type [" + type.getCanonicalName() + "]");
                    AbstractEntity entity = (AbstractEntity) obj;
                    Stack<KeyValuePair<Class<?>>> path = new Stack<KeyValuePair<Class<?>>>();
                    KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
                    cls.setValue(entity.getClass());
                    path.push(cls);
                    EntityHelper.setEntity(entity, rs, gr, path);
                    entities.add(entity);
                } else {
                    EntityHelper.setEntity(enref, refindx, rs);
                }
            }
        } finally {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        }
        if (joinedList) {
            for (String key : refindx.keySet()) {
                entities.add(refindx.get(key));
            }
        }
        return entities;
    } finally {
        if (stmnt != null && !stmnt.isClosed()) {
            stmnt.close();
        }
    }
}

From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java

private boolean isRSClosed(ResultSet rs) throws SQLException {
    try {// w w  w  .jav a  2  s .c  o  m
        return rs.isClosed();
    } catch (SQLException e) {
        throw e;
    } catch (Throwable e) {
        /*
         * in case they throw a method not found exception for the JDBC
         * driver not supporting v4.0 features
         */
        return false;
    }
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@Test
public void testExecuteSQLQuery() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);
    assertSame(statement, rs.getStatement());

    assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
    assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
    assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability());

    assertFalse(rs.isClosed());
    assertTrue(rs.isBeforeFirst());//w w w .j ava  2  s .c o m
    assertFalse(rs.isAfterLast());

    assertEquals(1, rs.findColumn("empno"));
    assertEquals(2, rs.findColumn("ename"));
    assertEquals(3, rs.findColumn("salary"));
    assertEquals(4, rs.findColumn("hiredate"));

    int count = printResultSet(rs);

    assertEquals(getEmpRowCount(), count);
    assertFalse(rs.isBeforeFirst());
    assertTrue(rs.isAfterLast());
    rs.close();
    assertTrue(rs.isClosed());

    statement.close();
    assertTrue(statement.isClosed());
}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

/**
 * Construct a KiWiTriple from the result of an SQL query. The query result is expected to contain the
 * following columns:/*from   w  w w.ja v a2 s.  co  m*/
 * <ul>
 *     <li>id: the database id of the triple (long value)</li>
 *     <li>subject: the database id of the subject (long value); the node will be loaded using the loadNodeById method</li>
 *     <li>predicate: the database id of the predicate (long value); the node will be loaded using the loadNodeById method</li>
 *     <li>object: the database id of the object (long value); the node will be loaded using the loadNodeById method</li>
 *     <li>context: the database id of the context (long value); the node will be loaded using the loadNodeById method</li>
 *     <li>creator: the database id of the creator (long value); the node will be loaded using the loadNodeById method; may be null</li>
 *     <li>deleted: a flag (boolean) indicating whether this triple has been deleted</li>
 *     <li>inferred: a flag (boolean) indicating whether this triple has been inferred by the KiWi reasoner</li>
 *     <li>createdAt: a timestamp representing the creation date of the triple</li>
 *     <li>createdAt: a timestamp representing the deletion date of the triple (null in case triple is not deleted)</li>
 * </ul>
 * The method will not change the ResultSet iterator, only read its values, so it needs to be executed for each row separately.
 *
 * @param row a database result containing the columns described above
 * @return a KiWiTriple representation of the database result
 */
protected KiWiTriple constructTripleFromDatabase(ResultSet row) throws SQLException {
    if (row.isClosed()) {
        throw new ResultInterruptedException("retrieving results has been interrupted");
    }

    // columns: id,subject,predicate,object,context,deleted,inferred,creator,createdAt,deletedAt
    //          1 ,2      ,3        ,4     ,5      ,6      ,7       ,8      ,9        ,10

    Long id = row.getLong(1);

    KiWiTriple cached = tripleCache.get(id);

    // lookup element in cache first, so we can avoid reconstructing it if it is already there
    if (cached != null) {
        return cached;
    }

    KiWiTriple result = new KiWiTriple();
    result.setId(id);

    KiWiNode[] batch = loadNodesByIds(row.getLong(2), row.getLong(3), row.getLong(4), row.getLong(5));
    result.setSubject((KiWiResource) batch[0]);
    result.setPredicate((KiWiUriResource) batch[1]);
    result.setObject(batch[2]);
    result.setContext((KiWiResource) batch[3]);

    //        result.setSubject((KiWiResource)loadNodeById(row.getLong(2)));
    //        result.setPredicate((KiWiUriResource) loadNodeById(row.getLong(3)));
    //        result.setObject(loadNodeById(row.getLong(4)));
    //        result.setContext((KiWiResource) loadNodeById(row.getLong(5)));
    if (row.getLong(8) != 0) {
        result.setCreator((KiWiResource) loadNodeById(row.getLong(8)));
    }
    result.setDeleted(row.getBoolean(6));
    result.setInferred(row.getBoolean(7));
    result.setCreated(new Date(row.getTimestamp(9).getTime()));
    try {
        if (row.getDate(10) != null) {
            result.setDeletedAt(new Date(row.getTimestamp(10).getTime()));
        }
    } catch (SQLException ex) {
        // work around a MySQL problem with null dates
        // (see http://stackoverflow.com/questions/782823/handling-datetime-values-0000-00-00-000000-in-jdbc)
    }

    cacheTriple(result);

    return result;
}