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.erbjuder.logger.server.rest.util.ResultSetConverter.java

private List<LogMessage> toLogMessageInternal(ResultSet rs, List<LogMessage> logMessages) {

    try {/*from www. ja v a  2  s .com*/

        // we will need the column names.
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        //loop through the ResultSet
        while (rs.next()) {

            //figure out how many columns there are
            int numColumns = rsmd.getColumnCount();

            //each row in the ResultSet will be converted to a Object
            LogMessage obj = new LogMessage();

            // loop through all the columns 
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);

                if (column_name.equals("ID")) {
                    obj.setId(rs.getBigDecimal(column_name).longValueExact());
                }

                if (column_name.equals("APPLICATIONNAME")) {
                    obj.setApplicationName(rs.getNString(column_name));
                }

                if (column_name.equals("EXPIREDDATE")) {
                    obj.setExpiredDate(rs.getDate(column_name));
                }

                if (column_name.equals("FLOWNAME")) {
                    obj.setFlowName(rs.getNString(column_name));
                }

                if (column_name.equals("FLOWPOINTNAME")) {
                    obj.setFlowPointName(rs.getNString(column_name));
                }

                if (column_name.equals("ISERROR")) {
                    obj.setIsError(rs.getBoolean(column_name));
                }

                if (column_name.equals("TRANSACTIONREFERENCEID")) {
                    obj.setTransactionReferenceID(rs.getNString(column_name));
                }

                if (column_name.equals("UTCLOCALTIMESTAMP")) {
                    obj.setUtcLocalTimeStamp(rs.getTimestamp(column_name));
                }

                if (column_name.equals("UTCSERVERTIMESTAMP")) {
                    obj.setUtcServerTimeStamp(rs.getTimestamp(column_name));
                }
            } //end foreach
            logMessages.add(obj);
        } //end while
    } catch (Exception e) {
        e.printStackTrace();
    }

    return logMessages;
}

From source file:com.nridge.core.ds.rdbms.hsqldb.HDBSQLTable.java

private void addTableRowFromFunctionResultSet(DataTable aTable, ResultSet aResultSet) {
    DataField dataField;//from  w w  w. j  av  a 2s.  com
    Logger appLogger = mAppMgr.getLogger(this, "addTableRowFromFunctionResultSet");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    FieldRow fieldRow = aTable.newRow();

    int columnNumber = 0;
    for (DataField pField : aTable.getColumnBag().getFields()) {
        columnNumber++;
        dataField = new DataField(pField);

        try {
            switch (pField.getType()) {
            case Integer:
                dataField.setValue(aResultSet.getInt(columnNumber));
                break;
            case Long:
                dataField.setValue(aResultSet.getLong(columnNumber));
                break;
            case Float:
                dataField.setValue(aResultSet.getFloat(columnNumber));
                break;
            case Double:
                dataField.setValue(aResultSet.getDouble(columnNumber));
                break;
            case Boolean:
                dataField.setValue(aResultSet.getBoolean(columnNumber));
                break;
            case Date:
                dataField.setValue(aResultSet.getDate(columnNumber));
                break;
            case Time:
                dataField.setValue(aResultSet.getTime(columnNumber));
                break;
            case DateTime:
                dataField.setValue(aResultSet.getTimestamp(columnNumber));
                break;
            default:
                dataField.setValue(aResultSet.getString(columnNumber));
                break;
            }

            if (!aResultSet.wasNull())
                aTable.setValueByName(fieldRow, pField.getName(), dataField.getValue());
        } catch (SQLException e) {
            appLogger.error(String.format("SQL Exception (%s): %s", pField.getName(), e.getMessage()));
        }
    }

    aTable.addRow(fieldRow);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.ds.rdbms.hsqldb.HDBSQLTable.java

private void addTableRowFromResultSet(DataTable aTable, ResultSet aResultSet) {
    String columnName;//from w w w .j a  v a2 s .c o  m
    DataField dataField;
    Logger appLogger = mAppMgr.getLogger(this, "addTableRowFromResultSet");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    FieldRow fieldRow = aTable.newRow();

    for (DataField pField : aTable.getColumnBag().getFields()) {
        dataField = new DataField(pField);

        try {
            columnName = columnName(pField.getName());

            switch (pField.getType()) {
            case Integer:
                dataField.setValue(aResultSet.getInt(columnName));
                break;
            case Long:
                dataField.setValue(aResultSet.getLong(columnName));
                break;
            case Float:
                dataField.setValue(aResultSet.getFloat(columnName));
                break;
            case Double:
                dataField.setValue(aResultSet.getDouble(columnName));
                break;
            case Boolean:
                dataField.setValue(aResultSet.getBoolean(columnName));
                break;
            case Date:
                dataField.setValue(aResultSet.getDate(columnName));
                break;
            case Time:
                dataField.setValue(aResultSet.getTime(columnName));
                break;
            case DateTime:
                dataField.setValue(aResultSet.getTimestamp(columnName));
                break;
            default:
                dataField.setValue(aResultSet.getString(columnName));
                break;
            }

            if (!aResultSet.wasNull())
                aTable.setValueByName(fieldRow, pField.getName(), dataField.getValue());
        } catch (SQLException e) {
            appLogger.error(String.format("SQL Exception (%s): %s", pField.getName(), e.getMessage()));
        } catch (NSException e) {
            appLogger.error(String.format("NS Exception (%s): %s", pField.getName(), e.getMessage()));
        }
    }

    aTable.addRow(fieldRow);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:edu.harvard.i2b2.pm.dao.PMDbDao.java

private ParameterizedRowMapper getSession() {
    ParameterizedRowMapper<SessionData> map = new ParameterizedRowMapper<SessionData>() {
        public SessionData mapRow(ResultSet rs, int rowNum) throws SQLException {
            SessionData rData = new SessionData();
            //            DTOFactory factory = new DTOFactory();

            rData.setSessionID(rs.getString("session_id"));

            Date date = rs.getTimestamp("expired_date");
            if (date == null)
                rData.setExpiredDate(null);
            else/*w w w.j  a  va 2s . c  o m*/
                rData.setExpiredDate(date);

            date = rs.getTimestamp("entry_date");
            if (date == null)
                rData.setIssuedDate(null);
            else
                rData.setIssuedDate(date);

            return rData;
        }
    };
    return map;
}

From source file:edu.harvard.i2b2.pm.dao.PMDbDao.java

private ParameterizedRowMapper getUserLogin() {
    ParameterizedRowMapper<SessionData> map = new ParameterizedRowMapper<SessionData>() {
        public SessionData mapRow(ResultSet rs, int rowNum) throws SQLException {
            SessionData rData = new SessionData();
            //            DTOFactory factory = new DTOFactory();

            rData.setSessionID(rs.getString("session_id"));

            Date date = rs.getTimestamp("expired_date");
            if (date == null)
                rData.setExpiredDate(null);
            else//from   w w  w  .  j a v a 2 s .com
                rData.setExpiredDate(date);

            date = rs.getTimestamp("entry_date");
            if (date == null)
                rData.setIssuedDate(null);
            else
                rData.setIssuedDate(date);

            return rData;
        }
    };
    return map;
}

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

/**
 * Load receipt./*from ww w  . j  a va  2s  . co m*/
 *
 * @param rs the rs
 * @param loadDetails the load details
 *
 * @return the receipt bean
 *
 * @throws SQLException the SQL exception
 */
private ReceiptBean loadReceipt(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

    ReceiptBean receipt = new ReceiptBean();

    receipt.setId(rs.getInt("ReceiptId"));
    receipt.setGUID(rs.getInt("GUID"));

    receipt.setAbbreviation(rs.getString("Abbreviation"));
    receipt.setNumber(rs.getString("ReceiptNo"));
    receipt.setDescription(rs.getString("Description"));
    receipt.setProcessType(rs.getString("ProcessType"));
    receipt.setProcessAbbreviation(rs.getString("ProcessAbbreviation"));
    receipt.setBatchReference(rs.getInt("BatchReference"));
    receipt.setBank(rs.getString("Bank"));
    receipt.setBranch(rs.getString("Branch"));
    try {
        receipt.setIssued(rs.getDate("Issued"));
    } catch (SQLException e) {
        receipt.setIssued(null);
    }
    receipt.setCancelled(rs.getBoolean("Cancelled"));

    int organisationGUID = rs.getInt("OrganisationId");
    int personGUID = rs.getInt("PersonId");

    if (personGUID > 0) {
        receipt.setPerson(loadPerson(rs, personGUID, loadDetails));
    }
    if (organisationGUID > 0) {
        receipt.setOrganisation(loadOrganisation(rs, organisationGUID, loadDetails));
    }

    receipt.setTypeName(rs.getString("Type"));
    receipt.setClassName(rs.getString("ReceiptType"));
    receipt.setTotalValue(rs.getDouble("TotalValue"));
    receipt.setSecurity(rs.getString("Security"));

    receipt.setActive(rs.getBoolean("Active"));
    if (loadDetails.getBoolean("HISTORY")) {
        try {
            receipt.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
        }
        receipt.setCreatedBy(rs.getString("CreatedBy"));
        try {
            receipt.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
        }
        receipt.setModifiedBy(rs.getString("ModifiedBy"));
        try {
            receipt.setExportedDate(rs.getTimestamp("ExportedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ExportedDate: " + sqe.getMessage());
        }
        receipt.setExportedBy(rs.getString("ExportedBy"));
    }

    if (loadDetails.getBoolean("TAGS")) {
        try {
            receipt.setTags(this.getTagDAO().load(receipt.getGUID(), loadDetails.getString("USERDN"), true));
        } catch (Exception e) {
            dataLogger.error("Error loading tags for receipt: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("MEMO")) {
        try {
            receipt.setMemo(this.getMemoDAO().load(receipt.getGUID(), loadDetails.getBoolean("MEMO_FULL")));
        } catch (Exception e) {
            dataLogger.error("Error loading memos: " + e.getMessage());
        }
    }
    if (loadDetails.getBoolean("PAYMENT")) {
        try {
            receipt.setPayments(
                    this.paymentDAO.load(receipt.getGUID(), loadDetails.getBoolean("PAYMENT_FULL")));
        } catch (Exception e) {
            dataLogger.error("Error loading payment details: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("GROUPS")) {
        receipt.setGroups(loadGroups(receipt.getGUID()));
    }

    if (loadDetails.getBoolean("CREATED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("CreatedFirstName"));
        user.setLastName(rs.getString("CreatedLastName"));
        receipt.setCreatedUser(user);
    }
    if (loadDetails.getBoolean("MODIFIED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ModifiedBy"));
        user.setPreferredName(rs.getString("ModifiedFirstName"));
        user.setLastName(rs.getString("ModifiedLastName"));
        receipt.setModifiedUser(user);
    }
    if (loadDetails.getBoolean("EXPORTED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ExportedBy"));
        user.setPreferredName(rs.getString("ExportedFirstName"));
        user.setLastName(rs.getString("ExportedLastName"));
        receipt.setExportedUser(user);
    }
    return receipt;
}

From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Populates the object's properties from the result set
 *
 * @param rs        Description of Parameter
 * @param isVersion Description of Parameter
 * @throws SQLException Description of Exception
 *//*from   w ww.  ja v a  2s . c om*/
protected void buildRecord(ResultSet rs, boolean isVersion) throws SQLException {
    id = rs.getInt("item_id");
    if (!isVersion) {
        linkModuleId = rs.getInt("link_module_id");
        linkItemId = rs.getInt("link_item_id");
        folderId = DatabaseUtils.getInt(rs, "folder_id", -1);
    }
    clientFilename = rs.getString("client_filename");
    filename = rs.getString("filename");
    subject = rs.getString("subject");
    size = rs.getInt("size");
    version = rs.getDouble("version");
    enabled = rs.getBoolean("enabled");
    downloads = rs.getInt("downloads");
    entered = rs.getTimestamp("entered");
    enteredBy = rs.getInt("enteredby");
    modified = rs.getTimestamp("modified");
    modifiedBy = rs.getInt("modifiedby");
    if (!isVersion) {
        thumbnailFilename = rs.getString("thumbnail");
    }
    defaultFile = rs.getBoolean("default_file");
    imageWidth = rs.getInt("image_width");
    imageHeight = rs.getInt("image_height");
    comment = rs.getString("comment");
    featuredFile = rs.getBoolean("featured_file");
    ratingCount = DatabaseUtils.getInt(rs, "rating_count", 0);
    ratingValue = DatabaseUtils.getInt(rs, "rating_value", 0);
    ratingAvg = DatabaseUtils.getDouble(rs, "rating_avg", 0.0);
    inappropriateCount = DatabaseUtils.getInt(rs, "inappropriate_count", 0);
}

From source file:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java

/**
 * Get a list of StartedJobInfo objects from a resultset of entries 
 * from runningJobsHistory table./*from  w  ww. j a v a 2s  . co m*/
 * @param rs a resultset with entries from table runningJobsHistory.
 * @return a list of StartedJobInfo objects from the resultset
 * @throws SQLException If any problems reading data from the resultset
 */
private List<StartedJobInfo> listFromResultSet(ResultSet rs) throws SQLException {
    List<StartedJobInfo> list = new LinkedList<StartedJobInfo>();
    while (rs.next()) {
        StartedJobInfo sji = new StartedJobInfo(rs.getString(HM_COLUMN.harvestName.rank()),
                rs.getLong(HM_COLUMN.jobId.rank()));
        sji.setElapsedSeconds(rs.getLong(HM_COLUMN.elapsedSeconds.rank()));
        sji.setHostUrl(rs.getString(HM_COLUMN.hostUrl.rank()));
        sji.setProgress(rs.getDouble(HM_COLUMN.progress.rank()));
        sji.setQueuedFilesCount(rs.getLong(HM_COLUMN.queuedFilesCount.rank()));
        sji.setTotalQueuesCount(rs.getLong(HM_COLUMN.totalQueuesCount.rank()));
        sji.setActiveQueuesCount(rs.getLong(HM_COLUMN.activeQueuesCount.rank()));
        sji.setExhaustedQueuesCount(rs.getLong(HM_COLUMN.exhaustedQueuesCount.rank()));
        sji.setAlertsCount(rs.getLong(HM_COLUMN.alertsCount.rank()));
        sji.setDownloadedFilesCount(rs.getLong(HM_COLUMN.downloadedFilesCount.rank()));
        sji.setCurrentProcessedKBPerSec(rs.getLong(HM_COLUMN.currentProcessedKBPerSec.rank()));
        sji.setProcessedKBPerSec(rs.getLong(HM_COLUMN.processedKBPerSec.rank()));
        sji.setCurrentProcessedDocsPerSec(rs.getDouble(HM_COLUMN.currentProcessedDocsPerSec.rank()));
        sji.setProcessedDocsPerSec(rs.getDouble(HM_COLUMN.processedDocsPerSec.rank()));
        sji.setActiveToeCount(rs.getInt(HM_COLUMN.activeToeCount.rank()));
        sji.setStatus(CrawlStatus.values()[rs.getInt(HM_COLUMN.status.rank())]);
        sji.setTimestamp(new Date(rs.getTimestamp(HM_COLUMN.tstamp.rank()).getTime()));

        list.add(sji);
    }
    return list;
}

From source file:org.ohmage.query.impl.CampaignQueries.java

public Campaign getCampaignInformation(final String campaignId) throws DataAccessException {
    try {//from   w  w w  .  j av a  2s  . c  om
        return getJdbcTemplate().queryForObject(SQL_GET_CAMPAIGN_INFORMATION, new Object[] { campaignId },
                new RowMapper<Campaign>() {
                    @Override
                    public Campaign mapRow(ResultSet rs, int rowNum) throws SQLException {
                        URL iconUrl = null;
                        String iconString = rs.getString("icon_url");
                        if (iconString != null) {
                            try {
                                iconUrl = new URL(iconString);
                            } catch (MalformedURLException e) {
                                // This parameter is still experimental, so
                                // we will leave this alone for now.
                            }
                        }

                        try {
                            return new Campaign(campaignId, rs.getString("name"), rs.getString("description"),
                                    iconUrl, rs.getString("authored_by"),
                                    Campaign.RunningState.valueOf(rs.getString("running_state").toUpperCase()),
                                    Campaign.PrivacyState.valueOf(rs.getString("privacy_state").toUpperCase()),
                                    new DateTime(rs.getTimestamp("creation_timestamp").getTime()),
                                    new HashMap<String, Survey>(0), rs.getString("xml"));
                        } catch (DomainException e) {
                            throw new SQLException("There was a problem creating the campaign.", e);
                        }
                    }
                });
    } catch (org.springframework.dao.IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() > 1) {
            throw new DataAccessException("Mutiple campaigns have the same ID: " + campaignId, e);
        }

        return null;
    } catch (org.springframework.dao.DataAccessException e) {
        throw new DataAccessException(
                "Error executing SQL '" + SQL_GET_CAMPAIGN_INFORMATION + "' with parameter: " + campaignId, e);
    }
}

From source file:morphy.command.LoginsCommand.java

public void process(String arguments, UserSession userSession) {
    /*if (arguments.equals("")) {
       process(userSession.getUser().getUserName(),userSession);
       return;/*  w ww  . j a  v a  2  s  .  c  o m*/
    }*/
    /*    log googlephone
       googlephone has not logged on.
     */
    /* log YUBBUB
       Sun Aug  7, 13:00 MDT 2011: YUBBUB(U)            login 
       log YUBBUBTWO
       There is no player matching the name yubbubtwo.
     */

    arguments = arguments.trim();

    String username = arguments;

    if (username.equals("")) {
        username = userSession.getUser().getUserName();
    }

    if (username.equals("*")) {
        new LLoginsCommand().process("", userSession);
        return;
    }

    int strlen = username.length();
    if (strlen < 2) {
        userSession.send("You need to specify at least two characters of the name.");
        return;
    }
    if (!arguments.contains("*") && !StringUtils.isAlpha(username)) {
        userSession.send(username + " is not a valid handle.");
        return;
    }
    if (arguments.contains("*"))
        username = username.replace("*", "%");

    boolean isAdmin = UserService.getInstance().isAdmin(userSession.getUser().getUserName());
    StringBuilder b = new StringBuilder();
    final java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE MMM dd, HH:mm z yyyy");

    int limit = 20;
    int count = 0;

    String query = "SELECT COUNT(*) FROM `logins` WHERE `username` LIKE '" + username + "'";
    ResultSet rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    try {
        if (rs.next()) {
            count = rs.getInt(1);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }

    if (limit > count)
        limit = count;

    query = "SELECT `id` FROM (SELECT `id` FROM `logins` WHERE `username` LIKE '" + username
            + "' ORDER BY `id` DESC) t LIMIT " + limit;
    rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    int[] arr = new int[limit];
    try {
        int index = 0;
        while (rs.next()) {
            arr[index++] = rs.getInt(1);
        }
        if (index == 0) {
            // this user has never connected it seems.
            if (username.contains("%")) {
                // this is a feature that is NOT part of FICS.
                userSession.send("No usernames matching the pattern " + username.replace("%", "*")
                        + " have ever logged in.");
                return;
            } else {
                userSession.send(username + " has not logged on.");
                return;
            }
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }
    java.util.Arrays.sort(arr);
    StringBuilder queryBuilder = new StringBuilder(125);
    queryBuilder.append("SELECT `id`,`username`,CONVERT_TZ(`timestamp`,'UTC','SYSTEM'),`type`"
            + (isAdmin ? ",`ipAddress`" : "") + " " + "FROM `logins` WHERE `id` IN ("); // WHERE `username` LIKE '" + username + "'
    for (int i = 0; i < arr.length; i++) {
        queryBuilder.append(arr[i]);
        if (i != arr.length - 1)
            queryBuilder.append(",");
    }
    queryBuilder.append(") ORDER BY `id` ASC");
    query = queryBuilder.toString();
    rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    try {
        while (rs.next()) {
            String line = "";
            if (!isAdmin)
                line = String.format("%26s: %-20s %s", sdf.format(rs.getTimestamp(3).getTime()),
                        rs.getString(2), rs.getString(4));
            if (isAdmin)
                line = String.format("%26s: %-20s %7s from %s", sdf.format(rs.getTimestamp(3).getTime()),
                        rs.getString(2), rs.getString(4), rs.getString(5));
            if (rs.next()) {
                line += "\n";
                rs.previous();
            }
            b.append(line);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }

    userSession.send(b.toString());
}