Example usage for java.sql ResultSet previous

List of usage examples for java.sql ResultSet previous

Introduction

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

Prototype

boolean previous() throws SQLException;

Source Link

Document

Moves the cursor to the previous row in this ResultSet object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    try {/*from   w  w w  .  j a v  a2  s .  c  om*/
        String url = "jdbc:odbc:yourdatabasename";
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String user = "guest";
        String password = "guest";

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);

        Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        String sqlQuery = "SELECT EMPNO, EName, Job, MGR, HIREDATE FROM EMP";

        ResultSet rs = stmt.executeQuery(sqlQuery);

        int rowSize = 0;
        while (rs.next()) {
            rowSize++;
        }

        System.out.println("Number of Rows in ResultSet is: " + rowSize);
        if (rowSize == 0) {
            System.out.println("Since there are no rows, exiting...");
            System.exit(0);
        }

        int cursorPosition = Math.round(rowSize / 2);

        System.out.println("Moving to position: " + cursorPosition);
        rs.absolute(cursorPosition);
        System.out.println("Name: " + rs.getString(2));

        rs.relative(-1);

        cursorPosition = rs.getRow();
        System.out.println("Moving to position: " + cursorPosition);
        System.out.println("Name: " + rs.getString(2));

        System.out.println("Moving to the first row");
        while (!rs.isFirst()) {
            rs.previous();
        }
        System.out.println("Name: " + rs.getString(2));
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:pt.ua.cbd.cbd_project.service.BookService.java

public List<Book> getBooks(String title) {
    String query = "SELECT \n" + "JSON_VALUE(f.doc, '$.id') as id,\n"
            + "JSON_VALUE(f.doc, '$.title') as title,\n" + "JSON_QUERY(f.doc, '$.authors') as authors,\n"
            + "JSON_VALUE(f.doc, '$.creationDate') as creationDate,\n"
            + "JSON_VALUE(f.doc, '$.isAvailable') as isAvailable,\n"
            + "JSON_VALUE(f.doc, '$.addToLibraryDate') as addToLibraryDate\n" + "FROM Book f\n"
            + "WHERE JSON_VALUE(f.doc ,'$.title') LIKE '%" + title + "%'";

    List<Book> bookList = new ArrayList<Book>();

    try {//from  ww w  .  j ava2  s.  c  om
        j.connect();

        ResultSet rs = j.viewTable(query);
        if (!rs.next()) {
            return null;
        }
        rs.previous();
        while (rs.next()) {
            Book book = new Book();
            //logger.info(rs.getString("title"));
            String authors = rs.getString("authors");
            BookAuthors bookAuthors[] = gson.fromJson(authors, BookAuthors[].class);
            book.setAuthors(bookAuthors);
            book.setId(rs.getInt("id"));
            book.setTitle(rs.getString("title"));
            //book.setCreationDate(rs.getString("creationDate"));
            // book.setIsAvailable(rs.getString("isAvailable"));
            book.setAddToLibraryDate(rs.getString("addToLibraryDate"));
            bookList.add(book);
        }
        return bookList;

    } catch (SQLException ex) {
        logger.error(ex.getMessage());
        return null;
    } finally {
        j.connectionClose();
    }

}

From source file:pt.ua.cbd.cbd_project.service.BookService.java

public Book getBookById(int id) {
    String query = "SELECT \n" + "JSON_VALUE(f.doc, '$.id') as id,\n"
            + "JSON_VALUE(f.doc, '$.title') as title,\n" + "JSON_QUERY(f.doc, '$.authors') as authors,\n"
            + "JSON_VALUE(f.doc, '$.creationDate') as creationDate,\n"
            + "JSON_VALUE(f.doc, '$.isAvailable') as isAvailable,\n"
            + "JSON_VALUE(f.doc, '$.addToLibraryDate') as addToLibraryDate\n" + "FROM Book f "
            + "WHERE JSON_VALUE(f.doc, '$.id') = '" + id + "'";
    try {//from   w  w  w. j av a  2  s  .  c o  m
        j.connect();
        ResultSet rs = j.viewTable(query);
        Book book = new Book();
        if (!rs.next()) {
            return null;
        }
        rs.previous();
        while (rs.next()) {

            book.setId(rs.getInt("id"));
            book.setTitle(rs.getString("title"));
            book.setCreationDate(rs.getString("creationDate"));
            book.setIsAvailable(rs.getString("isAvailable"));
            book.setAddToLibraryDate(rs.getString("addToLibraryDate"));

            String authors = rs.getString("authors");
            BookAuthors bookAuthors[] = gson.fromJson(authors, BookAuthors[].class);
            book.setAuthors(bookAuthors);
        }
        return book;
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return null;
    } finally {
        j.connectionClose();
    }

}

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));
    }//  w  ww .ja v 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:GuestBookServlet.java

private void printComments(PrintWriter out, Locale loc) throws IOException {
    Connection conn = null;//from   w  w  w  . j av a 2 s.  co  m

    try {
        DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, loc);
        ResultSet results;
        Statement stmt;
        int rows, count;

        conn = DriverManager.getConnection(jdbcURL, connectionProperties);
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        results = stmt.executeQuery("SELECT NAME, EMAIL, CMT_DATE, " + "COMMENT, COMMENT_ID " + "FROM COMMENT "
                + "ORDER BY CMT_DATE");
        out.println("<dl>");
        results.last();
        results.next();
        rows = results.getRow();
        // pick a random row
        rows = random.nextInt() % rows;
        if (rows < 4) {
            // if the random row is less than 4, print the first 4 rows
            results.afterLast();
        } else {
            // otherwise go to the specified row, print the prior 5 rows
            results.absolute(rows);
        }
        count = 0;
        // print up to 5 rows going backwards from the randomly
        // selected row
        while (results.previous() && (count < 5)) {
            String name, email, cmt;
            Date date;

            count++;
            name = results.getString(1);
            if (results.wasNull()) {
                name = "Unknown User";
            }
            email = results.getString(2);
            if (results.wasNull()) {
                email = "user@host";
            }
            date = results.getDate(3);
            if (results.wasNull()) {
                date = new Date((new java.util.Date()).getTime());
            }
            cmt = results.getString(4);
            if (results.wasNull()) {
                cmt = "No comment.";
            }
            out.println("<dt><b>" + name + "</b> (" + email + ") on " + fmt.format(date) + "</dt>");
            cmt = noXML(cmt);
            out.println("<dd> " + cmt + "</dd>");
        }
        out.println("</dl>");
    } catch (SQLException e) {
        out.println("A database error occurred: " + e.getMessage());
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:gsn.http.restapi.RequestHandler.java

private boolean getData(String sensor, List<String> fields, long from, long to, int size,
        List<Vector<Double>> elements, Vector<Long> timestamps, String[] conditions) {
    Connection connection = null;
    ResultSet resultSet = null;

    boolean result = true;

    try {/*from w w w.j  ava2  s .  co m*/
        connection = Main.getStorage(sensor).getConnection();
        StringBuilder query = new StringBuilder("select timed");

        for (int i = 0; i < fields.size(); i++) {
            query.append(", " + fields.get(i));
        }
        query.append(" from ").append(sensor).append(" where timed >=").append(from).append(" and timed <=")
                .append(to);
        if (conditions != null) {
            for (String cond : conditions) {
                query.append(" and " + cond);
            }
        }

        if (size > 0) {
            query.append(" order by timed desc").append(" limit 0," + size);
        }

        resultSet = Main.getStorage(sensor).executeQueryWithResultSet(query, connection);

        if (size > 0) {
            resultSet.afterLast();
            while (resultSet.previous()) {
                Vector<Double> stream = new Vector<Double>();
                timestamps.add(resultSet.getLong(1));
                for (int i = 0; i < fields.size(); i++) {
                    stream.add(getDouble(resultSet, fields.get(i)));
                }
                elements.add(stream);
            }
        } else {
            while (resultSet.next()) {
                Vector<Double> stream = new Vector<Double>();
                timestamps.add(resultSet.getLong("timed"));
                for (int i = 0; i < fields.size(); i++) {
                    stream.add(getDouble(resultSet, fields.get(i)));
                }
                elements.add(stream);
            }
        }
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        result = false;
    } finally {
        Main.getStorage(sensor).close(resultSet);
        Main.getStorage(sensor).close(connection);
    }

    return result;
}

From source file:org.jtotus.database.LocalJDBC.java

public double[] fetchPeriod(String tableName, DateTime startDate, DateTime endDate, String type) {
    BigDecimal retValue = null;/* ww w .  j a v  a  2s . c  om*/
    PreparedStatement pstm = null;
    java.sql.Date retDate = null;
    ResultSet results = null;
    ArrayList<Double> closingPrices = new ArrayList<Double>(600);
    Connection connection = null;

    try {
        String query = "SELECT " + type + ", DATE FROM " + this.normTableName(tableName)
                + " WHERE DATE>=? AND DATE<=? ORDER BY DATE ASC";
        // this.createTable(connection, this.normTableName(tableName));

        connection = this.getConnection();
        pstm = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        java.sql.Date startSqlDate = new java.sql.Date(startDate.getMillis());
        pstm.setDate(1, startSqlDate);

        java.sql.Date endSqlDate = new java.sql.Date(endDate.getMillis());
        pstm.setDate(2, endSqlDate);

        DateIterator dateIter = new DateIterator(startDate, endDate);

        results = pstm.executeQuery();
        DateTime dateCheck;

        if (debug) {
            System.out.printf("start data %s end date: %s\n", startSqlDate.toString(), endSqlDate.toString());
        }

        while (dateIter.hasNext()) {
            dateCheck = dateIter.nextInCalendar();

            if (results.next()) {
                retValue = results.getBigDecimal(1);
                retDate = results.getDate(2);

                DateTime compCal = new DateTime(retDate.getTime());
                if (compCal.getDayOfMonth() == dateCheck.getDayOfMonth()
                        && compCal.getMonthOfYear() == dateCheck.getMonthOfYear()
                        && compCal.getYear() == dateCheck.getYear()) {
                    closingPrices.add(retValue.doubleValue());
                    continue;
                } else {
                    results.previous();
                }
            }

            BigDecimal failOverValue = getFetcher().fetchData(tableName, dateCheck, type);
            if (failOverValue != null) {
                closingPrices.add(failOverValue.doubleValue());
            }
        }

    } catch (SQLException ex) {
        System.err.printf("LocalJDBC Unable to find date for:'%s' from'%s' Time" + startDate.toDate() + "\n",
                "Cosing Price", tableName);
        ex.printStackTrace();
        SQLException xp = null;
        while ((xp = ex.getNextException()) != null) {
            xp.printStackTrace();
        }

    } finally {
        try {
            if (results != null)
                results.close();
            if (pstm != null)
                pstm.close();
            if (connection != null)
                connection.close();
            //                System.out.printf("Max connect:%d in use:%d\n",mainPool.getMaxConnections(), mainPool.getActiveConnections());
            //                mainPool.dispose();

        } catch (SQLException ex) {
            Logger.getLogger(LocalJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return ArrayUtils.toPrimitive(closingPrices.toArray(new Double[0]));
}

From source file:org.intermine.bio.dataconversion.EnsemblSnpDbConverter.java

/**
 * {@inheritDoc}//from  www.j  a  v a  2 s.  com
 */
public void process(ResultSet res, String chrName) throws Exception {

    if (processedChrNames.contains(chrName.toUpperCase())) {
        LOG.info("Chr " + chrName + " has been processed...");
        return;
    } else {
        processedChrNames.add(chrName.toUpperCase());
    }

    // If empty set
    if (!res.next()) {
        setEmptyResultSet(true);
        LOG.info("Empty result for chr " + chrName);
        return;
    }

    int counter = 0; // result counter
    int snpCounter = 0;
    int consequenceCounter = 0;
    Set<String> seenLocsForSnp = new HashSet<String>(); // stored locations
    Boolean previousUniqueLocation = true; // whether previous snp has an unique location
    String previousTranscriptStableId = null;
    Set<String> consequenceItemIdSet = new HashSet<String>();
    boolean storeSnp = false;
    Integer previousVariationId = null;
    Integer currentVariationId = null;
    Item currentSnpItem = null; // the snp item to be stored
    String currentSnpItemId = null;
    Map<String, Integer> nonTranscriptConsequences = new HashMap<String, Integer>();

    // This code is complicated because not all SNPs map to a unique location and often have
    // locations on multiple chromosomes - we're processing one chromosome at a time for faster
    // queries to MySQL.
    res.previous(); // roll back one position
    while (res.next()) {

        counter++;

        currentVariationId = res.getInt("variation_id");

        // a new snp can't be the previous one OR one with pending consequences
        boolean newSnp = currentVariationId.equals(previousVariationId)
                || pendingSnpVariationIdToConsequencesMap.containsKey(currentVariationId) ? false : true;

        // For the first snp, the if condition is false
        if (pendingSnpVariationIdToConsequencesMap.containsKey(currentVariationId)) {
            previousUniqueLocation = false;
        }

        if (newSnp) {
            // starting a new SNP, store the one just finished - previousRsNumber

            {
                Integer storedSnpInterMineId = storedSnpVariationIdToInterMineIdMap.get(previousVariationId);

                // if we didn't get back a storedSnpId this was the first time we found this
                // (previous) SNP, so store it now
                // For the first snp, there is no previous one, storeSnp is false, if condition
                // is false
                if (storeSnp && storedSnpInterMineId == null) {
                    storedSnpInterMineId = store(currentSnpItem);
                    storedSnpVariationIdToInterMineIdMap.put(previousVariationId, storedSnpInterMineId);
                    snpCounter++;
                }

                if (previousUniqueLocation) {
                    // the SNP we just stored has only one location so we won't see it again
                    // For the first snp, previousUniqueLocation is true, consequenceItemIdSet is
                    // empty, nothing to store
                    storeSnpConsequenceCollections(storedSnpInterMineId, consequenceItemIdSet);
                } else {
                    // we'll see the previous SNP multiple times so hang onto data
                    Set<String> snpConsequences = pendingSnpVariationIdToConsequencesMap
                            .get(previousVariationId);

                    if (snpConsequences == null) {
                        snpConsequences = new HashSet<String>();
                        pendingSnpVariationIdToConsequencesMap.put(previousVariationId, snpConsequences);
                        snpConsequences.addAll(consequenceItemIdSet);
                    }
                }
            }

            // START NEW SNP
            previousVariationId = currentVariationId;
            seenLocsForSnp = new HashSet<String>();
            consequenceItemIdSet = new HashSet<String>();
            storeSnp = true;

            // map weight is the number of chromosome locations for the SNP, in practice there
            // are sometimes fewer locations than the map_weight indicates
            int mapWeight = res.getInt("map_weight");
            boolean currentUniqueLocation = (mapWeight == 1) ? true : false;
            previousUniqueLocation = currentUniqueLocation;

            // if not a unique location and we've seen the SNP before (e.g. on a
            // different chromosome), don't store, because the snp has been stored
            if (!currentUniqueLocation
                    && pendingSnpVariationIdToConsequencesMap.containsKey(currentVariationId)) {
                storeSnp = false;
            }

            if (storeSnp) {
                currentSnpItem = createItem("SNP");
                currentSnpItemId = currentSnpItem.getIdentifier();

                snpVariationIdToItemIdMap.put(currentVariationId, currentSnpItemId);

                currentSnpItem.setAttribute("primaryIdentifier", res.getString("variation_name"));
                currentSnpItem.setReference("organism", getOrganismItem(taxonId));
                currentSnpItem.setAttribute("uniqueLocation", "" + currentUniqueLocation);

                String alleles = res.getString("allele_string");
                if (!StringUtils.isBlank(alleles)) {
                    currentSnpItem.setAttribute("alleles", alleles);
                }

                String type = determineType(alleles);
                if (type != null) {
                    currentSnpItem.setAttribute("type", type);
                }

                // CHROMOSOME AND LOCATION
                // if SNP is mapped to multiple locations don't set chromosome and
                // chromosomeLocation references
                int start = res.getInt("seq_region_start");
                int end = res.getInt("seq_region_end");
                int chrStrand = res.getInt("seq_region_strand");

                int chrStart = Math.min(start, end);
                int chrEnd = Math.max(start, end);

                Item loc = storeLocation("" + chrStart, "" + chrEnd, "" + chrStrand, currentSnpItemId, chrName);

                // if mapWeight is 1 there is only one chromosome location, so set shortcuts
                if (currentUniqueLocation) {
                    currentSnpItem.setReference("chromosome", getChromosome(chrName, taxonId));
                    currentSnpItem.setReference("chromosomeLocation", loc);
                }
                seenLocsForSnp.add(chrName + ":" + chrStart);

                // SOURCE
                String source = res.getString("source_name");
                currentSnpItem.setReference("source", getSourceIdentifier(source));

                // VALIDATION STATES
                String validationStatus = res.getString("validation_status");
                List<String> validationStates = getValidationStateCollection(validationStatus);
                if (!validationStates.isEmpty()) {
                    currentSnpItem.setCollection("validations", validationStates);
                }
            }
        }

        currentSnpItemId = snpVariationIdToItemIdMap.get(currentVariationId);

        if (currentSnpItemId == null) {
            LOG.error("currentSNP is null. vf.variation_feature_id: " + res.getInt("variation_feature_id")
                    + " CurrentVariationId: " + currentVariationId + " previousVariationId: "
                    + previousVariationId + " storeSnp: " + storeSnp);
        } else {
            // we're on the same SNP but maybe a new location

            int start = res.getInt("seq_region_start");
            int end = res.getInt("seq_region_end");
            int strand = res.getInt("seq_region_strand");

            int chrStart = Math.min(start, end);
            int chrEnd = Math.max(start, end);

            String chrLocStr = chrName + ":" + chrStart;
            if (!seenLocsForSnp.contains(chrLocStr)) {
                seenLocsForSnp.add(chrLocStr);
                // if this location is on a chromosome we want, store it
                storeLocation("" + chrStart, "" + chrEnd, "" + strand, currentSnpItemId, chrName);
            }
        }

        // CONSEQUENCE TYPES
        // for SNPs without a uniqueLocation there will be different consequences at each one.
        // some consequences will need to stored at the end
        String currentTranscriptStableId = res.getString("feature_stable_id");

        if (!StringUtils.isBlank(currentTranscriptStableId)) {
            // In Ensembl 66, there are records with same transcript different allel_string
            // | variation_feature_id | feature_stable_id | allele_string | consequence_types     |
            // |             53025155 | ENST00000465814   | A/T           | nc_transcript_variant |
            // |             53025155 | ENST00000465814   | A/C           | nc_transcript_variant |
            // |             53025155 | ENST00000465814   | A/G           | nc_transcript_variant |

            // a new consequence type should not belong to same snp and same transcript
            boolean newConsequenceType = currentTranscriptStableId.equals(previousTranscriptStableId)
                    && currentVariationId.equals(previousVariationId) ? false : true;
            if (newConsequenceType) {
                previousTranscriptStableId = currentTranscriptStableId;
                String type = res.getString("transcript_variation_consequence_types");
                // Seen one example so far where consequence type is an empty string
                if (StringUtils.isBlank(type)) {
                    type = "UNKNOWN";
                }

                Item consequenceItem = createItem("Consequence");
                consequenceItem.setAttribute("description", type);
                for (String individualType : type.split(",")) {
                    consequenceItem.addToCollection("types", getConsequenceType(individualType.trim()));
                }
                setAttIfValue(consequenceItem, "peptideAlleles", res.getString("pep_allele_string"));
                setAttIfValue(consequenceItem, "siftPrediction", res.getString("sift_prediction"));
                setAttIfValue(consequenceItem, "siftScore", res.getString("sift_score"));
                setAttIfValue(consequenceItem, "polyphenPrediction", res.getString("polyphen_prediction"));
                setAttIfValue(consequenceItem, "polyphenScore", res.getString("polyphen_score"));

                consequenceItem.setReference("transcript", getTranscriptIdentifier(currentTranscriptStableId));

                consequenceItemIdSet.add(consequenceItem.getIdentifier());
                store(consequenceItem);
                consequenceCounter++;
            }
        } else { // transcriptStableId is empty, log it
            // variation_feature_consequence_types is full list of consequence types which
            // should include transcript_variation_consequence_types
            String variationConsequences = res.getString("variation_feature_consequence_types");
            Integer consequenceCount = nonTranscriptConsequences.get(variationConsequences);

            if (consequenceCount == null) {
                consequenceCount = new Integer(0);
            }

            // nonTranscriptConsequences is for log message only
            nonTranscriptConsequences.put(variationConsequences, new Integer(consequenceCount + 1));
        }

        if (counter % 100000 == 0) {
            LOG.info("Read " + counter + " rows total, stored " + snpCounter + " SNPs. for chr " + chrName);
        }
    }

    // The last record to store on the chromosome
    Integer storedSnpInterMineId;

    if (previousUniqueLocation) {
        storedSnpInterMineId = store(currentSnpItem);
        storedSnpVariationIdToInterMineIdMap.put(currentVariationId, storedSnpInterMineId);
        storeSnpConsequenceCollections(storedSnpInterMineId, consequenceItemIdSet);
    } else {
        storedSnpInterMineId = storedSnpVariationIdToInterMineIdMap.get(currentVariationId);

        if (storedSnpInterMineId == null) {
            storedSnpInterMineId = store(currentSnpItem);
            storedSnpVariationIdToInterMineIdMap.put(currentVariationId, storedSnpInterMineId);

            Set<String> snpConsequences = pendingSnpVariationIdToConsequencesMap.get(currentVariationId);
            if (snpConsequences == null) {
                snpConsequences = new HashSet<String>();
                pendingSnpVariationIdToConsequencesMap.put(currentVariationId, snpConsequences);
                snpConsequences.addAll(consequenceItemIdSet);
            }
        } else {
            pendingSnpVariationIdToConsequencesMap.get(currentVariationId).addAll(consequenceItemIdSet);
        }
    }

    LOG.info("Finished " + counter + " rows total, stored " + snpCounter + " SNPs for chr " + chrName);
    LOG.info("storedSnpRsNumberToInterMineIdMap.size() = " + storedSnpVariationIdToInterMineIdMap.size());
    LOG.info("Consequence count: " + consequenceCounter);
    LOG.info("Consequence types (consequence type to count) without transcript on Chromosome " + chrName + " : "
            + nonTranscriptConsequences);
}

From source file:morphy.command.LLoginsCommand.java

public void process(String arguments, UserSession userSession) {
    /* Sun Aug  7, 12:00 MDT 2011: GuestGYKQ(U)         logout */

    boolean empty = StringUtils.isEmpty(arguments);
    boolean numeric = StringUtils.isNumeric(arguments);

    int limit = 10; //200
    arguments = arguments.trim();//  www.jav  a  2  s .co  m
    if (empty) {
        limit = 10;
    } else if (numeric && !empty) {
        limit = Integer.parseInt(arguments);
    } else if (!numeric && !empty) {
        userSession.send(getContext().getUsage());
        return;
    }

    boolean isAdmin = UserService.getInstance().isAdmin(userSession.getUser().getUserName());
    StringBuilder b = new StringBuilder();

    final java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE MMM dd, HH:mm z yyyy");

    int count = 0;
    String query = "SELECT COUNT(*) FROM `logins`";
    ResultSet rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    try {
        if (rs.next()) {
            count = rs.getInt(1);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }

    if (limit > count)
        limit = count;

    query = "SELECT `id` FROM `logins` ORDER BY `id` DESC LIMIT " + limit;
    rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    int[] arr = new int[limit];
    try {
        int index = 0;
        while (rs.next()) {
            arr[index++] = rs.getInt(1);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }
    java.util.Arrays.sort(arr);

    Map<String, Boolean> registeredCache = new HashMap<String, Boolean>();

    query = "SELECT `id`,`username`,CONVERT_TZ(`timestamp`,'UTC','SYSTEM'),`type`"
            + (isAdmin ? ",`ipAddress`" : "") + " FROM logins WHERE "
            + MessagesCommand.formatIdListForQuery("id", arr) + " ORDER BY id ASC";
    rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    try {
        while (rs.next()) {
            String line = "";
            String username = rs.getString(2);
            if (!registeredCache.containsKey(username.toLowerCase())) {
                boolean registered = UserService.getInstance().isRegistered(username);
                if (!registered)
                    username += "(U)";
                registeredCache.put(username.toLowerCase(), registered);
            } else /* we have cached information about whether this user is registered */ {
                boolean registered = registeredCache.get(username.toLowerCase());
                if (!registered)
                    username += "(U)";
            }

            if (!isAdmin)
                line = String.format("%26s: %-20s %s", sdf.format(rs.getTimestamp(3).getTime()), username,
                        rs.getString(4));
            if (isAdmin)
                line = String.format("%26s: %-20s %7s from %s", sdf.format(rs.getTimestamp(3).getTime()),
                        username, rs.getString(4), rs.getString(5));
            if (rs.next()) {
                line += "\n";
                rs.previous();
            }
            b.append(line);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }

    userSession.send(b.toString());
    return;

    /*UserSession uS = null;
    String[] array = UserService.getInstance().completeHandle(arguments);
    if (array.length == 0) {
       userSession.send(arguments + " is not logged in.");
       return;
    }
    if (array.length > 1) {
       StringBuilder b = new StringBuilder();
       b.append("-- Matches: " + array.length + " player(s) --\n");
       for(int i=0;i<array.length;i++) {
    b.append(array[i] + "  ");
       }
       userSession.send(b.toString());
       return;
    }
    uS = UserService.getInstance().getUserSession(array[0]);
    */
}

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

/**
 * Produce a JDOM Element for an instance of Results object.
 * <br>//from w w  w.j  a v a 2s . c  o m
 * @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);
}