Example usage for java.sql ResultSet getTimestamp

List of usage examples for java.sql ResultSet getTimestamp

Introduction

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

Prototype

java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Timestamp object in the Java programming language.

Usage

From source file:dao.DirectoryFileSearchQuery.java

/**
 * This method lists all the results for the search text from directories
 * @param conn the connection//ww  w  . j  a  va  2 s .c  o  m
 * @param collabrumId the collabrumid
 * @return HashSet the set that has the list of moderators for these collabrums.
 * @throws BaseDaoException - when error occurs
 **/
public HashSet run(Connection conn, String sString, String fileName, String dirName) throws BaseDaoException {

    //if ((RegexStrUtil.isNull(sString) || conn == null)) {
    if ((conn == null) || RegexStrUtil.isNull(fileName)) {
        return null;
    }

    //StringBuffer sb = new StringBuffer("select distinct d1.dirname, d2.directoryid, d2.entryid, d2.btitle from directory d1, dirblob d2 where");
    StringBuffer sb = new StringBuffer(
            "select distinct d1.dirname, d2.directoryid, d2.entryid, d2.btitle from directory d1, dirblob d2 where");

    if (!RegexStrUtil.isNull(sString)) {
        ArrayList columns = new ArrayList();
        columns.add("dirname");
        // set the sqlConstraint as " and "
        String sqlConstraint = " and ";
        sb.append(sqlSearch.getConstraint(columns, sString, sqlConstraint));
    } else {
        sb.append("dirpath IS NULL");
    }

    // directory name can be null
    if (!RegexStrUtil.isNull(dirName)) {
        sb.append(" and dirname like '%");
        sb.append(dirName);
        sb.append("%'");
    }

    sb.append(" and d1.directoryid=d2.directoryid and ");
    sb.append("d2.btitle like '%");
    sb.append(fileName);
    sb.append("%'");
    logger.info("sb.toString() = " + sb.toString());

    try {
        PreparedStatement stmt = conn.prepareStatement(sb.toString());
        ResultSet rs = stmt.executeQuery();

        Vector columnNames = null;
        Directory directory = null;
        HashSet pendingSet = new HashSet();

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        }

        while (rs.next()) {
            directory = (Directory) eop.newObject(DbConstants.DIRECTORY);
            for (int j = 0; j < columnNames.size(); j++) {
                if (((String) (columnNames.elementAt(j))).equalsIgnoreCase(DbConstants.ENTRY_DATE)) {
                    try {
                        directory.setValue(DbConstants.ENTRY_DATE,
                                GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp(DbConstants.ENTRY_DATE)));
                    } catch (ParseException e) {
                        throw new BaseDaoException("could not parse the date for entrydate in directory "
                                + rs.getTimestamp(DbConstants.ENTRY_DATE), e);
                    }
                } else {
                    directory.setValue((String) columnNames.elementAt(j),
                            (String) rs.getString((String) columnNames.elementAt(j)));
                }
            }
            pendingSet.add(directory);
        }
        return pendingSet;
    } catch (Exception e) {
        throw new BaseDaoException("Error occured while executing search directory run query " + sb.toString(),
                e);
    }
}

From source file:com.zuoxiaolong.dao.CommentDao.java

public Map<String, String> transfer(ResultSet resultSet, ViewMode viewMode) {
    Map<String, String> comment = new HashMap<String, String>();
    try {/*  w w w.j a v  a  2s .  com*/
        comment.put("id", resultSet.getString("id"));
        String content = resultSet.getString("content");
        String escapeContent = JsoupUtil.getText(content);
        comment.put("content", content);
        comment.put("escapeContent", escapeContent);
        comment.put("shortContent",
                StringUtil.substring(escapeContent, 40) + (escapeContent.length() > 40 ? "..." : ""));
        comment.put("create_date",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(resultSet.getTimestamp("create_date")));
        String username = resultSet.getString("username");
        String resourceUsername = resultSet.getString("resource_username");
        if (!StringUtils.isEmpty(username)) {
            comment.put("commenter", username);
        } else if (!StringUtils.isEmpty(resourceUsername)) {
            comment.put("commenter", resourceUsername);
        } else {
            comment.put("commenter", resultSet.getString("city") + "?");
        }
        Integer articleId = resultSet.getInt("article_id");
        if (viewMode == null) {
            viewMode = ViewMode.DYNAMIC;
        }
        Map<String, String> article = DaoFactory.getDao(ArticleDao.class).getArticle(articleId, viewMode);
        comment.put("articleUrl", article.get("url"));
        comment.put("articleSubject", article.get("subject"));
        comment.put("good_times", resultSet.getString("good_times"));
        comment.put("bad_times", resultSet.getString("bad_times"));
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return comment;
}

From source file:com.sfs.whichdoctor.dao.WorkshopDAOImpl.java

/**
 * Load workshop./*from   w  w  w.  j a  v  a 2s  .  c om*/
 *
 * @param rs the rs
 * @param fullResults the full results
 * @return the workshop bean
 * @throws SQLException the SQL exception
 */
private WorkshopBean loadWorkshop(final ResultSet rs, final boolean fullResults) throws SQLException {

    WorkshopBean workshop = new WorkshopBean();

    workshop.setId(rs.getInt("WorkshopId"));
    workshop.setGUID(rs.getInt("GUID"));
    workshop.setReferenceGUID(rs.getInt("ReferenceGUID"));
    workshop.setType(rs.getString("Type"));
    try {
        workshop.setWorkshopDate(rs.getDate("Date"));
    } catch (SQLException e) {
        workshop.setWorkshopDate(null);
    }
    workshop.setMemo(rs.getString("Memo"));

    workshop.setActive(rs.getBoolean("Active"));

    try {
        workshop.setCreatedDate(rs.getTimestamp("CreatedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
    }
    workshop.setCreatedBy(rs.getString("CreatedBy"));
    try {
        workshop.setModifiedDate(rs.getTimestamp("ModifiedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
    }
    workshop.setModifiedBy(rs.getString("ModifiedBy"));

    return workshop;
}

From source file:org.jrecruiter.service.migration.impl.MigrationServiceImpl.java

@Override
@Transactional()/*from w w w. j a v a2  s  .  co m*/
public void migrateUserData(final Boolean digestPasswords) {
    String sql = "select first_name, last_name, user_name, user_passwd, "
            + "phone, fax, email, register_date, expire_date, update_date, company from users where users.user_name <> 'admin'";

    ParameterizedRowMapper<User> mapper = new ParameterizedRowMapper<User>() {

        // notice the return type with respect to Java 5 covariant return types
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setFirstName(rs.getString("first_name"));
            user.setLastName(rs.getString("last_name"));

            user.setUsername(rs.getString("user_name"));
            user.setPassword(rs.getString("user_passwd"));

            user.setPhone(rs.getString("phone"));
            user.setFax(rs.getString("fax"));
            user.setEmail(rs.getString("email"));

            user.setRegistrationDate(rs.getTimestamp("register_date"));
            user.setUpdateDate(rs.getTimestamp("update_date"));
            user.setCompany(rs.getString("company"));
            user.setEnabled(true);
            return user;
        }
    };

    final List<User> users = this.jdbcTemplateV1.query(sql, mapper);

    if (digestPasswords) {

        int counter = 0;
        for (User user : users) {
            LOGGER.info("[" + ++counter + "/" + users.size() + "] User: " + user + "...digesting password.");
            user.setPassword(stringDigester.digest(user.getPassword()));
        }

    }

    final Role managerRole = roleDao.getRole(Constants.Roles.MANAGER.name());

    if (managerRole == null) {
        throw new IllegalStateException("Role was not found but is required.");
    }

    int counter = 0;
    for (User user : users) {
        LOGGER.info("[" + ++counter + "/" + users.size() + "] User: " + user + "...saving.");
        //  if ( counter % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:

        Set<UserToRole> userToRoles = user.getUserToRoles();

        UserToRole utr = new UserToRole();
        utr.setRole(managerRole);
        utr.setUser(user);

        userToRoles.add(utr);

        userDao.save(user);
        entityManager.flush();
        //    entityManager.clear();
        // }
    }

    LOGGER.info("Total number of records saved: " + users.size());

}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Try to retrieve a ConvergenceCertObservation from the local cache i.e. the ConvergenceCertObservations-table
 * /*from   www. j a va2s  .c  o  m*/
 * @param hostPort The Hostname and port of the server from which a questionable certificate has been received 
 * @param certSHA1 The SHA1-hash of the questionable certificate
 * @return If known (and not archaic): The ConvergenceCertObservation for the "hostPort"/"certSHA1"-combination, else null
 * @throws SQLException
 */
private ConvergenceCertObservation getCCOFromCache(String hostPort, String certSHA1) throws SQLException {

    Object[] params = { hostPort, certSHA1 };
    ResultSet rs = db.executeQuery(
            "SELECT * FROM ConvergenceCertObservations WHERE ServerHostPort = ? AND SHA1Hash = ? LIMIT 1",
            params);

    // If the result is empty then there is no cache entry to return
    if (!rs.next()) {
        return null;
    }

    // If the cache entry is not valid anymore (and should be refreshed) then there is nothing to return
    Timestamp lastUpdate = rs.getTimestamp("LastUpdate");
    if (lastUpdate.before(new Timestamp(System.currentTimeMillis() - this.refreshInterval)))
        return null;

    // If there is a cache entry that is currently valid: return it as ConvergenceCertObservation
    return new ConvergenceCertObservation(rs.getString("ServerHostPort"), rs.getString("SHA1Hash"),
            rs.getTimestamp("FirstObservation"), rs.getTimestamp("LastObservation"), lastUpdate);
}

From source file:com.sfs.whichdoctor.dao.IsbMessageDAOImpl.java

/**
 * Load isb message bean./*from   www . j a  v a2 s  .co m*/
 *
 * @param rs the rs
 *
 * @return the isb message bean
 *
 * @throws SQLException the SQL exception
 */
private IsbMessageBean loadIsbMessageBean(final ResultSet rs) throws SQLException {

    final IsbMessageBean message = new IsbMessageBean();

    message.setId(rs.getInt("Id"));
    message.setSource(rs.getString("Source"));
    message.setTarget(rs.getString("IsbTarget"));
    message.setAction(rs.getString("Action"));
    message.setIdentifier(rs.getString("Identifier"));
    message.setIsInbound(rs.getBoolean("IsInbound"));
    message.setProcessed(rs.getBoolean("Processed"));
    try {
        message.setCreatedDate(rs.getTimestamp("Created"));
    } catch (SQLException e) {
        dataLogger.debug("Error reading Created date: " + e.getMessage());
    }
    // Load the ISB payload
    try {
        message.setIsbPayload(this.isbPayloadDAO.loadSiblingOf(message.getId()));
    } catch (WhichDoctorDaoException wde) {
        dataLogger.debug("Error loading ISB payload: " + wde.getMessage());
    }

    return message;
}

From source file:com.ewcms.component.interaction.dao.InteractionDAO.java

@Override
public List<Speak> findSpeakByInteractionId(int interactionId, String username, int page, int row) {
    String sql = "Select * From plugin_interaction_speak "
            + "Where interaction_id = ? And (checked = true Or username=?) "
            + "Order By date desc Limit ? OffSet ?";
    username = (username == null ? "" : username);
    int offset = page * row;
    List<Speak> list = jdbcTemplate.query(sql, new Object[] { interactionId, username, row, offset },
            new RowMapper<Speak>() {

                @Override/*from www.j av  a2s .c om*/
                public Speak mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Speak vo = new Speak();
                    vo.setUsername(rs.getString("username"));
                    vo.setName(rs.getString("name"));
                    vo.setContent(rs.getString("content"));
                    vo.setIp(rs.getString("ip"));
                    vo.setChecked(rs.getBoolean("checked"));
                    vo.setDate(rs.getTimestamp("date"));
                    vo.setInteractionId(rs.getInt("interaction_id"));
                    vo.setName(rs.getString("name"));

                    return vo;
                }
            });

    return list;
}

From source file:edu.jhu.pha.vospace.meta.MySQLMetaStore2.java

@Override
public NodeInfo getNodeInfo(final VospaceId identifier) {
    return DbPoolServlet.goSql("Retrieving node info",
            "select rev, deleted, nodes.mtime, nodes.size, mimetype, chunked_name from nodes "
                    + "JOIN containers ON nodes.container_id = containers.container_id "
                    + "JOIN user_identities ON containers.user_id = user_identities.user_id "
                    + "LEFT JOIN chunked_uploads ON nodes.node_id = chunked_uploads.node_id "
                    + "WHERE current_rev = 1 and container_name = ? and path = ? and identity = ?",
            new SqlWorker<NodeInfo>() {
                @Override/*from   w w w.  j  a v a2s  .co m*/
                public NodeInfo go(Connection conn, PreparedStatement stmt) throws SQLException {
                    NodeInfo info = new NodeInfo();

                    stmt.setString(1, identifier.getNodePath().getContainerName());
                    stmt.setString(2, identifier.getNodePath().getNodeRelativeStoragePath());
                    stmt.setString(3, owner);

                    ResultSet resSet = stmt.executeQuery();

                    if (resSet.next()) {
                        info.setRevision(resSet.getInt("rev"));
                        info.setDeleted(resSet.getBoolean("deleted"));
                        info.setMtime(new Date(resSet.getTimestamp("mtime").getTime()));
                        info.setSize(resSet.getLong("size"));
                        info.setContentType(resSet.getString("mimetype"));
                        info.setChunkedName(resSet.getString("chunked_name"));
                    } else {
                        throw new NotFoundException("NodeNotFound");
                    }

                    return info;
                }
            });
}

From source file:ru.org.linux.comment.CommentDaoImpl.java

@Override
public List<CommentsListItem> getUserComments(int userId, int limit, int offset) {
    return jdbcTemplate.query("SELECT sections.name as ptitle, groups.title as gtitle, topics.title, "
            + "topics.id as topicid, comments.id as msgid, comments.postdate "
            + "FROM sections, groups, topics, comments "
            + "WHERE sections.id=groups.section AND groups.id=topics.groupid " + "AND comments.topic=topics.id "
            + "AND comments.userid=? AND NOT comments.deleted ORDER BY postdate DESC LIMIT ? OFFSET ?",
            new RowMapper<CommentsListItem>() {
                @Override/*from  w  ww  . j  a  v  a 2  s .  c  o  m*/
                public CommentsListItem mapRow(ResultSet rs, int rowNum) throws SQLException {
                    CommentsListItem item = new CommentsListItem();

                    item.setSectionTitle(rs.getString("ptitle"));
                    item.setGroupTitle(rs.getString("gtitle"));
                    item.setTopicId(rs.getInt("topicid"));
                    item.setCommentId(rs.getInt("msgid"));
                    item.setTitle(StringUtil.makeTitle(rs.getString("title")));
                    item.setPostdate(rs.getTimestamp("postdate"));

                    return item;
                }
            }, userId, limit, offset);
}

From source file:edu.harvard.i2b2.im.dao.PdoDao.java

public AuditsType getAudit(final GetAuditType auditType, final String userId, final ProjectType projectInfo,
        final DBInfoType dbInfo) throws Exception {

    String metadataSchema = dbInfo.getDb_fullSchema();
    setDataSource(dbInfo.getDb_dataSource());

    //       First step is to call PM to see what roles user belongs to.

    if (projectInfo.getRole().size() == 0) {
        log.error("no role found for this user in project: " + projectInfo.getName());
        I2B2Exception e = new I2B2Exception("No role found for user");
        throw e;//from w  w  w. ja v  a 2s .  c  o  m
    }

    boolean protectedAccess = false;
    Iterator it = projectInfo.getRole().iterator();
    while (it.hasNext()) {
        String role = (String) it.next();
        if (role.toLowerCase().equalsIgnoreCase("ADMIN") || (role.toLowerCase().equalsIgnoreCase("MANAGER"))) {
            protectedAccess = true;
            break;
        }
    }

    if (!protectedAccess)
        throw new I2B2DAOException("Access Denied");

    ParameterizedRowMapper<AuditType> map = new ParameterizedRowMapper<AuditType>() {
        public AuditType mapRow(ResultSet rs, int rowNum) throws SQLException {
            AuditType pid = new AuditType();
            pid.setPid(rs.getString("lcl_id"));
            pid.setComment(rs.getString("comments"));
            pid.setProjectId(rs.getString("project_id"));
            pid.setSource(rs.getString("lcl_site"));
            pid.setImportDate(dtoFactory.getXMLGregorianCalendar(rs.getTimestamp("query_date").getTime()));
            pid.setUserId(rs.getString("user_id"));
            return pid;
        }
    };
    List<AuditType> queryResult = null;
    String tablesSql = "";
    int min = 1;
    int max = 1000;

    if (dbInfo.getDb_serverType().equals("ORACLE")) {
        tablesSql = "SELECT * FROM ( " + "    SELECT a.*, rownum r__ " + "    FROM " + "    ( "
                + "       SELECT * FROM " + metadataSchema + "im_audit WHERE ";

        if (auditType != null) {
            if (auditType.getMin() != null)
                min = auditType.getMin();
            if (auditType.getMax() != null)
                max = auditType.getMax();
            if ((auditType.getPid() != null) && (auditType.getPid().length() > 0))
                tablesSql += "lcl_site = '" + auditType.getSource() + "' and lcl_id = '" + auditType.getPid()
                        + "' and ";
            if ((auditType.getUserId() != null) && (auditType.getUserId().length() > 0))
                tablesSql += "user_id = '" + auditType.getUserId() + "' and ";
            if ((auditType.getProjectId() != null) && (auditType.getProjectId().length() > 0))
                tablesSql += " project_id =  '" + auditType.getProjectId() + "' and ";

            if (auditType.getComment() != null)
                tablesSql += " comment =  '" + auditType.getComment() + "' and ";

        }

        tablesSql += " 1 = 1 " + "       ORDER BY query_date DESC " + "    ) a " + "    WHERE rownum < ((" + min
                + " * " + max + ") + 1 ) " + " ) " + " WHERE r__ >= (((" + min + "-1) * " + max + ") + 1) ";

    } else if (dbInfo.getDb_serverType().equals("SQLSERVER")
            || (dbInfo.getDb_serverType().equals("POSTGRESQL"))) {
        tablesSql = "SELECT * FROM ( " + "    SELECT ROW_NUMBER() OVER ( ORDER BY query_date ) AS RowNum, * "
                + "       FROM " + metadataSchema + "im_audit WHERE ";

        if (auditType != null) {
            if (auditType.getMin() != null)
                min = auditType.getMin();
            if (auditType.getMax() != null)
                max = auditType.getMax();
            if (auditType.getPid() != null)
                tablesSql += "lcl_site = '" + auditType.getSource() + "' and lcl_id = '" + auditType.getPid()
                        + "' and ";
            if ((auditType.getUserId() != null) && (auditType.getUserId().length() > 0))
                tablesSql += "user_id = '" + auditType.getUserId() + "' and ";
            if ((auditType.getProjectId() != null) && (auditType.getProjectId().length() > 0))
                tablesSql += " project_id =  '" + auditType.getProjectId() + "' and ";

            if (auditType.getComment() != null)
                tablesSql += " comment =  '" + auditType.getComment() + "' and ";

        }

        tablesSql += " 1=1 " + "    ) as  RowConstrainedResult " + "    WHERE RowNum >= " + min
                + " and RowNum < " + max + " ORDER BY RowNum ";
    }

    try {
        queryResult = jt.query(tablesSql, map);

        //            queryResult = jt.query(tablesSql, mapper, "N", projectInfo.getId().toLowerCase());
    } catch (DataAccessException e) {
        log.error(e.getMessage());
        throw new I2B2DAOException("Database error: " + e.getMessage());
    }

    log.debug("result size = " + queryResult.size());

    AuditsType auditTypes = new AuditsType();
    auditTypes.getAudit().addAll(queryResult);

    return auditTypes; //patientdataResonse;
}