Example usage for java.sql ResultSet first

List of usage examples for java.sql ResultSet first

Introduction

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

Prototype

boolean first() throws SQLException;

Source Link

Document

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

Usage

From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson6a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from ww w .j a va2  s.co  m
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";

        try {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet results = statement.executeQuery(query);

            if ((results != null) && (results.first() == true)) {
                ResultSetMetaData resultsMetaData = results.getMetaData();
                StringBuffer output = new StringBuffer();

                output.append(writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 6) {
                    return trackProgress(AttackResult.success("You have succeed: " + output.toString()));
                } else {
                    return trackProgress(AttackResult.failed("You are close, try again. " + output.toString()));
                }

            } else {
                return trackProgress(AttackResult.failed("No Results Matched. Try Again. "));

            }
        } catch (SQLException sqle) {

            return trackProgress(AttackResult.failed(sqle.getMessage()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(
                AttackResult.failed("ErrorGenerating" + this.getClass().getName() + " : " + e.getMessage()));
    }
}

From source file:org.cerberus.refactor.TestcaseList.java

/**
 * Processes requests for both HTTP//ww  w . ja v a2 s.  co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    DatabaseSpring db = appContext.getBean(DatabaseSpring.class);
    Connection conn = db.connect();
    PreparedStatement stmt_testlist = null;
    try {

        String application = request.getParameter("application");
        String app = "";
        String test = request.getParameter("test");
        String tes = "";
        String url = request.getParameter("url");

        if ((StringUtils.isNotBlank(application)) && !(application.equals("all"))) {
            app = " and application = '" + application + "'";
        } else {
            app = "";
        }

        if ((StringUtils.isNotBlank(test)) && !(test.equals("all"))) {
            tes = " and test = '" + test + "'";
        } else {
            tes = "";
        }

        if (StringUtils.isNotBlank(url)) {
            stmt_testlist = conn.prepareStatement("SELECT concat(?) AS list FROM testcase "
                    + " WHERE TcActive = 'Y'  AND `Group` = 'AUTOMATED' ? ? ORDER BY test,testcase");
            stmt_testlist.setString(1, url);
            stmt_testlist.setString(2, app);
            stmt_testlist.setString(3, tes);
            ResultSet rs_testlist = stmt_testlist.executeQuery();
            int id = 0;

            if (rs_testlist.first()) {
                do {

                    out.println(rs_testlist.getString("list"));

                } while (rs_testlist.next());

            }
            rs_testlist.close();
            stmt_testlist.close();
        }
    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        out.close();
        try {
            conn.close();
        } catch (Exception ex) {
            MyLogger.log(TestcaseList.class.getName(), Level.INFO,
                    "Exception closing ResultSet: " + ex.toString());
        }
        try {
            if (stmt_testlist != null) {
                stmt_testlist.close();
            }
        } catch (SQLException ex) {
            MyLogger.log(TestcaseList.class.getName(), Level.INFO,
                    "Exception closing PreparedStatement: " + ex.toString());
        }
    }

}

From source file:com.bc.fiduceo.db.AbstractDriver.java

Integer getSensorId(String sensorName) throws SQLException {
    final Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    final ResultSet resultSet = statement
            .executeQuery("SELECT ID FROM SENSOR WHERE NAME = '" + sensorName + "'");

    if (resultSet.first()) {
        return resultSet.getInt("ID");
    } else {// w w  w.  j av  a2 s  . c o  m
        return null;
    }
}

From source file:com.versatus.jwebshield.securitylock.SecurityLockService.java

private SecurityLock checkSecurityLock(int userId, String ip) throws SQLException {

    logger.debug("checkAccountLock: userid=" + userId);
    logger.debug("checkAccountLock: ip=" + ip);

    SecurityLock res;//from w  ww.j a  v a 2  s. c  o  m
    Object[] params = new Object[] { userId, ip };

    QueryRunner run = new QueryRunner();
    Connection conn = dbHelper.getConnection();
    BeanHandler<SecurityLock> rsh = new BeanHandler(SecurityLock.class) {

        @Override
        public SecurityLock handle(ResultSet rs) throws SQLException {
            SecurityLock brp = null;
            if (rs.first()) {
                brp = new BasicRowProcessor().toBean(rs, SecurityLock.class);
            }
            return brp;
        }
    };

    try {

        res = run.query(conn, lockCheckSql, rsh, params);

        logger.debug("checkAccountLock: response=" + res);

        if (res != null) {
            if (res.isLock()) {
                logger.debug("checkAccountLock: Calendar.getInstance()=" + Calendar.getInstance().getTime());
                logger.debug("checkAccountLock: TimeWhenUnlock()=" + res.getTimeWhenUnlock());
                logger.debug("checkAccountLock: is time to ulock="
                        + Calendar.getInstance().getTime().after(res.getTimeWhenUnlock()));
                if (Calendar.getInstance().getTime().after(res.getTimeWhenUnlock())) {
                    logger.info("unlocking IP " + res.getIp());
                    int r = run.update(conn, resetLockSql, new Object[] { ip });

                    logger.debug("checkAccountLock: reset response=" + r);

                    res = run.query(conn, lockCheckSql, rsh, params);

                    logger.debug("checkAccountLock: after reset response=" + res);
                }
            }

        } else {
            res = new SecurityLock();
            res.setLock(false);
        }

    } finally {

        try {
            DbUtils.close(conn);
        } catch (SQLException e) {
            // ignore
        }
    }

    return res;
}

From source file:ua.aits.crc.model.ProjectModel.java

public String deleteProject(String id) throws SQLException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, IOException {
    ResultSet result = DB.getResultSet(
            "SELECT projects.project_category FROM projects WHERE projects.project_id = " + id + ";");
    result.first();
    DB.runQuery("UPDATE `projects` SET `project_is_delete`= 1 WHERE project_id = " + id + ";");
    String category = result.getString("project_category");
    DB.closeCon();//  ww w .  j a  v  a  2 s. c o m
    return category;
}

From source file:org.rhq.plugins.mysql.MySqlTableComponent.java

@Override
public AvailabilityType getAvailability() {
    AvailabilityType result = AvailabilityType.DOWN;
    Connection conn = parent.getConnection();
    if (conn != null) {
        Statement stmt = null;/*from  w ww.j a  v a 2  s .  c o  m*/
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("show tables from " + databaseName + " like '" + tableName + "'");
            if (rs.first()) {
                result = AvailabilityType.UP;
            }
        } catch (SQLException se) {
            // ignore as unablailable if we can't execute the query
        } finally {
            DatabaseQueryUtility.close(stmt, rs);
        }
    }
    return result;
}

From source file:ua.aits.crc.model.ProjectModel.java

public ProjectModel getProjectByID(String id) throws SQLException, ClassNotFoundException,
        InstantiationException, IllegalAccessException, ParseException {
    ResultSet result = DB.getResultSet(
            "SELECT * FROM projects WHERE projects.project_id = " + id + " AND projects.project_is_delete = 0");
    result.first();
    ProjectModel temp = new ProjectModel();
    temp.setProject_id(result.getInt("project_id"));
    temp.setProject_name_en(result.getString("project_name_en").replace("\"", "&quot;"));
    temp.setProject_name_ua(result.getString("project_name_ua").replace("\"", "&quot;"));
    temp.setProject_text_en(result.getString("project_text_en"));
    temp.setProject_text_ua(result.getString("project_text_ua"));
    temp.setProject_text_avatar_ua(result.getString("project_text_avatar_ua"));
    temp.setProject_text_avatar_en(result.getString("project_text_avatar_en"));
    temp.setProject_avatar(result.getString("project_avatar"));
    temp.setProject_category(result.getInt("project_category"));
    DB.closeCon();/*from   www.jav a2 s .c  o  m*/
    return temp;
}

From source file:utilities.DonationManager.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   www  .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 {

    String encodedAmount = request.getParameter("amount");
    String encodedCharityID = request.getParameter("charity_id");
    String articleID = ("undefined".equals(request.getParameter("article_id").toString())) ? "0"
            : request.getParameter("article_id");

    //Base64 decode the paramaters that are passed back. This encoding was to offer
    //increased security. In real life deployment, this method would have to involve a more complex cipher
    //for strongerv security 
    byte[] decodedAmountBytes = Base64.decodeBase64(encodedAmount);
    byte[] decodedCharityIDBytes = Base64.decodeBase64(encodedCharityID);

    System.out.println(decodedAmountBytes.toString());

    String amountString = new String(decodedAmountBytes);
    int amount = 0;
    if (amountString.contains(".")) {
        amount = (int) Math.round(Double.valueOf(amountString));
    } else {
        amount = Integer.valueOf(amountString);
    }
    int charityID = Integer.valueOf(new String(decodedCharityIDBytes));

    if (DEBUG_ON) {
        System.out.println("Amount: " + amount);
        System.out.println("Charity ID: " + charityID);
    }

    //Connect to Database
    DBConnect dbConnect = new DBConnect();
    Connection connection = dbConnect.getConnection();

    String insertNewDonation = "INSERT INTO donations (charity_id, amount)" + "VALUES (?,?)";

    try (PreparedStatement insertDonationStatement = connection.prepareStatement(insertNewDonation)) {
        insertDonationStatement.setInt(1, charityID);
        insertDonationStatement.setInt(2, amount);
        insertDonationStatement.executeUpdate();
    } catch (SQLException e) {
        System.err.println(this.getClass().getName()
                + " : INSERT Statement failed, either charity_id or amounr entered in error");
        e.printStackTrace();
    }

    String selectCharityName = "SELECT name " + "FROM charities " + "WHERE id = ?";

    String charityName = "";
    try (PreparedStatement selectCharityNameStatement = connection.prepareStatement(selectCharityName)) {
        selectCharityNameStatement.setInt(1, charityID);
        ResultSet charityNameResultSet = selectCharityNameStatement.executeQuery();

        if (charityNameResultSet.first()) {
            charityName = charityNameResultSet.getString(1);
        }
    } catch (SQLException ex) {
        System.err
                .println(this.getClass().getName() + " : Select Statement failed, no name matches charity_id");
        ex.printStackTrace();
    }

    //If it's a Sponsorship donation
    if (!"0".equals(articleID)) {
        String insertSponsorship = "INSERT INTO sponsorships (charity_id, amount, article_id) "
                + "VALUES (?,?,?)";

        try (PreparedStatement insertSponsorshipStatement = connection.prepareStatement(insertSponsorship)) {
            insertSponsorshipStatement.setInt(1, charityID);
            insertSponsorshipStatement.setInt(2, amount);
            insertSponsorshipStatement.setInt(3, Integer.valueOf(articleID));
            insertSponsorshipStatement.executeUpdate();

        } catch (SQLException ex) {
            System.err.println(this.getClass().getName() + " : Insert Sponsorship Statement failed ");
            ex.printStackTrace();
        }

    }

    //Close the Connection
    try {
        connection.close();
    } catch (SQLException ex) {
        Logger.getLogger(DonationManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    if ("".equals(charityName)) {
        //Redirect to Homepage
        response.sendRedirect("Homepage");
    } else {
        //Redirect to Charity's homepage with a Thank
        response.sendRedirect(request.getContextPath() + "/charities/"
                + DirectoryManager.toLowerCaseAndTrim(charityName) + "/index.html");
    }

}

From source file:com.ianzepp.logging.jms.service.BasicDaoTest.java

/**
 * TODO Method description for <code>testSaveEvent()</code>
 * /*w  ww  . j a v a 2 s  .  c o  m*/
 * @throws Exception
 */
@Test
public final void testSaveEvent() throws Exception {
    // Save the id first
    HashMap<String, Object> paramMap = newInitializedEventMap(UUID.randomUUID());

    // Run the save
    assertTrue(newInitializedInstance().executeQuery("InsertEvent", paramMap) > 0);

    // Test the result
    String statementSql = "SELECT * FROM \"Event\" WHERE \"Id\" = '" + paramMap.get("Id") + "'";
    Statement statement = getConnection().createStatement();

    // Check the query
    assertTrue(statement.execute(statementSql));

    // Check the result set
    ResultSet resultSet = statement.getResultSet();

    assertTrue("No result set data was returned.", resultSet.first());

    for (String columnName : paramMap.keySet()) {
        assertEquals(paramMap.get(columnName), resultSet.getString(columnName));
    }

    assertFalse("Too many results were returned", resultSet.next());
}

From source file:org.kuali.kpme.core.block.dao.CalendarBlockDaoJdbcImpl.java

@Override
public DateTime getLatestEndTimestampForEarnCode(String earnCode, String calendarBlockType) {

    PreparedStatementCreator timeBlockPSC = new PreparedStatementCreator() {

        @Override//  ww  w.ja va 2  s  .  com
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT max(end_ts) ");
            sql.append("FROM tk_time_block_t ");
            sql.append("WHERE earn_code = ?");

            String query = sql.toString();

            return conn.prepareStatement(query);
        }
    };

    PreparedStatementCreator leaveBlockPSC = new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT max(end_ts) ");
            sql.append("FROM lm_leave_block_t ");
            sql.append("WHERE earn_code = ?");

            String query = sql.toString();

            return conn.prepareStatement(query);
        }
    };
    try {
        PreparedStatement statement = null;
        if (StringUtils.equals(calendarBlockType, "Time")) {
            statement = timeBlockPSC.createPreparedStatement(this.getDataSource().getConnection());
        } else if (StringUtils.equals(calendarBlockType, "Leave")) {
            statement = leaveBlockPSC.createPreparedStatement(this.getDataSource().getConnection());
        } else {
            throw new IllegalArgumentException("calendarBlockType must be one of 'Time' or 'Leave'");
        }
        if (statement != null) {
            statement.setString(1, earnCode);
        }

        ResultSet rs = statement.executeQuery();
        if (rs != null) {
            boolean empty = !rs.first();
            Timestamp maxDate = rs.getTimestamp("max(end_ts)");
            if (maxDate == null) {
                return null;
            } else {
                return new DateTime(maxDate.getTime());
            }
        }
    } catch (SQLException e) {
        LOG.warn("error creating or executing sql statement");
        throw new RuntimeException();
    }
    return null;
}