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.apache.roller.weblogger.ui.rendering.pagers.WeblogEntriesListPager.java

/** Get last updated time from items in pager */
public Date getLastUpdated() {
    if (lastUpdated == null) {
        // feeds are sorted by pubtime, so first might not be last updated
        List<WeblogEntryWrapper> items = (List<WeblogEntryWrapper>) getItems();
        if (getItems() != null && getItems().size() > 0) {
            Timestamp newest = ((WeblogEntryWrapper) getItems().get(0)).getUpdateTime();
            for (WeblogEntryWrapper e : items) {
                if (e.getUpdateTime().after(newest)) {
                    newest = e.getPubTime();
                }/* w w  w  . j av  a2 s. c  om*/
            }
            lastUpdated = new Date(newest.getTime());
        } else {
            // no update so we assume it's brand new
            lastUpdated = new Date();
        }
    }
    return lastUpdated;
}

From source file:org.apache.ofbiz.service.job.PersistedServiceJob.java

/**
 * Creates a new PersistedServiceJob//from   ww w  .j av a 2 s. c  om
 * @param dctx
 * @param jobValue
 * @param req
 */
public PersistedServiceJob(DispatchContext dctx, GenericValue jobValue, GenericRequester req) {
    super(dctx, jobValue.getString("jobId"), jobValue.getString("jobName"), null, null, req);
    this.delegator = dctx.getDelegator();
    this.jobValue = jobValue;
    Timestamp storedDate = jobValue.getTimestamp("runTime");
    this.startTime = storedDate.getTime();
    this.maxRetry = jobValue.get("maxRetry") != null ? jobValue.getLong("maxRetry").longValue() : -1;
    Long retryCount = jobValue.getLong("currentRetryCount");
    if (retryCount != null) {
        this.currentRetryCount = retryCount.longValue();
    } else {
        // backward compatibility
        this.currentRetryCount = getRetries(this.delegator);
    }
}

From source file:org.kuali.kpme.core.block.dao.CalendarBlockDaoJdbcImpl.java

@Override
public DateTime getLatestEndTimestampForEarnCode(String earnCode, String calendarBlockType) {

    PreparedStatementCreator timeBlockPSC = new PreparedStatementCreator() {

        @Override/*from w  ww  . j  a v  a  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 earn_code = ?");

            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 earn_code = ?");

            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, earnCode);
        }

        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.jdesigner.platform.web.converter.DateTimeConverter.java

/**
 * Convert the input object into a Date object of the specified type.
 * <p>// w  w w  . j  a va2s.  com
 * This method handles conversions between the following types:
 * <ul>
 * <li><code>java.util.Date</code></li>
 * <li><code>java.util.Calendar</code></li>
 * <li><code>java.sql.Date</code></li>
 * <li><code>java.sql.Time</code></li>
 * <li><code>java.sql.Timestamp</code></li>
 * </ul>
 * 
 * It also handles conversion from a <code>String</code> to any of the above
 * types.
 * <p>
 * 
 * For <code>String</code> conversion, if the converter has been configured
 * with one or more patterns (using <code>setPatterns()</code>), then the
 * conversion is attempted with each of the specified patterns. Otherwise
 * the default <code>DateFormat</code> for the default locale (and
 * <i>style</i> if configured) will be used.
 * 
 * @param targetType
 *            Data type to which this value should be converted.
 * @param value
 *            The input value to be converted.
 * @return The converted value.
 * @throws Exception
 *             if conversion cannot be performed successfully
 */
protected Object convertToType(Class targetType, Object value) throws Exception {

    // Class sourceType = value.getClass();

    // Handle java.sql.Timestamp
    if (value instanceof java.sql.Timestamp) {

        // ---------------------- JDK 1.3 Fix ----------------------
        // N.B. Prior to JDK 1.4 the Timestamp's getTime() method
        // didn't include the milliseconds. The following code
        // ensures it works consistently accross JDK versions
        java.sql.Timestamp timestamp = (java.sql.Timestamp) value;
        long timeInMillis = ((timestamp.getTime() / 1000) * 1000);
        timeInMillis += timestamp.getNanos() / 1000000;
        // ---------------------- JDK 1.3 Fix ----------------------
        return toDate(targetType, timeInMillis);
    }

    // Handle Date (includes java.sql.Date & java.sql.Time)
    if (value instanceof Date) {
        Date date = (Date) value;
        return toDate(targetType, date.getTime());
    }

    // Handle Calendar
    if (value instanceof Calendar) {
        Calendar calendar = (Calendar) value;
        return toDate(targetType, calendar.getTime().getTime());
    }

    // Handle Long
    if (value instanceof Long) {
        Long longObj = (Long) value;
        return toDate(targetType, longObj.longValue());
    }

    // Convert all other types to String & handle
    String stringValue = value.toString().trim();
    if (stringValue.length() == 0) {
        return handleMissing(targetType);
    }

    // Default String conversion
    return toDate(targetType, stringValue);

}

From source file:ome.services.JobBean.java

@Transactional(readOnly = false)
@RolesAllowed("user")
public long submit(Job newJob) {
    reset(); // TODO or do we want to just checkState
    // and throw an exception if this is a stale handle.

    EventContext ec = getCurrentEventContext();
    long ms = System.currentTimeMillis();
    Timestamp now = new Timestamp(ms);

    // Values that can't be set by the user
    newJob.setUsername(ec.getCurrentUserName());
    newJob.setGroupname(ec.getCurrentGroupName());
    newJob.setType(ec.getCurrentEventType());
    newJob.setStarted(null);//from   www  .  j  a va 2 s.c  om
    newJob.setFinished(null);
    newJob.setSubmitted(now);

    // Values that the user can optionally set
    Timestamp t = newJob.getScheduledFor();
    if (t == null || t.getTime() < now.getTime()) {
        newJob.setScheduledFor(now);
    }
    JobStatus s = newJob.getStatus();
    if (s == null) {
        newJob.setStatus(new JobStatus(JobHandle.SUBMITTED));
    } else {
        // Verifying the status
        if (s.getId() != null) {
            try {
                s = iQuery.get(JobStatus.class, s.getId());
            } catch (Exception e) {
                throw new ApiUsageException("Unknown job status: " + s);
            }
        }

        if (s.getValue() == null) {
            throw new ApiUsageException("JobStatus must have id or value set.");
        } else {
            if (!(s.getValue().equals(SUBMITTED) || s.getValue().equals(WAITING))) {
                throw new ApiUsageException("Currently only SUBMITTED and WAITING are accepted as JobStatus");
            }
        }
    }
    String m = newJob.getMessage();
    if (m == null) {
        newJob.setMessage("");
    }

    // Here it is necessary to perform a {@link SecureAction} since
    // SecuritySystem#isSystemType() returns true for all Jobs
    newJob.getDetails().copy(sec.newTransientDetails(newJob));
    newJob = secureSave(newJob);

    jobId = newJob.getId();

    return jobId;
}

From source file:org.kuali.kpme.core.block.dao.CalendarBlockDaoJdbcImpl.java

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

    PreparedStatementCreator timeBlockPSC = new PreparedStatementCreator() {

        @Override//from w w w  .  j a v  a2s  .  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:com.ganji.tungsten.replicator.applier.GanjiMcQueueApplier.java

private boolean insert2Queue(String schema, String table, String actionName, JSONObject obj, Timestamp tm)
        throws ApplierException {
    obj.put("__schema", schema);
    obj.put("__table", table);
    obj.put("__action", actionName);
    obj.put("__ts", tm.getTime());

    Future<Boolean> f = mc_conn.set(queue_name, 0, obj.toJSONString());
    try {//w  ww  .  ja va2s.  c  o  m
        Boolean b = f.get();
        return b.booleanValue();
    } catch (InterruptedException e) {
        throw new ApplierException(e);
    } catch (ExecutionException e) {
        throw new ApplierException(e);
    }

    //return false;
}

From source file:com.appeligo.alerts.AlertManager.java

public void checkIfPending(ProgramAlert programAlert) {
    if (programAlert.isDeleted() || programAlert.isDisabled() || (programAlert.getUser() == null)) {
        if (log.isDebugEnabled())
            log.debug("programAlert deleted=" + programAlert.isDeleted() + ", disabled="
                    + programAlert.isDisabled() + ", user=" + programAlert.getUser());
        return;/*  w ww . j  av  a2s  . c  om*/
    }
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 14); // 14 days in the future
    List<ScheduledProgram> scheduledPrograms = epg.getNextShowings(programAlert.getUser().getLineupId(),
            programAlert.getProgramId(), programAlert.isNewEpisodes(), true);

    log.debug("Adding alert for program " + programAlert.getProgramId() + ", list of upcoming count="
            + scheduledPrograms.size());

    boolean pendingAlertsAdded = false;
    for (ScheduledProgram scheduledProgram : scheduledPrograms) {
        if (programAlert.isNewEpisodes() && // only alert on new episodes
                (!scheduledProgram.isNewEpisode())) {
            continue;
        }
        if (scheduledProgram == null) {
            if (log.isDebugEnabled())
                log.debug("checkIfPending did not find an upcoming program");
        }
        if (scheduledProgram != null) {
            if (log.isDebugEnabled())
                log.debug("Found next showing " + scheduledProgram.getProgramTitle() + ", start: "
                        + scheduledProgram.getStartTime());

            String callSign = scheduledProgram.getNetwork().getStationCallSign();
            Timestamp startTime = new Timestamp(scheduledProgram.getStartTime().getTime());
            Timestamp alertTime = new Timestamp(startTime.getTime() - (programAlert.getAlertMinutes() * 60000));

            Set<PendingAlert> pendingAlerts = programAlert.getLivePendingAlerts();
            for (PendingAlert pa : pendingAlerts) {
                if ((!pa.isDeleted()) && (pa.getCallSign().equals(callSign))
                        && (pa.getProgramStartTime().equals(startTime))
                        && (pa.getAlertTime().equals(alertTime))) {
                    if (log.isDebugEnabled())
                        log.debug("found matching pending alert");
                    continue;
                }
            }

            PendingAlert pendingAlert = new PendingAlert();
            pendingAlert.setProgramAlert(programAlert);
            pendingAlert.setProgramId(scheduledProgram.getProgramId());
            pendingAlert.setUserId(programAlert.getUser().getUserId());
            pendingAlert.setCallSign(callSign);
            pendingAlert.setProgramStartTime(scheduledProgram.getStartTime());
            pendingAlert.setAlertTime(alertTime);

            if (log.isDebugEnabled())
                log.debug("adding pending alert");
            pendingAlerts.add(pendingAlert);

            pendingAlertsAdded = true;
        }
    }
    if (pendingAlertsAdded) {
        Transaction currentTransaction = TransactionManager.currentTransaction();
        if (currentTransaction == null) {
            synchronized (pendingAlertThread) {
                if (log.isDebugEnabled())
                    log.debug("Notifying pending alert thread immediately");
                pendingAlertThread.notifyAll();
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Will Notify pending alert thread after transaction is done");
            currentTransaction.registerSynchronization(new Synchronization() {

                public void afterCompletion(int arg0) {
                    synchronized (pendingAlertThread) {
                        if (log.isDebugEnabled())
                            log.debug("Notifying pending alert thread now that the transaction is done");
                        pendingAlertThread.notifyAll();
                    }
                }

                public void beforeCompletion() {
                    // Not needed
                }
            });
        }
    }
}

From source file:org.kuali.kfs.module.ar.document.service.impl.ContractsGrantsBillingAwardVerificationServiceImpl.java

/**
 * @see org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService#hasNoBillsToInvoice(org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward)
 *///from  w w w  .  j a  v a 2 s.c om
@Override
public boolean hasBillsToInvoice(ContractsAndGrantsBillingAward award) {
    boolean hasBillsToInvoice = true;
    if (award.getBillingFrequencyCode().equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {

        List<Bill> bills = new ArrayList<Bill>();
        List<Bill> validBills = new ArrayList<Bill>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(KFSPropertyConstants.PROPOSAL_NUMBER, award.getProposalNumber());
        map.put(KFSPropertyConstants.ACTIVE, true);

        bills = (List<Bill>) businessObjectService.findMatching(Bill.class, map);
        // To retrieve the previous period end Date to check for milestones and billing schedule.

        Timestamp ts = new Timestamp(new java.util.Date().getTime());
        java.sql.Date today = new java.sql.Date(ts.getTime());
        AccountingPeriod currPeriod = accountingPeriodService.getByDate(today);
        java.sql.Date[] pair = verifyBillingFrequencyService
                .getStartDateAndEndDateOfPreviousBillingPeriod(award, currPeriod);
        java.sql.Date invoiceDate = pair[1];

        for (Bill awdBill : bills) {
            if (awdBill.getBillDate() != null && !invoiceDate.before(awdBill.getBillDate())
                    && !awdBill.isBilled() && awdBill.getEstimatedAmount().isGreaterThan(KualiDecimal.ZERO)) {
                validBills.add(awdBill);
            }
        }
        if (CollectionUtils.isEmpty(validBills)) {
            hasBillsToInvoice = false;
        }
    }
    return hasBillsToInvoice;
}