Example usage for java.sql ResultSet getRow

List of usage examples for java.sql ResultSet getRow

Introduction

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

Prototype

int getRow() throws SQLException;

Source Link

Document

Retrieves the current row number.

Usage

From source file:com.snowy.data.java

public ArrayList<ArrayList<String>> retriveChallenges() {
    ArrayList<ArrayList<String>> res = new ArrayList<>();
    try {// w  ww  .  java  2s.com

        String uname = this.getUsernameFromToken();
        PreparedStatement ps = con.prepareStatement(
                "select requestor,requested,timestamp,accepted,RequestId from gamerequest where requestor = (select user_id from users where Username=?) or requested = (select user_id from users where Username=?) and timestamp >subdate(current_timestamp, interval 2 hour)");
        ps.setString(1, uname);
        ps.setString(2, uname);
        //PreparedStatement pss =con.prepareStatement("select Username from users where user_id=?");

        ResultSet rs = ps.executeQuery();
        rs.last();
        if (rs.getRow() > 0) {
            rs.beforeFirst();
            while (rs.next()) {

                ArrayList<String> al = new ArrayList<>();
                al.add(this.getUsernameFromId(rs.getInt("requestor")));
                al.add(this.getUsernameFromId(rs.getInt("requested")));
                al.add(String.valueOf(rs.getTimestamp("timestamp").getTime()));
                al.add(rs.getInt("accepted") + "");
                //al.add(rs.getInt("gameCreated")+"");
                al.add(rs.getInt("RequestId") + "");
                res.add(al);
            }
        }
        //ps.close();
        //rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}

From source file:com.snowy.data.java

public String createUser(String username, String password, String email) {

    String responce = "";
    try {/* w  ww. j a  v a 2  s. com*/
        PreparedStatement ps = con.prepareStatement("select * from users where Username =?");
        ps.setString(1, username);
        ResultSet rs = ps.executeQuery();
        rs.last();
        if (rs.getRow() == 0) {

            ps = con.prepareStatement("select * from users where Email=?");
            ps.setString(1, email);
            rs = ps.executeQuery();
            rs.last();
            if (rs.getRow() == 0) {
                ps = con.prepareStatement(
                        "insert into users (Username,Password,Email,timeoutTime) values (?,?,?,0)");
                ps.setString(1, username);
                ps.setString(2, PasswordHash.createHash(password));
                ps.setString(3, email);
                if (ps.executeUpdate() == 1) {
                    return "Creation Sucess";
                } else {
                    return "Creation Failure";
                }
            } else {
                responce = "Email Exists";
            }
        } else {
            responce = "Username Exists";
        }
        //ps.close();
        //rs.close();
    } catch (SQLException | PasswordHash.CannotPerformOperationException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }

    return responce;
}

From source file:com.chiorichan.database.DatabaseEngine.java

public int getRowCount(ResultSet rs) {
    try {/*ww  w. j av a 2 s .co  m*/
        // int curRow = rs.getRow();
        rs.last();
        int lastRow = rs.getRow();
        rs.first(); // TODO: Set the row???
        return lastRow;
    } catch (Exception e) {
        return 0;
    }
}

From source file:ca.on.gov.jus.icon.common.iconcodetables.IconCodeTablesManager.java

private IconCodeTable getICONCodesTableList() {
    IconCodeTable iconCodesTableList = null;
    String selectSql = null;//ww  w. j a  v a2s  .co m
    Connection oracleConnection = ReportsConnectionManager.getPooledOracleConnection();
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    if (null != oracleConnection) {
        selectSql = "" + "SELECT " + "    ICONADMIN.ICON_TABLES_CODE.CODE, "
                + "    ICONADMIN.ICON_TABLES_CODE.DESCRIPTION, " + "    ICONADMIN.ICON_TABLES_CODE.TABLE_PASS  "
                + "FROM  " + "    ICONADMIN.ICON_TABLES_CODE " + "ORDER BY  "
                + "    ICONADMIN.ICON_TABLES_CODE.DESCRIPTION ASC ";

        try {

            preparedStatement = oracleConnection.prepareStatement(selectSql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            resultSet = preparedStatement.executeQuery();

            resultSet.last();
            int resultSetCount = resultSet.getRow();
            //logger.info("resultSetCount: " + resultSetCount);
            resultSet.beforeFirst();

            if (resultSetCount > 0) {
                iconCodesTableList = new IconCodeTable("ICON_CodeTablesList", "ICON Codes Table List");
            }

            while (resultSet.next()) {
                IconCodeTable iconCodeTable = new IconCodeTable(resultSet.getString("CODE"),
                        resultSet.getString("DESCRIPTION"));
                iconCodeTable.setCodeTablePass(resultSet.getString("TABLE_PASS"));

                //Null it so that it can not be used that way
                iconCodeTable.setCodeTableValues(null);

                iconCodesTableList.getCodeTableValues().put(resultSet.getString("CODE"), iconCodeTable);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                //clean up
                if (null != resultSet) {
                    resultSet.close();
                    resultSet = null;
                }
                if (null != preparedStatement) {
                    preparedStatement.close();
                    preparedStatement = null;
                }
                //Should never close the pooled connection
                //               if(null != oracleConnection){ 
                //                  oracleConnection.close();
                //                  oracleConnection = null;
                //               }
            } catch (SQLException e1) {
            }
        }
    }

    return iconCodesTableList;
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static Document addResultSetXmlPart(Element resultsElement, ResultSet rs, Document xmlDocumentResult)
        throws SQLException {
    // resultSet = statement.getResultSet();
    // connection to an ACCESS MDB
    ResultSetMetaData rsmd = rs.getMetaData();
    Element resultSetElement = xmlDocumentResult.createElement("ResultSet");

    resultSetElement.setAttribute("fetchSize", String.valueOf(rs.getFetchSize()));
    resultsElement.appendChild(resultSetElement);

    int colCount = rsmd.getColumnCount();
    while (rs.next()) {
        Element rowElement = xmlDocumentResult.createElement("Row");
        rowElement.setAttribute("rowNumber", String.valueOf(rs.getRow()));

        resultsElement.appendChild(rowElement);
        for (int ii = 1; ii <= colCount; ii++) {
            String columnName = "";
            if (!StringUtils.isBlank(rsmd.getTableName(ii))) {
                columnName += (rsmd.getTableName(ii)).toUpperCase() + ".";
            }//from   w w  w.  j a  va  2 s  .  c o m
            columnName += (rsmd.getColumnName(ii)).toUpperCase();
            String value = rs.getString(ii);
            Element node = xmlDocumentResult.createElement(createXmlName(columnName));
            if (!StringUtils.isBlank(value)) {
                Text textNode = xmlDocumentResult.createTextNode(value.toString());
                node.appendChild(textNode);
            }
            rowElement.appendChild(node);
        }
        resultSetElement.appendChild(rowElement);
    }
    return xmlDocumentResult;
}

From source file:com.github.heartsemma.enderauth.Database.java

/**@param uuid (Universally Unique Identifier)
 * @return A boolean/* ww w .  j  a  va  2s .c  o m*/
 * 
 * <br><Br>Returns true if there is an entry in the User Table with a uuid matching the parameter. 
 * <br>Returns false if there is not.
 * 
 * @throws SQLException The function uses PreparedStatements to ask about the presence of the UUID in the User Table.
 * @throws DatabaseException If the returned ResultSet from the SELECT command is completely empty (that is, lacking even the names of the columns in the table), the function throws a DatabaseException.*/
public boolean isInDatabase(byte[] uuid) throws SQLException, DatabaseException {
    logger.debug("Attempting to determine presence of user " + new String(uuid) + " in the database.");

    String isInDatabaseCommand = "SELECT * FROM ? WHERE ? = ?";

    ArrayList<Object> isInDatabaseVariables = new ArrayList<Object>();

    isInDatabaseVariables.add(1, userTableName);
    isInDatabaseVariables.add(2, userTableIDColumn);
    isInDatabaseVariables.add(3, uuid);

    //Command should look something like: SELECT * FROM ea_users WHERE id == uuid

    ResultSet selection = transact(isInDatabaseCommand, isInDatabaseVariables);

    logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + ".");

    logger.debug("Error Checking...");
    Preconditions.checkNotNull(selection);

    //ResultSet Analysis + Error Checking
    if (selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet.
        logger.error("EnderAuth attempted to find if there was a uuid matching " + new String(uuid)
                + " in the database but was unable to run the necessary SQL queries.");
        logger.error(
                "There were no rows in the returned table of data after running the MySql 'PreparedStatement'.");
        throw new DatabaseException("Returned ResultSet in isPresent(String uuid) contained no rows.");
    }

    selection.last();

    if (selection.getRow() == 1) { //There are no entries in the ResultSet.
        logger.debug("No entries for user " + new String(uuid) + " were found in the ResultSet.");
        return false;

    } else { //There is one or more entries with the matching uuid.
        logger.debug("User " + new String(uuid) + " was found in the database.");
        return true;
    }

}

From source file:com.snowy.data.java

public boolean login(String username, String password) {

    //Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, con.toString());
    boolean b = false;
    try {//  w w w. j av  a 2 s .co  m
        PreparedStatement s = con.prepareStatement("select Username,Password from users where Username = ?");
        s.setString(1, username);
        ResultSet rs = s.executeQuery();
        rs.last();
        //srs = template.queryForRowSet("select Username,Password from tempuser where Username = ?", username);
        //srs.last();
        if (rs.getRow() >= 1) {
            b = PasswordHash.verifyPassword(password.trim(), rs.getString("Password").trim());

        } else {
            b = false;
        }
        //s.close();
        //rs.close();
    } catch (PasswordHash.InvalidHashException | SQLException
            | PasswordHash.CannotPerformOperationException ex) {
        b = false;
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }

    return b;
}

From source file:com.github.heartsemma.enderauth.Database.java

/**
 * @param uuid (Universally Unique Identifier)
 * @return The Pre-Shared Key of the user for their TOTP authentication.
 * // w w  w.j  av  a 2 s  . c  o  m
 * <br><br>Returns the TOTP Pre-Shared Key connected with the specified UUID.
 * <br>Returns null if unable to retrieve the key (if not found or  
 * 
 * @throws SQLException This function accesses the database via a "SELECT" query.
 * @throws DatabaseException Thrown if the returned ResultSet contains missing or what should be erroneous data.
 */
public String getTotpKey(byte[] uuid) throws SQLException, DatabaseException {
    logger.debug("Attempting to retrieve TOTP PSK for user " + new String(uuid) + ".");

    String getKeyCommand = "SELECT ? FROM ? WHERE ? == ?";

    ArrayList<Object> getKeyVariables = new ArrayList<Object>();
    getKeyVariables.add(userTableTotpPSKColumn);
    getKeyVariables.add(userTableName);
    getKeyVariables.add(userTableIDColumn);
    getKeyVariables.add(uuid);

    ResultSet selection = transact(getKeyCommand, getKeyVariables);

    logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + ".");

    //There should be one String in this resultset, but we will check it good because EnderAuth is stronk, EnderAuth is reliable.
    logger.debug("Error checking...");
    Preconditions.checkNotNull(selection);

    if (!selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet.
        logger.error("EnderAuth attempted to retrieve " + new String(uuid)
                + "'s PSK from the database but was unable to find it.");
        logger.error(
                "There were no rows in the returned table of data after running the MySql 'PreparedStatement' .");

        throw new DatabaseException("getTotpKey()'s PreparedStatement returned a ResultSet that had no data.");
    }

    selection.last();

    if (selection.getRow() == 1) { //There was no entry for this user.
        logger.error("EnderAuth attempted to retrieve " + new String(uuid)
                + "'s PSK from the database but was unable to find it.");
        logger.error("Does " + new String(uuid) + " have an entry in the " + userTableName + " table?");

        //Returns null because we were unable to get the required data.
        throw new UUIDNotFoundException(
                "getTotpKey() was unable to find the entry in the database with the specified UUID.");

    } else if (selection.getRow() == 2) { //There was one entry for this user
        //If we get to this point, everything looks tight.   
        logger.debug("Successfully retrieved PSK from user " + new String(uuid) + ".");

        String PSK = selection.getString(userTableTotpPSKColumnIndex);
        return PSK;

    } else { //There was more than one entry for this user.
        logger.error("EnderAuth searched for " + new String(uuid)
                + "'s PSK and found multiple entries for that user in the database.");
        logger.error(
                "This should not have happened and indicates either plugin glitches or malcious database tampering.");

        throw new DatabaseException("Multiple entries matching the specified UUID were found in the database.");
    }
}

From source file:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java

@Override
public void onBeforeRender() {
    super.onBeforeRender();

    Connection jdbcConnection = null;
    try {//  www.j a  va  2  s  .  c om
        if (report == null)
            throw new Exception("No report given to render diagram");

        jdbcConnection = DatabaseUtils.getDatabaseConnection(report.getDataSource());
        ResultSet resultSet = DatabaseUtils.getResultSet(jdbcConnection, report.getStatement(), parameters);

        ResultSetMetaData metaData = resultSet.getMetaData();
        JFreeChart chart = null;
        resultSet.beforeFirst();

        // Line chart - 1 numeric value
        if (report.getDiagram() == 0) {
            if (metaData.getColumnCount() != 1)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.1numvalues")
                                .wrapOnAssignment(this).getObject());

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            while (resultSet.next())
                dataset.addValue(resultSet.getDouble(1), metaData.getColumnName(1),
                        String.valueOf(resultSet.getRow()));

            chart = ChartFactory.createLineChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    new ResourceModel("dashboard.report.reportdiagram.image.row-label").wrapOnAssignment(this)
                            .getObject(),
                    metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true);

            // XY Series chart - 2 numeric values
        } else if (report.getDiagram() == 1) {
            if (metaData.getColumnCount() != 2)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.2numvalues")
                                .wrapOnAssignment(this).getObject());

            XYSeries series = new XYSeries(metaData.getColumnName(1) + " / " + metaData.getColumnName(2));
            while (resultSet.next())
                series.add(resultSet.getDouble(1), resultSet.getDouble(2));

            chart = ChartFactory.createXYLineChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    metaData.getColumnName(1), metaData.getColumnName(2), new XYSeriesCollection(series),
                    PlotOrientation.VERTICAL, true, true, true);

            // Category chart - 1 numeric value, 1 comparable value
        } else if (report.getDiagram() == 2) {
            if (metaData.getColumnCount() != 2)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values")
                                .wrapOnAssignment(this).getObject());

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            while (resultSet.next())
                dataset.setValue(resultSet.getDouble(1),
                        metaData.getColumnName(1) + " / " + metaData.getColumnName(2), resultSet.getString(2));

            chart = new JFreeChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    new CategoryPlot(dataset, new LabelAdaptingCategoryAxis(14, metaData.getColumnName(2)),
                            new NumberAxis(metaData.getColumnName(1)), new CategoryStepRenderer(true)));

            // Pie chart - 1 numeric value, 1 comparable value (used as category)
        } else if ((report.getDiagram() == 3) || (report.getDiagram() == 4)) {
            if (metaData.getColumnCount() != 2)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values")
                                .wrapOnAssignment(this).getObject());

            DefaultPieDataset dataset = new DefaultPieDataset();
            while (resultSet.next())
                dataset.setValue(resultSet.getString(2), resultSet.getDouble(1));

            if (report.getDiagram() == 3)
                // Pie chart 2D
                chart = ChartFactory
                        .createPieChart(new ResourceModel("dashboard.report.reportdiagram.image.label")
                                .wrapOnAssignment(this).getObject(), dataset, true, true, true);
            else if (report.getDiagram() == 4) {
                // Pie chart 3D
                chart = ChartFactory
                        .createPieChart3D(new ResourceModel("dashboard.report.reportdiagram.image.label")
                                .wrapOnAssignment(this).getObject(), dataset, true, true, true);
                ((PiePlot3D) chart.getPlot()).setForegroundAlpha(
                        Float.valueOf(new ResourceModel("dashboard.report.reportdiagram.image.alpha")
                                .wrapOnAssignment(this).getObject()));
            }

            // Bar chart - 1 numeric value, 2 comparable values (used as category, series)
        } else if (report.getDiagram() == 5) {
            if ((metaData.getColumnCount() != 2) && (metaData.getColumnCount() != 3))
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.3values")
                                .wrapOnAssignment(this).getObject());

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            while (resultSet.next())
                dataset.setValue(resultSet.getDouble(1), resultSet.getString(2),
                        resultSet.getString(metaData.getColumnCount()));

            chart = ChartFactory.createBarChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    metaData.getColumnName(2), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL,
                    true, true, true);
        }

        int[] winSize = DashboardCfgDelegate.getInstance().getWindowSize("reportDiagramImage");
        addOrReplace(new JFreeChartImage("diagram", chart, winSize[0], winSize[1]));

        final JFreeChart downloadableChart = chart;
        addOrReplace(new Link<Object>("diagram-download") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick() {

                RequestCycle.get().setRequestTarget(new IRequestTarget() {

                    public void respond(RequestCycle requestCycle) {

                        WebResponse wr = (WebResponse) requestCycle.getResponse();
                        wr.setContentType("image/png");
                        wr.setHeader("content-disposition", "attachment;filename=diagram.png");

                        OutputStream os = wr.getOutputStream();
                        try {
                            ImageIO.write(downloadableChart.createBufferedImage(800, 600), "png", os);
                            os.close();
                        } catch (IOException e) {
                            log.error(this.getClass().toString() + ": " + "respond: " + e.getMessage());
                            log.debug("Exception: ", e);
                        }
                        wr.close();
                    }

                    @Override
                    public void detach(RequestCycle arg0) {
                    }
                });
            }
        }.add(new Image("diagram-download-image", ImageManager.IMAGE_DASHBOARD_REPORT_DOWNLOAD)
                .add(new ImageSizeBehaviour())
                .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.downloadlink"))));

        addOrReplace(new Image("diagram-print-image", ImageManager.IMAGE_DASHBOARD_REPORT_PRINT)
                .add(new ImageSizeBehaviour())
                .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.printbutton")));

        addOrReplace(new Label("error-message", "").setVisible(false));
        addOrReplace(new Label("error-reason", "").setVisible(false));
    } catch (Exception e) {
        log.error("Exception: " + e.getMessage());

        addOrReplace(((DynamicDisplayPage) this.getPage()).new PlaceholderLink("diagram-download")
                .setVisible(false));
        addOrReplace(new Image("diagram-print-image").setVisible(false));
        addOrReplace(new Image("diagram").setVisible(false));
        addOrReplace(new Label("error-message",
                new ResourceModel("dashboard.report.reportdiagram.statement.error").wrapOnAssignment(this)
                        .getObject())
                                .add(new AttributeModifier("class", true, new Model<String>("message-error"))));
        addOrReplace(new Label("error-reason", e.getMessage())
                .add(new AttributeModifier("class", true, new Model<String>("message-error"))));
        log.debug(getClass() + ": ", e);
    } finally {
        try {
            jdbcConnection.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.opensoc.enrichment.adapters.geo.GeoMysqlAdapter.java

@SuppressWarnings("unchecked")
@Override//from w w w.  jav  a 2  s .c o  m
public JSONObject enrich(String metadata) {

    ResultSet resultSet = null;

    try {

        _LOG.trace("[OpenSOC] Received metadata: " + metadata);

        InetAddress addr = InetAddress.getByName(metadata);

        if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress()
                || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) {
            _LOG.trace("[OpenSOC] Not a remote IP: " + metadata);
            _LOG.trace("[OpenSOC] Returning enrichment: " + "{}");

            return new JSONObject();
        }

        _LOG.trace("[OpenSOC] Is a valid remote IP: " + metadata);

        statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS";
        resultSet = statement.executeQuery(locid_query);

        if (resultSet == null)
            throw new Exception(
                    "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query);

        resultSet.last();
        int size = resultSet.getRow();

        if (size == 0)
            throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query);

        resultSet.beforeFirst();
        resultSet.next();

        String locid = null;
        locid = resultSet.getString("ANS");

        if (locid == null)
            throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query);

        String geo_query = "select * from location where locID = " + locid + ";";
        resultSet = statement.executeQuery(geo_query);

        if (resultSet == null)
            throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid
                    + ". Query run was: " + geo_query);

        resultSet.last();
        size = resultSet.getRow();

        if (size == 0)
            throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid
                    + ". Query run was: " + geo_query);

        resultSet.beforeFirst();
        resultSet.next();

        JSONObject jo = new JSONObject();
        jo.put("locID", resultSet.getString("locID"));
        jo.put("country", resultSet.getString("country"));
        jo.put("city", resultSet.getString("city"));
        jo.put("postalCode", resultSet.getString("postalCode"));
        jo.put("latitude", resultSet.getString("latitude"));
        jo.put("longitude", resultSet.getString("longitude"));
        jo.put("dmaCode", resultSet.getString("dmaCode"));
        jo.put("locID", resultSet.getString("locID"));

        jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude"));

        _LOG.debug("Returning enrichment: " + jo);

        return jo;

    } catch (Exception e) {
        e.printStackTrace();
        _LOG.error("Enrichment failure: " + e);
        return new JSONObject();
    }
}