List of usage examples for java.util Date before
public boolean before(Date when)
From source file:mekhq.campaign.mission.Contract.java
/** * Get the number of months left in this contract after the given date. Partial months are counted as * full months.//from ww w . j a v a 2 s. com * * @param date * @return */ public int getMonthsLeft(Date date) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(Calendar.MONTH, 1); date = cal.getTime(); int monthsLeft = 0; while (date.before(endDate) || date.equals(endDate)) { monthsLeft++; cal.add(Calendar.MONTH, 1); date = cal.getTime(); } return monthsLeft; }
From source file:gov.nih.nci.cabig.labviewer.grid.LabViewerRegistrationConsumer.java
public void rollback(Registration registration) throws RemoteException, InvalidRegistrationException { log.debug("Received a rollback for participant"); ParticipantType participant = registration.getParticipant(); String participantGridId = participant.getGridId(); String participantExtension = participant.getIdentifier(0).getValue(); // obtain Connection con = dao.getConnection();// w w w. j a v a 2s .com // method returns the ctominsertdate if the participantGridId is found // in the database try { // check if Participant exists for rollback java.util.Date insertdate = dao.checkParticipantForRollback(con, participantGridId, participantExtension); if (insertdate != null) { java.util.Date currdate = new Date(); long milis1 = insertdate.getTime(); long milis2 = currdate.getTime(); long diffInMin = (milis2 - milis1) / MILLIS_PER_MINUTE; if (insertdate.before(currdate) && diffInMin < THRESHOLD_MINUTE) { // issue Participant roll back dao.rollbackParticipant(con, participantGridId, participantExtension); log.info("deleted participant"); } else { log.info("There is no participant within the threshold time for rollback"); } } else { InvalidRegistrationException ire = new InvalidRegistrationException(); ire.setFaultString( "Lab Viewer invalid patient rollback message - no patient found with given gridid"); log.fatal(ire); throw (ire); } } catch (SQLException se) { log.error("Error deleting participant", se); String msg = "Lab Viewer unable to rollback participant" + se.getMessage(); throw new RemoteException(msg); } finally { try { con.close(); } catch (SQLException e) { log.error("Error closing connection", e); } } }
From source file:org.jasig.portlet.announcements.mvc.servlet.AjaxApproveController.java
@RequestMapping public ModelAndView toggleApprove(HttpServletRequest request) throws PortletException { final Long annId = Long.valueOf(request.getParameter("annId")); final Boolean approval = Boolean.valueOf(request.getParameter("approval")); final Announcement ann = announcementService.getAnnouncement(annId); final Date startDisplay = ann.getStartDisplay(); Date endDisplay = ann.getEndDisplay(); if (endDisplay == null) { // Unspecified end date means the announcement does not expire; we // will substitute a date in the future each time this item is // evaluated. final long aYearFromNow = System.currentTimeMillis() + Announcement.MILLISECONDS_IN_A_YEAR; endDisplay = new Date(aYearFromNow); }//from w w w . j av a 2s. c om final Date now = new Date(); int status = STATUS_PENDING; // default /* Scheduled = 0 Expired = 1 Showing = 2 Pending = 3 */ if (startDisplay.after(now) && endDisplay.after(now) && approval) { status = STATUS_SCHEDULED; } else if (startDisplay.before(now) && endDisplay.after(now) && approval) { status = STATUS_SHOWING; } else if (endDisplay.before(now)) { status = STATUS_EXPIRED; } ann.setPublished(approval); announcementService.addOrSaveAnnouncement(ann); return new ModelAndView("ajaxApprove", "status", status); }
From source file:ReservationData.java
private void setDates(int arrivalDay, int arrivalMonth, int arrivalYear, int departureDay, int departureMonth, int departureYear) { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.DAY_OF_MONTH, arrivalDay); calendar.set(Calendar.MONTH, arrivalMonth); calendar.set(Calendar.YEAR, arrivalYear); Date arrivalDate = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, departureDay); calendar.set(Calendar.MONTH, departureMonth); calendar.set(Calendar.YEAR, departureYear); Date departureDate = calendar.getTime(); System.out.println(arrivalDate + " - " + departureDate); if (!arrivalDate.before(departureDate)) { // arrival date is before dep. date. setErrorMessage("The arrival date is not before the departure date"); setPageComplete(false);/* www . j a v a 2 s .c o m*/ } else { setErrorMessage(null); // clear error message. setPageComplete(true); ((ReservationWizard) getWizard()).data.arrivalDate = arrivalDate; ((ReservationWizard) getWizard()).data.departureDate = departureDate; } }
From source file:com.salesmanager.core.module.impl.application.prices.OneTimePriceModule.java
public OrderTotalSummary calculateOrderPrice(Order order, OrderTotalSummary orderSummary, OrderProduct orderProduct, OrderProductPrice productPrice, String currency, Locale locale) { // TODO Auto-generated method stub /**/* w w w. j a va 2 s. c o m*/ * activation price goes in the oneTime fees */ BigDecimal finalPrice = null; // BigDecimal discountPrice=null; // order price this type of price needs an upfront payment BigDecimal otprice = orderSummary.getOneTimeSubTotal(); if (otprice == null) { otprice = new BigDecimal(0); } // the final price is in the product price finalPrice = productPrice.getProductPriceAmount(); int quantity = orderProduct.getProductQuantity(); finalPrice = finalPrice.multiply(new BigDecimal(quantity)); otprice = otprice.add(finalPrice); orderSummary.setOneTimeSubTotal(otprice); ProductPriceSpecial pps = productPrice.getSpecial(); // Build text StringBuffer notes = new StringBuffer(); notes.append(quantity).append(" x "); notes.append(orderProduct.getProductName()); notes.append(" "); notes.append( CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency)); notes.append(" "); notes.append(productPrice.getProductPriceName()); BigDecimal originalPrice = orderProduct.getOriginalProductPrice(); if (!productPrice.isDefaultPrice()) { originalPrice = productPrice.getProductPriceAmount(); } if (pps != null) { if (pps.getProductPriceSpecialStartDate() != null && pps.getProductPriceSpecialEndDate() != null) { if (pps.getProductPriceSpecialStartDate().before(order.getDatePurchased()) && pps.getProductPriceSpecialEndDate().after(order.getDatePurchased())) { BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue()); if (dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) { BigDecimal subTotal = originalPrice .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount() .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal credit = subTotal.subtract(creditSubTotal); StringBuffer spacialNote = new StringBuffer(); spacialNote.append("<font color=\"red\">["); spacialNote.append(productPrice.getProductPriceName()); // spacialNote.append(getPriceText(currency,locale)); spacialNote.append(" "); spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); spacialNote.append("]</font>"); if (productPrice.getProductPriceAmount().doubleValue() > pps.getProductPriceSpecialAmount() .doubleValue()) { OrderTotalLine line = new OrderTotalLine(); line.setText(spacialNote.toString()); line.setCost(credit); line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); orderSummary.addDueNowCredits(line); BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge(); oneTimeCredit = oneTimeCredit.add(credit); orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit); } } } else if (pps.getProductPriceSpecialDurationDays() > -1) { Date dt = new Date(); int numDays = pps.getProductPriceSpecialDurationDays(); Date purchased = order.getDatePurchased(); Calendar c = Calendar.getInstance(); c.setTime(dt); c.add(Calendar.DATE, numDays); BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue()); if (dt.before(c.getTime()) && dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) { BigDecimal subTotal = originalPrice .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount() .multiply(new BigDecimal(orderProduct.getProductQuantity())); BigDecimal credit = subTotal.subtract(creditSubTotal); StringBuffer spacialNote = new StringBuffer(); spacialNote.append("<font color=\"red\">["); spacialNote.append(productPrice.getProductPriceName()); // spacialNote.append(getPriceText(currency,locale)); spacialNote.append(" "); spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); spacialNote.append("]</font>"); if (productPrice.getProductPriceAmount().doubleValue() > pps.getProductPriceSpecialAmount() .doubleValue()) { OrderTotalLine line = new OrderTotalLine(); line.setText(spacialNote.toString()); line.setCost(credit); line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency)); orderSummary.addDueNowCredits(line); BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge(); oneTimeCredit = oneTimeCredit.add(credit); orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit); } } } } } if (!productPrice.isDefaultPrice()) { // add a price description OrderTotalLine scl = new OrderTotalLine(); scl.setText(notes.toString()); scl.setCost(finalPrice); scl.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(finalPrice, currency)); orderSummary.addOtherDueNowPrice(scl); } return orderSummary; }
From source file:biz.gabrys.maven.plugins.lesscss.CompileMojo.java
private void saveCompiledCode(final File source, final String compiled, final Date compilationDate) throws MojoFailureException { final File destination = new DestinationFileCreator(sourceDirectory, outputDirectory, outputFileFormat) .create(source);//from w w w .ja v a 2 s .c om final boolean skipsFileSaving = !force && !alwaysOverwrite && destination.exists() && compilationDate.before(new Date(destination.lastModified())); if (skipsFileSaving) { if (verbose) { getLog().info( "Skips saving CSS compiled code to file, because cached version is older than destination file: " + destination.getAbsolutePath()); } return; } if (verbose) { getLog().info("Saving CSS code to " + destination.getAbsolutePath()); } try { FileUtils.write(destination, compiled, encoding); } catch (final IOException e) { throw new MojoFailureException( String.format("Cannot save CSS compiled code to file: %s", destination.getAbsolutePath()), e); } }
From source file:edu.stanford.muse.util.EmailUtils.java
public static Pair<Date, Date> getFirstLast(Collection<? extends DatedDocument> allDocs, boolean ignoreInvalidDates) { // compute the begin and end date of the corpus Date first = null;//www . j a v a2 s . c o m Date last = null; if (allDocs == null) return null; for (DatedDocument ed : allDocs) { Date d = ed.date; if (d == null) { // drop this $ed$ EmailUtils.log.warn("Warning: null date on email: " + ed.getHeader()); continue; } // ignore invalid date if asked if (ignoreInvalidDates) if (EmailFetcherThread.INVALID_DATE.equals(d)) continue; if (first == null || d.before(first)) first = d; if (last == null || d.after(last)) last = d; } return new Pair<Date, Date>(first, last); }
From source file:com.apigee.sdk.apm.http.impl.client.cache.CachingHttpClient.java
HttpResponse revalidateCacheEntry(HttpHost target, HttpRequest request, HttpContext context, HttpCacheEntry cacheEntry) throws IOException, ProtocolException { HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry); Date requestDate = getCurrentDate(); HttpResponse backendResponse = backend.execute(target, conditionalRequest, context); Date responseDate = getCurrentDate(); final Header entryDateHeader = cacheEntry.getFirstHeader("Date"); final Header responseDateHeader = backendResponse.getFirstHeader("Date"); if (entryDateHeader != null && responseDateHeader != null) { try {/*from w ww.ja v a2 s. c om*/ Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); Date respDate = DateUtils.parseDate(responseDateHeader.getValue()); if (respDate.before(entryDate)) { HttpRequest unconditional = conditionalRequestBuilder.buildUnconditionalRequest(request, cacheEntry); requestDate = getCurrentDate(); backendResponse = backend.execute(target, unconditional, context); responseDate = getCurrentDate(); } } catch (DateParseException e) { // either backend response or cached entry did not have a valid // Date header, so we can't tell if they are out of order // according to the origin clock; thus we can skip the // unconditional retry recommended in 13.2.6 of RFC 2616. } } backendResponse.addHeader("Via", generateViaHeader(backendResponse)); int statusCode = backendResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) { cacheUpdates.getAndIncrement(); setResponseStatus(context, CacheResponseStatus.VALIDATED); } if (statusCode == HttpStatus.SC_NOT_MODIFIED) { HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(target, request, cacheEntry, backendResponse, requestDate, responseDate); if (suitabilityChecker.isConditional(request) && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) { return responseGenerator.generateNotModifiedResponse(updatedEntry); } return responseGenerator.generateResponse(updatedEntry); } return handleBackendResponse(target, conditionalRequest, requestDate, responseDate, backendResponse); }
From source file:net.audumla.scheduler.quartz.AstronomicTriggerImpl.java
@Override public Date getFireTimeAfter(Date now) { Date fireTime = null;/* ww w.j a va2 s . c om*/ //seed the start time schedule.startTime.calculateEventFrom(now); // honor the count for the number of events to repeat on if (schedule.eventCount == Integer.MIN_VALUE || eventCount < schedule.eventCount) { // Ensure that we only execute a number of times equal to the repeat count during start and end events boolean nextEvent = false; if (schedule.interval > 0 && (schedule.repeat == Integer.MIN_VALUE || count <= schedule.repeat)) { fireTime = org.apache.commons.lang3.time.DateUtils.addSeconds(now, schedule.interval); Date end = null; if (schedule.endTime == null) { // if there is no end event then use the next start event instead so that we dont overlap with recurring events end = org.apache.commons.lang3.time.DateUtils.addSeconds( schedule.startTime.getNextEvent().getCalculatedEventTime(), (int) schedule.startOffset); } else { // if an end event has been set then use it, but ensure that the event we use is after the current start event end = schedule.endTime.calculateEventFrom(now); while (end.before(org.apache.commons.lang3.time.DateUtils .addSeconds(schedule.startTime.getCalculatedEventTime(), (int) schedule.startOffset))) { schedule.endTime = schedule.endTime.getNextEvent(); end = org.apache.commons.lang3.time.DateUtils .addSeconds(schedule.endTime.getCalculatedEventTime(), (int) schedule.endOffset); } } // make sure that the next fire is not passed the end event time if (end.before(fireTime)) { nextEvent = true; } } else { nextEvent = true; } if (nextEvent) { // if the next fire time is after the calculated end time then we need to reseed the start time to the next scheduled event schedule.startTime = schedule.startTime.getNextEvent(); // increment the event count as we have passed an entire event cycle if we enter this section. We also need to reset the count to 0 as the count applies for each individual triggered event ++eventCount; count = 0; fireTime = org.apache.commons.lang3.time.DateUtils .addSeconds(schedule.startTime.getCalculatedEventTime(), (int) schedule.startOffset); } // adjust the fire time based on the calendar if (fireTime != null && calendar != null && !calendar.isTimeIncluded(fireTime.getTime())) { Date nextValid = new Date(calendar.getNextIncludedTime(fireTime.getTime())); fireTime = getFireTimeAfter(nextValid); } } else { mayFireAgain = false; } return fireTime; }
From source file:cc.kune.core.server.manager.impl.UserManagerDefault.java
@Override public void verifyPasswordHash(final Long userId, final String emailReceivedHash, final long period) throws EmailHashInvalidException, EmailHashExpiredException { final User user = find(userId); final Date on = new Date(user.getEmailCheckDate() + period); final Date now = new Date(); if (on.before(now)) { throw new EmailHashExpiredException(); }//from www . j av a2 s . co m final String emailConfirmHash = user.getEmailConfirmHash(); if (emailReceivedHash != null && emailConfirmHash != null && emailReceivedHash.equals(emailConfirmHash)) { clearPasswordHash(user); persist(user); } else { throw new EmailHashInvalidException(); } }