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:com.adanac.module.blog.dao.CommentDao.java

public Map<String, String> transfer(ResultSet resultSet, ViewMode viewMode) {
    Map<String, String> comment = new HashMap<String, String>();
    try {/*  w w  w  .  ja  va2  s  . co  m*/
        comment.put("id", resultSet.getString("id"));
        comment.put("content", resultSet.getString("content"));
        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") + "?");
        }
        comment.put("articleUrl",
                Configuration.getSiteUrl() + "/blog/article.ftl?id=" + resultSet.getInt("article_id"));
        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:Employee.getAllCustomers.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w.j a va 2s .  c  om
 *
 * @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 {
    //json to pass back to our ajax request
    JSONArray jsonArray = new JSONArray();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();

        String query = "SELECT * FROM [MatchesFromAbove].[dbo].[Customer] WHERE active=1";

        ResultSet rs = st.executeQuery(query);

        //loop through result set and create the json objects
        while (rs.next()) {
            JSONObject customerToAdd = new JSONObject();
            customerToAdd.put("ssn", rs.getString("SSN"));
            customerToAdd.put("ppp", rs.getString("PPP"));
            customerToAdd.put("rating", rs.getInt("Rating"));
            customerToAdd.put("lastActiveDate", rs.getTimestamp("LastActive").toString());
            //add the json object that we're passing into the json array
            jsonArray.add(customerToAdd);
        }
        //set the content type of our response
        response.setContentType("application/json");
        //printout prints it to our ajax call and it shows up there as data. you can use this data in the success function.
        PrintWriter printout = response.getWriter();
        printout.print(jsonArray);
        printout.flush();
        con.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return;
    }
}

From source file:org.surfnet.cruncher.repository.StatisticsRepositoryImpl.java

@Override
public List<SpStatistic> getActiveServices(String userid, String idpEntityId) {
    NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(cruncherJdbcTemplate);

    String query = "select loginstamp as loginstamp, spentityid as spentityid, "
            + "spentityname as spentityname from user_log_logins " + "where " + "userid = :userId AND "
            + "idpentityid = :idpEntityId ";

    Map<String, Object> parameterMap = new HashMap<String, Object>();
    parameterMap.put("userId", userid);
    parameterMap.put("idpEntityId", idpEntityId);

    return namedJdbcTemplate.query(query, parameterMap, new RowMapper<SpStatistic>() {

        @Override/*  w  ww. j  av a  2s .c o m*/
        public SpStatistic mapRow(ResultSet rs, int row) throws SQLException {
            SpStatistic result = new SpStatistic();
            result.setEntryTime(rs.getTimestamp("loginstamp").getTime());
            result.setSpEntityId(rs.getString("spentityid"));
            result.setSpName(rs.getString("spentityname"));

            return result;
        }

    });
}

From source file:com.agiletec.plugins.jpcontentfeedback.aps.system.services.contentfeedback.comment.CommentDAO.java

/**
 * Dato il resultSet, ne estrae i dati e popola l'oggetto comment
 * @param res/*from w  w  w .j  a  v  a2  s.c o  m*/
 * @return
 * @throws ApsSystemException
 */
private Comment popualteComment(ResultSet res) throws ApsSystemException {
    Comment comment = new Comment();
    try {
        comment.setId(res.getInt("id"));
        comment.setContentId(res.getString("contentid"));
        Timestamp creationDate = res.getTimestamp("creationDate");
        if (null != creationDate) {
            comment.setCreationDate(new Date(creationDate.getTime()));
        }
        comment.setComment(res.getString("usercomment"));
        comment.setStatus(res.getInt("status"));
        comment.setUsername(res.getString("username"));
    } catch (Throwable t) {
        throw new ApsSystemException("Errore loading comment", t);
    }
    return comment;
}

From source file:dk.dma.msinm.legacy.msi.service.LegacyMsiImportService.java

private Date getDate(ResultSet rs, String key) throws SQLException {
    Timestamp val = rs.getTimestamp(key);
    return rs.wasNull() ? null : val;
}

From source file:henu.dao.impl.CaclDaoImpl.java

@Override
public Cacl getCacl(String cid) {
    String sql = "select * from cacl where cid=" + cid;

    ResultSet rs = SqlDB.executeQuery(sql);
    Cacl cacl = new Cacl();

    try {//  w  ww. j av a 2  s  . c  o m
        cacl.setTid(rs.getLong("cid"));
        cacl.setName(rs.getString("cname"));
        cacl.setStructure(rs.getString("structure"));
        cacl.setAuthor(rs.getInt("author"));
        cacl.setType(rs.getBoolean("ctype"));
        cacl.setPostime(rs.getTimestamp("postime").toString());
        cacl.setEndtime(rs.getString("endtime"));
        cacl.setUsers(getCaclUserList(cid));

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

    SqlDB.close();

    return cacl;
}

From source file:com.springsource.greenhouse.events.load.JdbcEventLoaderRepositoryTest.java

@Test
public void loadTimeSlot() throws SQLException {
    long eventId = eventLoaderRepository.loadEvent(
            new EventData(1, "Test Event", "Test Event Description", "test", "2012-10-15T00:00:00",
                    "2012-10-18T23:59:59", "America/New_York", "NFJS", 297),
            new VenueData("Some Fancy Hotel", "1234 North Street, Chicago, IL 60605", 41.89001, -87.677765,
                    "It's in Illinois"));

    long timeSlotId = eventLoaderRepository.loadTimeSlot(new TimeSlotData(eventId, "Time Slot 1",
            "2012-10-15T00:00:00", "2012-10-15T01:30:00", "NFJS", 6296));
    assertEquals(1L, timeSlotId);/*from w  w w  .j  a  va  2  s  .  c  om*/
    jdbcTemplate.queryForObject("select id, event, label, startTime, endTime from EventTimeSlot where id=?",
            new RowMapper<ResultSet>() {
                public ResultSet mapRow(ResultSet rs, int rowNum) throws SQLException {
                    assertEquals(1L, rs.getLong("id"));
                    assertEquals(1L, rs.getLong("event"));
                    assertEquals("Time Slot 1", rs.getString("label"));
                    Timestamp startTime = rs.getTimestamp("startTime");
                    Timestamp endTime = rs.getTimestamp("endTime");
                    //            assertEquals(new DateTime(2012, 10, 15, 0, 0, 0, 0, DateTimeZone.getDefault()).getMillis(), startTime.getTime());
                    //            assertEquals(new DateTime(2012, 10, 15, 1, 30, 0, 0, DateTimeZone.getDefault()).getMillis(), endTime.getTime());
                    return null;
                }
            }, timeSlotId);
}

From source file:bookUtilities.PopulateMyBooksServlet.java

private JSONArray getUserBooks(String email, JSONArray fileTypes) {
    String query;/*from w  w  w  .  j  a v  a2s . co m*/
    JSONArray jsons = new JSONArray();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");
        Statement st = con.createStatement();
        query = "SELECT Book.*, checkedBooks.ExpirationDate "
                + "FROM [HardCover].[dbo].[Book] Book, [HardCover].[dbo].[RegisteredUser] RegisteredUser, [HardCover].[dbo].[CheckedOutBook] checkedBooks, [HardCover].[dbo].[Person] P "
                + "WHERE Book.BookUuid = checkedBooks.BookId AND checkedBooks.RegisteredUserId = RegisteredUser.RegisteredUserId AND P.PersonUuid = RegisteredUser.RegisteredUserId "
                + " AND P.Email = '" + email + "' AND checkedBooks.Expired = 0";

        ResultSet rs = st.executeQuery(query);
        /* TODO output your page here. You may use following sample code. */
        while (rs.next()) {
            JSONObject bookToAdd = new JSONObject();

            JSONArray fileTypesArray = new JSONArray();
            Statement st2 = con.createStatement();
            Statement st3 = con.createStatement();
            Timestamp timeStamp = rs.getTimestamp("ExpirationDate");
            String timeString = timeStamp.toString();
            String bookId = rs.getString("BookUuid");

            query = "SELECT AuthorName " + "FROM [HardCover].[dbo].[Author] " + "WHERE BookId = '" + bookId
                    + "';";
            ResultSet rs2 = st2.executeQuery(query);
            rs2.next();

            query = "SELECT FileType, DownloadLink " + "FROM [HardCover].[dbo].[BookFileType] "
                    + "WHERE BookId = '" + bookId + "'";

            ResultSet rs3 = st3.executeQuery(query);
            while (rs3.next()) {
                JSONObject fileTypeToAdd = new JSONObject();
                fileTypeToAdd.put("fileType", rs3.getString("FileType"));
                fileTypeToAdd.put("downloadLink", rs3.getString("DownLoadLink"));
                fileTypesArray.add(fileTypeToAdd);
            }
            fileTypes.add(fileTypesArray);
            bookToAdd.put("expirationDate", timeString);
            bookToAdd.put("author", rs2.getString("AuthorName"));
            bookToAdd.put("title", rs.getString("Title"));
            bookToAdd.put("cover", rs.getString("Cover"));
            bookToAdd.put("dateAdded", rs.getString("DateAdded"));
            bookToAdd.put("bookId", rs.getString("BookUuid"));

            jsons.add(bookToAdd);
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return jsons;
}

From source file:com.surevine.alfresco.audit.integration.AuditRowMapper.java

public Object mapRow(ResultSet rs, int rowCount) throws SQLException {

    Auditable audited = new AuditItem();
    audited.setAction(rs.getString("action"));
    audited.setSource(rs.getString("source"));
    audited.setVersion(rs.getString("version"));
    audited.setRemoteAddress(rs.getString("remote_addr"));
    audited.setUser(rs.getString("username"));
    audited.setDetails(rs.getString("details"));
    audited.setSuccess(rs.getBoolean("success"));
    audited.setUrl(rs.getString("url"));
    audited.setDate(new Date(rs.getTimestamp("tstamp").getTime()));
    audited.setSite(rs.getString("site"));
    audited.setVersion(rs.getString("version"));
    audited.setSecLabel(rs.getString("secLabel"));
    audited.setTags(rs.getString("tags"));
    audited.setNodeRef(rs.getString("node_ref"));

    return audited;
}

From source file:org.apache.lucene.store.jdbc.JdbcDirectory.java

/**
 * Delets all the file entries that are marked to be deleted, and they were marked
 * "delta" time ago (base on database time, if possible by dialect).
 */// w  w  w  .  j  av a  2  s.com
public void deleteMarkDeleted(long delta) throws IOException {
    long currentTime = System.currentTimeMillis();
    if (dialect.supportsCurrentTimestampSelection()) {
        String timestampSelectString = dialect.getCurrentTimestampSelectString();
        if (dialect.isCurrentTimestampSelectStringCallable()) {
            currentTime = ((Long) jdbcTemplate.executeCallable(timestampSelectString,
                    new JdbcTemplate.CallableStatementCallback() {
                        public void fillCallableStatement(CallableStatement cs) throws Exception {
                            cs.registerOutParameter(1, java.sql.Types.TIMESTAMP);
                        }

                        public Object readCallableData(CallableStatement cs) throws Exception {
                            Timestamp timestamp = cs.getTimestamp(1);
                            return new Long(timestamp.getTime());
                        }
                    })).longValue();
        } else {
            currentTime = ((Long) jdbcTemplate.executeSelect(timestampSelectString,
                    new JdbcTemplate.ExecuteSelectCallback() {
                        public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                            // nothing to do here
                        }

                        public Object execute(ResultSet rs) throws Exception {
                            rs.next();
                            Timestamp timestamp = rs.getTimestamp(1);
                            return new Long(timestamp.getTime());
                        }
                    })).longValue();
        }
    }
    final long deleteBefore = currentTime - delta;
    jdbcTemplate.executeUpdate(table.sqlDeletaMarkDeleteByDelta(),
            new JdbcTemplate.PrepateStatementAwareCallback() {
                public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                    ps.setBoolean(1, true);
                    ps.setTimestamp(2, new Timestamp(deleteBefore));
                }
            });
}