Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

In this page you can find the example usage for java.sql Timestamp getTime.

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:org.nuxeo.ecm.core.storage.sql.db.dialect.DialectOracle.java

@Override
@SuppressWarnings("boxing")
public Serializable getFromResultSet(ResultSet rs, int index, Column column) throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
        String string = rs.getString(index);
        if (column.getType() == ColumnType.BLOBID && string != null) {
            return column.getModel().getBinary(string);
        } else {/*  ww w  .j  a  v a  2  s.c o  m*/
            return string;
        }
    case Types.CLOB:
        // Oracle cannot read CLOBs using rs.getString when the ResultSet is
        // a ScrollableResultSet (the standard OracleResultSetImpl works
        // fine).
        Reader r = rs.getCharacterStream(index);
        if (r == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[4096];
        try {
            int n;
            while ((n = r.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, n));
            }
        } catch (IOException e) {
            log.error("Cannot read CLOB", e);
        }
        return sb.toString();
    case Types.BIT:
        return rs.getBoolean(index);
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
        return rs.getLong(index);
    case Types.DOUBLE:
        return rs.getDouble(index);
    case Types.TIMESTAMP:
        Timestamp ts = rs.getTimestamp(index);
        if (ts == null) {
            return null;
        } else {
            Serializable cal = new GregorianCalendar(); // XXX timezone
            ((Calendar) cal).setTimeInMillis(ts.getTime());
            return cal;
        }
    }
    throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
}

From source file:se.crisp.codekvast.warehouse.file_import.ImportDAOImpl.java

@Override
public boolean saveInvocation(Invocation invocation, ImportContext context) {
    long applicationId = context.getApplicationId(invocation.getLocalApplicationId());
    long methodId = context.getMethodId(invocation.getLocalMethodId());
    long jvmId = context.getJvmId(invocation.getLocalJvmId());
    Timestamp invokedAt = new Timestamp(invocation.getInvokedAtMillis());

    Timestamp oldInvokedAt = queryForTimestamp(
            "SELECT invokedAtMillis FROM invocations WHERE applicationId = ? AND methodId = ? AND jvmId = ? ",
            applicationId, methodId, jvmId);

    boolean databaseTouched = false;
    if (oldInvokedAt == null) {
        jdbcTemplate.update(//www  .j  a v a2 s.c  o  m
                "INSERT INTO invocations(applicationId, methodId, jvmId, invokedAtMillis, invocationCount, status) "
                        + "VALUES(?, ?, ?, ?, ?, ?) ",
                applicationId, methodId, jvmId, invokedAt.getTime(), invocation.getInvocationCount(),
                invocation.getStatus().name());
        log.trace("Inserted invocation {}:{}:{} {}", applicationId, methodId, jvmId, invokedAt);
        databaseTouched = true;
    } else if (invokedAt.after(oldInvokedAt)) {
        jdbcTemplate.update(
                "UPDATE invocations SET invokedAtMillis = ?, invocationCount = invocationCount + ?, status = ? "
                        + "WHERE applicationId = ? AND methodId = ? AND jvmId = ? ",
                invokedAt.getTime(), invocation.getInvocationCount(), invocation.getStatus().name(),
                applicationId, methodId, jvmId);
        log.trace("Updated invocation {}:{}:{} {}", applicationId, methodId, jvmId, invokedAt);
        databaseTouched = true;
    } else if (oldInvokedAt.equals(invokedAt)) {
        log.trace("Ignoring invocation, same row exists in database");
    } else {
        log.trace("Ignoring invocation, a newer row exists in database");
    }
    return databaseTouched;
}

From source file:com.oltpbenchmark.benchmarks.seats.SEATSProfile.java

/**
 * Return a random date in the future (after the start of upcoming flights)
 * @return/*  w ww.  j  av a2 s . com*/
 */
public Timestamp getRandomUpcomingDate() {
    Timestamp upcoming_start_date = this.flight_upcoming_date;
    int offset = rng.nextInt((int) this.getFlightFutureDays());
    return (new Timestamp(upcoming_start_date.getTime() + (offset * SEATSConstants.MILLISECONDS_PER_DAY)));
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static int weekNumber(Timestamp input, int startOfWeek) {
    Calendar calendar = Calendar.getInstance();
    calendar.setFirstDayOfWeek(startOfWeek);

    if (startOfWeek == Calendar.MONDAY) {
        calendar.setMinimalDaysInFirstWeek(4);
    } else if (startOfWeek == Calendar.SUNDAY) {
        calendar.setMinimalDaysInFirstWeek(3);
    }//from   w  w  w. ja v  a  2s  .c  o  m

    calendar.setTime(new Date(input.getTime()));
    return calendar.get(Calendar.WEEK_OF_YEAR);
}

From source file:org.apache.oozie.command.coord.CoordMaterializeTransitionXCommand.java

/**
 * Calculate startMatdTime and endMatdTime from job's start time if next materialized time is null
 *
 * @throws CommandException thrown if failed to calculate startMatdTime and endMatdTime
 *///  ww  w.j a va2s .c o m
protected void calcMatdTime() throws CommandException {
    Timestamp startTime = coordJob.getNextMaterializedTimestamp();
    if (startTime == null) {
        startTime = coordJob.getStartTimestamp();
    }
    // calculate end time by adding materializationWindow to start time.
    // need to convert materializationWindow from secs to milliseconds
    long startTimeMilli = startTime.getTime();
    long endTimeMilli = startTimeMilli + (materializationWindow * 1000);

    startMatdTime = DateUtils.toDate(new Timestamp(startTimeMilli));
    endMatdTime = DateUtils.toDate(new Timestamp(endTimeMilli));
    endMatdTime = getMaterializationTimeForCatchUp(endMatdTime);
    // if MaterializationWindow end time is greater than endTime
    // for job, then set it to endTime of job
    Date jobEndTime = coordJob.getEndTime();
    if (endMatdTime.compareTo(jobEndTime) > 0) {
        endMatdTime = jobEndTime;
    }

    LOG.debug("Materializing coord job id=" + jobId + ", start=" + DateUtils.formatDateOozieTZ(startMatdTime)
            + ", end=" + DateUtils.formatDateOozieTZ(endMatdTime) + ", window=" + materializationWindow);
}

From source file:org.apache.hadoop.hive.ql.exec.vector.expressions.TestVectorTimestampExpressions.java

private byte[] encodeTime(Timestamp timestamp) {
    ByteBuffer encoded;/*from w  ww .ja va 2  s  .com*/
    long time = timestamp.getTime();
    try {
        String formatted = dateFormat.format(new Date(time));
        encoded = Text.encode(formatted);
    } catch (CharacterCodingException e) {
        throw new RuntimeException(e);
    }
    return Arrays.copyOf(encoded.array(), encoded.limit());
}

From source file:com.aionengine.gameserver.services.BrokerService.java

private void checkExpiredItems() {
    Map<Integer, BrokerItem> asmoBrokerItems = getRaceBrokerItems(Race.ASMODIANS);
    Map<Integer, BrokerItem> elyosBrokerItems = getRaceBrokerItems(Race.ELYOS);

    Timestamp currentTime = new Timestamp(Calendar.getInstance().getTimeInMillis());

    for (BrokerItem item : asmoBrokerItems.values()) {
        if (item != null && item.getExpireTime().getTime() <= currentTime.getTime()) {
            expireItem(Race.ASMODIANS, item);
            asmodianBrokerItems.remove(item.getItemUniqueId());
        }//w  w  w .java  2s. c o m
    }

    for (BrokerItem item : elyosBrokerItems.values()) {
        if (item != null && item.getExpireTime().getTime() <= currentTime.getTime()) {
            expireItem(Race.ELYOS, item);
            this.elyosBrokerItems.remove(item.getItemUniqueId());
        }
    }
}

From source file:org.apache.wiki.auth.user.JDBCUserDatabase.java

/**
 * @see org.apache.wiki.auth.user.UserDatabase#rename(String, String)
 *///w  ww  . ja v a2 s.  c  o  m
public void rename(String loginName, String newName)
        throws NoSuchPrincipalException, DuplicateUserException, WikiSecurityException {
    // Get the existing user; if not found, throws NoSuchPrincipalException
    UserProfile profile = findByLoginName(loginName);

    // Get user with the proposed name; if found, it's a collision
    try {
        UserProfile otherProfile = findByLoginName(newName);
        if (otherProfile != null) {
            throw new DuplicateUserException("security.error.cannot.rename", newName);
        }
    } catch (NoSuchPrincipalException e) {
        // Good! That means it's safe to save using the new name
    }

    Connection conn = null;
    try {
        // Open the database connection
        conn = m_ds.getConnection();
        if (m_supportsCommits) {
            conn.setAutoCommit(false);
        }

        Timestamp ts = new Timestamp(System.currentTimeMillis());
        Date modDate = new Date(ts.getTime());

        // Change the login ID for the user record
        PreparedStatement ps = conn.prepareStatement(m_renameProfile);
        ps.setString(1, newName);
        ps.setTimestamp(2, ts);
        ps.setString(3, loginName);
        ps.execute();
        ps.close();

        // Change the login ID for the role records
        ps = conn.prepareStatement(m_renameRoles);
        ps.setString(1, newName);
        ps.setString(2, loginName);
        ps.execute();
        ps.close();

        // Set the profile name and mod time
        profile.setLoginName(newName);
        profile.setLastModified(modDate);

        // Commit and close connection
        if (m_supportsCommits) {
            conn.commit();
        }
    } catch (SQLException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.schedule.S2SPollingTask.java

/**
 * //  w w  w. ja v  a 2  s  . co m
 * This method processes data that is to be sent by mail
 * 
 * @param propList
 * @param mailInfo
 * @return {@link MailMessage}
 */
private MailMessage parseNGetMailAttr(Vector<SubmissionData> propList, MailInfo mailInfo) {
    if (propList == null || propList.isEmpty()) {
        return null;
    }

    MailMessage mailMessage = mailInfo.getMailMessage();
    StringBuffer message = new StringBuffer(mailMessage.getMessage());

    for (SubmissionData submissionData : propList) {

        S2sAppSubmission appSubmission = submissionData.getS2sAppSubmission();
        Timestamp lastNotifiedDate = appSubmission.getLastNotifiedDate();
        Timestamp statusChangedDate = appSubmission.getLastModifiedDate();
        Calendar lastNotifiedDateCal = Calendar.getInstance();

        if (lastNotifiedDate != null) {
            lastNotifiedDateCal.setTimeInMillis(lastNotifiedDate.getTime());
        }
        Calendar statusChangedDateCal = Calendar.getInstance();
        if (statusChangedDate != null) {
            statusChangedDateCal.setTimeInMillis(statusChangedDate.getTime());
        }
        Calendar recDateCal = Calendar.getInstance();
        recDateCal.setTimeInMillis(appSubmission.getReceivedDate().getTime());

        long lastModifiedTime = statusChangedDate == null ? appSubmission.getReceivedDate().getTime()
                : statusChangedDate.getTime();
        Timestamp today = new Timestamp(new Date().getTime());
        long delta = today.getTime() - lastModifiedTime;
        double deltaHrs = ((double) Math.round((delta / (1000.0d * 60.0d * 60.0d)) * Math.pow(10.0, 2))) / 100;

        int days = 0;
        int hrs = 0;
        if (deltaHrs > 0) {
            days = (int) deltaHrs / 24;
            hrs = (int) (((double) Math.round((deltaHrs % 24) * Math.pow(10.0, 2))) / 100);

        }
        if (propList.size() > 0) {
            SubmissionData prevSubmissionData = propList.elementAt(propList.size() - 1);
            if (!prevSubmissionData.getSortId().equals(submissionData.getSortId())) {
                message.append("\n\n");
                message.append(sortMsgKeyMap.get(submissionData.getSortId()));
                message.append("\n____________________________________________________");
            }
        } else {
            message.append("\n\n");
            message.append(sortMsgKeyMap.get(submissionData.getSortId()));
            message.append("\n____________________________________________________");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        message.append('\n');
        message.append("Proposal Number : " + appSubmission.getProposalNumber() + "\n");
        message.append("Received Date : ");
        message.append(dateFormat.format(appSubmission.getReceivedDate()));
        message.append('\n');
        message.append("Grants.Gov Tracking Id : ");
        message.append(appSubmission.getGgTrackingId());
        message.append('\n');
        String agTrackId = appSubmission.getAgencyTrackingId() == null ? "Not updated yet"
                : appSubmission.getAgencyTrackingId();
        message.append("Agency Tracking Id : ");
        message.append(agTrackId);
        message.append('\n');
        message.append("Current Status : ");
        message.append(appSubmission.getStatus());
        message.append('\n');
        String stChnageDate = appSubmission.getLastModifiedDate() == null ? "Not updated yet"
                : dateFormat.format(appSubmission.getLastModifiedDate());
        message.append("Last Status Change : " + stChnageDate + "\t *** " + days + " day(s) and " + hrs
                + " hour(s) ***\n");
        message.append('\n');
    }
    message.append('\n');
    message.append(mailInfo.getFooter());
    mailMessage.setMessage(message.toString());

    return mailMessage;
}

From source file:org.kuali.kra.s2s.polling.S2SPollingTask.java

/**
 * //from   w  w w  .java 2 s .c om
 * This method processes data that is to be sent by mail
 * 
 * @param propList
 * @param mailInfo
 * @return {@link MailMessage}
 */
private MailMessage parseNGetMailAttr(Vector<SubmissionData> propList, MailInfo mailInfo) {
    if (propList == null || propList.isEmpty()) {
        return null;
    }

    MailMessage mailMessage = mailInfo.getMailMessage();
    StringBuffer message = new StringBuffer(mailMessage.getMessage());

    for (SubmissionData submissionData : propList) {

        S2sAppSubmission appSubmission = submissionData.getS2sAppSubmission();
        Timestamp lastNotifiedDate = appSubmission.getLastNotifiedDate();
        Timestamp statusChangedDate = appSubmission.getLastModifiedDate();
        Calendar lastNotifiedDateCal = dateTimeService.getCurrentCalendar();

        if (lastNotifiedDate != null) {
            lastNotifiedDateCal.setTimeInMillis(lastNotifiedDate.getTime());
        }
        Calendar statusChangedDateCal = dateTimeService.getCurrentCalendar();
        if (statusChangedDate != null) {
            statusChangedDateCal.setTimeInMillis(statusChangedDate.getTime());
        }
        Calendar recDateCal = dateTimeService.getCurrentCalendar();
        recDateCal.setTimeInMillis(appSubmission.getReceivedDate().getTime());

        long lastModifiedTime = statusChangedDate == null ? appSubmission.getReceivedDate().getTime()
                : statusChangedDate.getTime();
        Timestamp today = dateTimeService.getCurrentTimestamp();
        long delta = today.getTime() - lastModifiedTime;
        double deltaHrs = ((double) Math.round((delta / (1000.0d * 60.0d * 60.0d)) * Math.pow(10.0, 2))) / 100;

        int days = 0;
        int hrs = 0;
        if (deltaHrs > 0) {
            days = (int) deltaHrs / 24;
            hrs = (int) (((double) Math.round((deltaHrs % 24) * Math.pow(10.0, 2))) / 100);

        }
        if (propList.size() > 0) {
            SubmissionData prevSubmissionData = propList.elementAt(propList.size() - 1);
            if (!prevSubmissionData.getSortId().equals(submissionData.getSortId())) {
                message.append("\n\n");
                message.append(sortMsgKeyMap.get(submissionData.getSortId()));
                message.append("\n____________________________________________________");
            }
        } else {
            message.append("\n\n");
            message.append(sortMsgKeyMap.get(submissionData.getSortId()));
            message.append("\n____________________________________________________");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        message.append('\n');
        message.append("Proposal Number : " + appSubmission.getProposalNumber() + "\n");
        message.append("Received Date : ");
        message.append(dateFormat.format(appSubmission.getReceivedDate()));
        message.append('\n');
        message.append("Grants.Gov Tracking Id : ");
        message.append(appSubmission.getGgTrackingId());
        message.append('\n');
        String agTrackId = appSubmission.getAgencyTrackingId() == null ? "Not updated yet"
                : appSubmission.getAgencyTrackingId();
        message.append("Agency Tracking Id : ");
        message.append(agTrackId);
        message.append('\n');
        message.append("Current Status : ");
        message.append(appSubmission.getStatus());
        message.append('\n');
        String stChnageDate = appSubmission.getLastModifiedDate() == null ? "Not updated yet"
                : dateFormat.format(appSubmission.getLastModifiedDate());
        message.append("Last Status Change : " + stChnageDate + "\t *** " + days + " day(s) and " + hrs
                + " hour(s) ***\n");
        message.append('\n');
    }
    message.append('\n');
    message.append(mailInfo.getFooter());
    mailMessage.setMessage(message.toString());

    return mailMessage;
}