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.kuali.kpme.core.block.dao.CalendarBlockDaoJdbcImpl.java

@Override
public DateTime getLatestEndTimestampForAssignment(Assignment assignment, String calendarBlockType) {

    PreparedStatementCreator timeBlockPSC = new PreparedStatementCreator() {

        @Override/*w  w  w .ja va  2  s. c o m*/
        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 principal_id = ? AND job_number=? AND task=? AND work_area=?");

            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 principal_id = ? AND job_number=? AND task=? AND work_area=?");

            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, assignment.getPrincipalId());
            statement.setString(2, assignment.getJobNumber().toString());
            statement.setString(3, assignment.getTask().toString());
            statement.setString(4, assignment.getWorkArea().toString());
        }

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

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

public AvailabilityType getAvailability() {
    AvailabilityType result = AvailabilityType.DOWN;
    Connection conn = getConnection();
    ResultSet rs = null;
    Statement stmt = null;//from www  . j  a  va2 s.  c  om
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(
                "select User from mysql.user where User='" + userName + "' and Host='" + host + "'");
        if (rs.first()) {
            result = AvailabilityType.UP;
        }
    } catch (SQLException sqle) {

    } finally {
        DatabaseQueryUtility.close(stmt, rs);
    }
    return result;
}

From source file:org.ensembl.healthcheck.testcase.generic.SourceTypes.java

public boolean geneSources(Connection con) {

    boolean result = true;

    String[] sources = { "ensembl", "havana", "ensembl_havana" };

    // get all chromosomes, ignore LRG and MT
    String[] seqRegionNames = DBUtils.getColumnValues(con,
            "SELECT s.name FROM seq_region s, seq_region_attrib sa, attrib_type at WHERE s.seq_region_id = sa.seq_region_id AND sa.attrib_type_id = at.attrib_type_id AND code = 'karyotype_rank' AND s.name NOT LIKE 'MT'");

    // loop over each seq region, check that each logic name is represented
    try {//from w w w .j  a  v a  2  s.c  om

        PreparedStatement stmt = con.prepareStatement(
                "SELECT COUNT(*) FROM gene g, seq_region sr WHERE g.seq_region_id=sr.seq_region_id AND sr.name=? AND g.source=?");

        for (String seqRegion : seqRegionNames) {

            for (String source : sources) {

                stmt.setString(1, seqRegion);
                stmt.setString(2, source);

                ResultSet rs = stmt.executeQuery();

                rs.first();
                int rows = rs.getInt(1);

                if (rows == 0) {

                    result = false;
                    ReportManager.problem(this, con,
                            String.format("Chromosome %s has no genes with source %s", seqRegion, source));

                }

                rs.close();

            }

        }

        stmt.close();

    } catch (SQLException e) {

        System.err.println("Error executing SQL");
        e.printStackTrace();

    }

    return result;

}

From source file:ua.aits.Carpath.model.MapModel.java

public String getPanoramaName(String id)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    ResultSet result = DB.getResultSet("select panorama from content where id = " + id + " and publish = 1;");
    result.first();
    if (!result.next()) {
        return "";
    }//from   w w  w . ja  v a 2s.c  o  m
    if (result.getString("panorama").contains("archive_content")) {
        return result.getString("panorama");
    }
    return "files/panoramas/" + result.getString("panorama");
}

From source file:octavio.server.db.managers.UserManager.java

/**
 * Indique si un nom d'utilisateur est disponible.
 *
 * @param name Nom  vrifier// w  w w. j  av  a 2s.co  m
 *
 * @return Disponibilit du nom
 *
 * @throws SQLException Erreur SQL
 */
public boolean getNameAvailability(String name) throws SQLException {
    // Prparation et excution de la requte
    PreparedStatement statement = this.query(UserManager.QUERY_NAME_AVAILABLE);
    statement.setString(1, name);
    ResultSet set = statement.executeQuery();

    // Vrai si le rsultat est vide
    return !set.first();
}

From source file:octavio.server.db.managers.UserManager.java

/**
 * Rcupre un utilisateur via son nom et son mot de passe hash.
 *
 * @param id Identifiant de l'utilisateur
 *
 * @return Instance d'User correspondant
 *
 * @throws CommandException Erreur de login
 * @throws SQLException     Erreur SQL/*from w  ww .  j  ava2  s .c  o  m*/
 */
public User getUser(int id) throws CommandException, SQLException {
    // Prparation et excution de la requte
    PreparedStatement statement = this.query(UserManager.QUERY_USER);
    statement.setInt(1, id);
    ResultSet set = statement.executeQuery();

    // Retourne l'utilisateur trouv
    if (set.first()) {
        User user = new User(set.getInt("id"), set.getString("name"));
        return user;
    } else {
        CommandException exception = new CommandException("Unknown username", "unknown_user");
        exception.setArgument("id", String.valueOf(id));
        throw exception;
    }
}

From source file:octavio.server.db.managers.UserManager.java

/**
 * Rcupre un utilisateur via son nom et son mot de passe hash.
 *
 * @param name     Nom de l'utilisateur//from   ww  w  .j  a v a2s . co  m
 * @param password Mot de passe hash de l'utilisateur
 *
 * @return Instance d'User correspondant  l'utilisateur trouv ou null
 *
 * @throws CommandException Erreur de login
 * @throws SQLException     Erreur SQL
 */
public User getUser(String name, String password) throws CommandException, SQLException {
    // Prparation et excution de la requte
    PreparedStatement statement = this.query(UserManager.QUERY_USER_BY_LOGIN);
    statement.setString(1, name);
    statement.setString(2, password);
    ResultSet set = statement.executeQuery();

    // Retourne l'utilisateur si le nom existe
    if (set.first()) {
        User user = new User(set.getInt("id"), set.getString("name"));

        statement = this.query(UserManager.QUERY_USER_PARAMETERS);
        statement.setInt(1, user.getId());
        set = statement.executeQuery();
        while (set.next()) {
            user.setParameter(set.getString("parameter"), set.getString("value"));
        }

        statement = this.query(UserManager.QUERY_USER_RIGHTS);
        statement.setInt(1, user.getId());
        set = statement.executeQuery();
        while (set.next()) {
            user.setRight(set.getString("right"), set.getString("value"));
        }

        return user;
    } else {
        CommandException exception = new CommandException("Wrong username or password", "log_error");
        exception.setArgument("name", name);
        throw exception;
    }
}

From source file:ua.aits.sdolyna.model.ArticleModel.java

public String insertArticle(String titleEN, String titleRU, String textEN, String textRU, String category,
        String date, String date_end)
        throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    DB.runQuery(/*w w  w  .j a  va2s .  c  o  m*/
            "INSERT INTO `sdolyna_content`(`article_category`, `article_title_ru`, `article_title_en`, `article_text_ru`, `article_text_en`, `article_date`, `article_date_end`) VALUES ("
                    + "" + category + ",'" + StringEscapeUtils.escapeSql(titleRU) + "','"
                    + StringEscapeUtils.escapeSql(titleEN) + "','" + StringEscapeUtils.escapeSql(textRU) + "','"
                    + StringEscapeUtils.escapeSql(textEN) + "','" + date + "','" + date_end + "');");
    ResultSet last_id = DB.getResultSet("SELECT MAX(article_id) as MaximumID FROM `sdolyna_content`;");
    last_id.first();
    String id = last_id.getString("MaximumID");
    DB.closeCon();
    return id;
}

From source file:com.linkedin.pinot.integration.tests.HybridClusterIntegrationTest.java

@BeforeClass
public void setUp() throws Exception {
    //Clean up//from ww w .  j a  v a2s.  c o  m
    ensureDirectoryExistsAndIsEmpty(_tmpDir);
    ensureDirectoryExistsAndIsEmpty(_segmentDir);
    ensureDirectoryExistsAndIsEmpty(_tarDir);

    // Start Zk, Kafka and Pinot
    startHybridCluster();

    // Unpack the Avro files
    TarGzCompressionUtils.unTar(new File(TestUtils.getFileFromResourceUrl(OfflineClusterIntegrationTest.class
            .getClassLoader().getResource("On_Time_On_Time_Performance_2014_100k_subset_nonulls.tar.gz"))),
            _tmpDir);

    _tmpDir.mkdirs();

    final List<File> avroFiles = getAllAvroFiles();

    File schemaFile = getSchemaFile();
    schema = Schema.fromFile(schemaFile);
    addSchema(schemaFile, schema.getSchemaName());
    final List<String> invertedIndexColumns = makeInvertedIndexColumns();
    final String sortedColumn = makeSortedColumn();

    // Create Pinot table
    addHybridTable("mytable", "DaysSinceEpoch", "daysSinceEpoch", KafkaStarterUtils.DEFAULT_ZK_STR, KAFKA_TOPIC,
            schema.getSchemaName(), TENANT_NAME, TENANT_NAME, avroFiles.get(0), sortedColumn,
            invertedIndexColumns, null);
    LOGGER.info("Running with Sorted column=" + sortedColumn + " and inverted index columns = "
            + invertedIndexColumns);

    // Create a subset of the first 8 segments (for offline) and the last 6 segments (for realtime)
    final List<File> offlineAvroFiles = getOfflineAvroFiles(avroFiles);
    final List<File> realtimeAvroFiles = getRealtimeAvroFiles(avroFiles);

    // Load data into H2
    ExecutorService executor = Executors.newCachedThreadPool();
    setupH2AndInsertAvro(avroFiles, executor);

    // Create segments from Avro data
    LOGGER.info("Creating offline segments from avro files " + offlineAvroFiles);
    buildSegmentsFromAvro(offlineAvroFiles, executor, 0, _segmentDir, _tarDir, "mytable", false, null);

    // Initialize query generator
    setupQueryGenerator(avroFiles, executor);

    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MINUTES);

    // Set up a Helix spectator to count the number of segments that are uploaded and unlock the latch once 12 segments are online
    final CountDownLatch latch = new CountDownLatch(1);
    HelixManager manager = HelixManagerFactory.getZKHelixManager(getHelixClusterName(), "test_instance",
            InstanceType.SPECTATOR, ZkStarter.DEFAULT_ZK_STR);
    manager.connect();
    manager.addExternalViewChangeListener(new ExternalViewChangeListener() {
        @Override
        public void onExternalViewChange(List<ExternalView> externalViewList,
                NotificationContext changeContext) {
            for (ExternalView externalView : externalViewList) {
                if (externalView.getId().contains("mytable")) {

                    Set<String> partitionSet = externalView.getPartitionSet();
                    if (partitionSet.size() == offlineSegmentCount) {
                        int onlinePartitionCount = 0;

                        for (String partitionId : partitionSet) {
                            Map<String, String> partitionStateMap = externalView.getStateMap(partitionId);
                            if (partitionStateMap.containsValue("ONLINE")) {
                                onlinePartitionCount++;
                            }
                        }

                        if (onlinePartitionCount == offlineSegmentCount) {
                            System.out.println("Got " + offlineSegmentCount
                                    + " online tables, unlatching the main thread");
                            latch.countDown();
                        }
                    }
                }
            }
        }
    });

    // Upload the segments
    int i = 0;
    for (String segmentName : _tarDir.list()) {
        System.out.println("Uploading segment " + (i++) + " : " + segmentName);
        File file = new File(_tarDir, segmentName);
        FileUploadUtils.sendSegmentFile("localhost", "8998", segmentName, new FileInputStream(file),
                file.length());
    }

    // Wait for all offline segments to be online
    latch.await();

    // Load realtime data into Kafka
    LOGGER.info("Pushing data from realtime avro files " + realtimeAvroFiles);
    pushAvroIntoKafka(realtimeAvroFiles, KafkaStarterUtils.DEFAULT_KAFKA_BROKER, KAFKA_TOPIC);

    // Wait until the Pinot event count matches with the number of events in the Avro files
    int pinotRecordCount, h2RecordCount;
    long timeInFiveMinutes = System.currentTimeMillis() + 5 * 60 * 1000L;

    Statement statement = _connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    statement.execute("select count(*) from mytable");
    ResultSet rs = statement.getResultSet();
    rs.first();
    h2RecordCount = rs.getInt(1);
    rs.close();

    waitForRecordCountToStabilizeToExpectedCount(h2RecordCount, timeInFiveMinutes);
}

From source file:ua.aits.sdolyna.model.ArticleModel.java

public ArticleModel getArticleByID(String id) throws SQLException {
    ResultSet result = DB.getResultSet("SELECT * FROM `sdolyna_content` WHERE `article_id` = " + id + ";");
    result.first();
    ArticleModel article = new ArticleModel();
    article.setArticle_id(result.getInt("article_id"));
    article.setArticle_title_ru(result.getString("article_title_ru").replaceAll("\"", "&quot;"));
    article.setArticle_title_en(result.getString("article_title_en").replaceAll("\"", "&quot;"));
    article.setArticle_text_ru(result.getString("article_text_ru"));
    article.setArticle_text_en(result.getString("article_text_en"));
    article.setArticle_category(result.getInt("article_category"));
    article.setArticle_date(result.getString("article_date"));
    article.setArticle_date_end(result.getString("article_date_end"));
    String langs = "";
    if (!"".equals(article.article_title_ru)) {
        langs += "RU,";
    }//from ww  w  . j  av  a  2  s  .co m
    if (!"".equals(article.article_title_en)) {
        langs += "EN,";
    }
    if (langs != "") {
        article.setArticle_lang(langs.substring(0, langs.length() - 1));
    }
    article.setArticle_images(this.fillImages(article.article_id.toString()));

    DB.closeCon();
    return article;
}