Example usage for org.joda.time LocalDate compareTo

List of usage examples for org.joda.time LocalDate compareTo

Introduction

In this page you can find the example usage for org.joda.time LocalDate compareTo.

Prototype

public int compareTo(ReadablePartial partial) 

Source Link

Document

Compares this partial with another returning an integer indicating the order.

Usage

From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsReservationsController.java

@Override
public ModelAndView postEditView(@ModelAttribute("Model") ReservationRequest reservationRequest,
        HttpServletRequest request, BindingResult bindingResult) {
    ModelAndView addView = getAddView(reservationRequest);
    validator.validate(reservationRequest, bindingResult);
    if (bindingResult.hasErrors()) {
        return addView;
    }/*from  www.  j a v a  2s. co m*/
    try {
        Player player = sessionUtil.getUser(request);

        //calculate reservation bookings, taking into account holidays
        LocalDate date = reservationRequest.getStartDate();
        LocalDate endDate = reservationRequest.getEndDate();

        List<Booking> bookings = new ArrayList<>();
        List<Booking> failedBookings = new ArrayList<>();
        LocalDateTime blockingTime = new LocalDateTime();

        while (date.compareTo(endDate) <= 0) {
            Set<CalendarWeekDay> calendarWeekDays = reservationRequest.getCalendarWeekDays();
            for (CalendarWeekDay calendarWeekDay : calendarWeekDays) {
                if (calendarWeekDay.ordinal() + 1 == date.getDayOfWeek()) {
                    try {
                        List<CalendarConfig> calendarConfigs = calendarConfigDAO.findFor(date); //throws CalendarConfigException
                        Iterator<CalendarConfig> iterator = calendarConfigs.iterator();
                        while (iterator.hasNext()) {
                            CalendarConfig calendarConfig = iterator.next();
                            if (!bookingUtil.isHoliday(date, calendarConfig)) {
                                for (Offer offer : reservationRequest.getOffers()) {

                                    Booking booking = new Booking();
                                    booking.setAmount(BigDecimal.ZERO);
                                    booking.setBlockingTime(blockingTime);
                                    booking.setBookingDate(date);
                                    booking.setBookingTime(reservationRequest.getStartTime());
                                    booking.setBookingType(BookingType.reservation);
                                    booking.setComment(reservationRequest.getComment());
                                    booking.setConfirmed(Boolean.TRUE);
                                    booking.setCurrency(Currency.EUR);
                                    booking.setDuration(getDuration(reservationRequest, calendarConfig));
                                    booking.setPaymentConfirmed(reservationRequest.getPaymentConfirmed());
                                    booking.setPaymentMethod(PaymentMethod.Reservation);
                                    booking.setPlayer(player);
                                    booking.setUUID(BookingUtil.generateUUID());
                                    booking.setOffer(offer);
                                    booking.setPublicBooking(reservationRequest.getPublicBooking());

                                    //we call this inside the loop to prevent overbooking
                                    List<Booking> confirmedBookings = bookingDAO
                                            .findBlockedBookingsForDate(date);

                                    OfferDurationPrice offerDurationPrice = bookingUtil.getOfferDurationPrice(
                                            calendarConfigs, confirmedBookings, booking.getBookingDate(),
                                            booking.getBookingTime(), offer);
                                    if (offerDurationPrice == null) {
                                        failedBookings.add(booking);
                                        continue;
                                    } else {
                                        BigDecimal price = offerDurationPrice.getDurationPriceMap()
                                                .get(booking.getDuration().intValue());
                                        booking.setAmount(price);
                                    }

                                    TimeSlot timeSlot = new TimeSlot();
                                    timeSlot.setDate(date);
                                    timeSlot.setStartTime(reservationRequest.getStartTime());
                                    timeSlot.setEndTime(reservationRequest.getEndTime());
                                    timeSlot.setConfig(calendarConfig);
                                    Long bookingSlotsLeft = bookingUtil.getBookingSlotsLeft(timeSlot, offer,
                                            confirmedBookings);

                                    if (bookingSlotsLeft < 1) {
                                        failedBookings.add(booking);
                                        continue;
                                    }

                                    //we save the booking directly to prevent overbookings
                                    booking = bookingDAO.saveOrUpdate(booking);
                                    bookings.add(booking);
                                }
                            }
                            break;
                        }
                        break;
                    } catch (CalendarConfigException e) {
                        LOG.warn(
                                "Caught calendar config exception during add reservation request. This may be normal (for holidays)",
                                e);
                        Booking failedBooking = new Booking();
                        failedBooking.setPlayer(player);
                        failedBooking.setBookingDate(date);
                        failedBooking.setBookingTime(reservationRequest.getStartTime());
                        failedBookings.add(failedBooking);
                    }
                }
            }
            date = date.plusDays(1);
        }

        if (!failedBookings.isEmpty()) {
            throw new Exception(msg.get("UnableToReserveAllDesiredTimes", new Object[] {
                    StringUtils.join(bookings, "<br/>"), StringUtils.join(failedBookings, "<br/>") }));
        }

        if (bookings.isEmpty()) {
            throw new Exception(msg.get("NoCourtReservationsForSelectedDateTime"));
        }

        return new ModelAndView("redirect:/admin/bookings/reservations");
    } catch (Exception e) {
        LOG.error(e, e);
        bindingResult.addError(new ObjectError("comment", e.getMessage()));
        return addView;
    }
}

From source file:de.appsolve.padelcampus.controller.bookings.BookingsController.java

private void validateAndAddObjectsToView(ModelAndView mav, HttpServletRequest request, Booking booking,
        String day, String time, Offer offer) throws Exception {
    LocalDate selectedDate = FormatUtils.DATE_HUMAN_READABLE.parseLocalDate(day);
    LocalTime selectedTime = FormatUtils.TIME_HUMAN_READABLE.parseLocalTime(time);

    LocalDate today = new LocalDate();
    LocalTime now = new LocalTime();
    if (selectedDate.compareTo(today) < 0 || (selectedDate.equals(today) && selectedTime.compareTo(now) < 0)) {
        throw new Exception(msg.get("RequestedTimeIsInThePast"));
    }// ww w.jav  a2 s  .  c  om

    LocalDate lastDay = bookingUtil.getLastBookableDay(request);
    if (selectedDate.isAfter(lastDay)) {
        throw new Exception(msg.get("RequestedTimeIsInTheFuture"));
    }

    //create a list of possible booking durations taking into account calendar configurations and confirmed bookings
    List<CalendarConfig> configs = calendarConfigDAO.findFor(selectedDate);
    List<Booking> confirmedBookings = bookingDAO.findBlockedBookingsForDate(selectedDate);
    OfferDurationPrice offerDurationPrice = bookingUtil.getOfferDurationPrice(configs, confirmedBookings,
            selectedDate, selectedTime, offer);

    //notify the user in case there are no durations bookable
    if (offerDurationPrice == null) {
        throw new Exception(msg.get("NoFreeCourtsForSelectedTimeAndDate"));
    }

    //store user provided data in the session booking
    booking.setBookingDate(selectedDate);
    booking.setBookingTime(selectedTime);

    //set currency and price if offer and duration have been selected
    if (booking.getOffer() != null && booking.getDuration() != null) {
        if (offerDurationPrice.getOffer().equals(booking.getOffer())) {
            BigDecimal price;
            switch (booking.getPaymentMethod()) {
            case Subscription:
                price = BigDecimal.ZERO;
                break;
            default:
                price = offerDurationPrice.getDurationPriceMap().get(booking.getDuration().intValue());

            }
            booking.setAmount(price);
            booking.setCurrency(offerDurationPrice.getConfig().getCurrency());
        }
    }

    sessionUtil.setBooking(request, booking);

    if (mav != null) {
        mav.addObject("Booking", booking);
        mav.addObject("OfferDurationPrice", offerDurationPrice);
        mav.addObject("SelectedOffer", offer);
    }
}

From source file:de.azapps.mirakel.helper.TaskHelper.java

License:Open Source License

/**
 * Returns the ID of the ColorResource for a DueDate
 * /* w w w .  j a  v a 2s. c  o  m*/
 * @param origDue
 *            The DueDate
 * @param isDone
 *            Is the Task done?
 * @return ID of the ColorResource
 */
public static int getTaskDueColor(Calendar origDue, boolean isDone) {
    if (origDue == null)
        return R.color.Grey;
    LocalDate today = new LocalDate();
    LocalDate nextWeek = new LocalDate().plusDays(7);
    LocalDate due = new LocalDate(origDue);
    int cmpr = today.compareTo(due);
    int color;
    if (isDone) {
        color = R.color.Grey;
    } else if (cmpr > 0) {
        color = R.color.Red;
    } else if (cmpr == 0) {
        color = R.color.Orange;
    } else if (nextWeek.compareTo(due) >= 0) {
        color = R.color.Yellow;
    } else {
        color = R.color.Green;
    }
    return color;
}

From source file:divconq.struct.scalar.DateStruct.java

License:Open Source License

public static int comparison(Object x, Object y) {
    LocalDate xv = Struct.objectToDate(x);
    LocalDate yv = Struct.objectToDate(y);

    if ((yv == null) && (xv == null))
        return 0;

    if (yv == null)
        return 1;

    if (xv == null)
        return -1;

    return xv.compareTo(yv);
}

From source file:edu.harvard.med.iccbl.screensaver.reports.icbg.AssayInfoProducer.java

License:Open Source License

public AssayInfo getAssayInfoForScreen(Screen screen) throws FileNotFoundException {
    AssayInfo assayInfo = new AssayInfo();
    assayInfo.setAssayName("ICCBL" + screen.getFacilityId());
    assayInfo.setProtocolDescription(screen.getTitle());
    assayInfo.setPNote(screen.getSummary());
    assayInfo.setInvestigator(// w w  w  .j  a  va  2  s.c  o  m
            screen.getLabHead() == null ? "" : screen.getLabHead().getLastName().toUpperCase());

    String assayCategoryText = "";
    for (String keyword : screen.getKeywords()) {
        assayCategoryText += keyword.toUpperCase() + " ";
    }
    if (assayCategories != null) {
        assayInfo.setAssayCategory(assayCategories.get(screen.getFacilityId()));
    } else {
        assayCategoryText += screen.getSummary().toUpperCase();
        setAssayCategory(assayInfo, assayCategoryText);
    }
    LocalDate assayDate = screen.getDateCreated().toLocalDate();
    for (StatusItem statusItem : screen.getStatusItems()) {
        LocalDate statusItemDate = statusItem.getStatusDate();
        if (assayDate == null || assayDate.compareTo(statusItemDate) < 0) {
            assayDate = statusItemDate;
        }
    }

    assayInfo.setAssayDate(
            assayDate.getMonthOfYear() + "/" + assayDate.getDayOfMonth() + "/" + (assayDate.getYear()));
    assert assayDate.getYear() >= 1900 : "year should include century";

    return assayInfo;
}

From source file:edu.harvard.med.screensaver.model.screens.Screen.java

License:Open Source License

/**
 * Create and return a new <code>StatusItem</code> for this screen.
 * @param statusDate the status date//w w w .  jav  a  2  s .c  o  m
 * @param screenStatus the status value
 * @return the new status item
 */
public StatusItem createStatusItem(LocalDate statusDate, ScreenStatus screenStatus) {
    for (StatusItem statusItem : _statusItems) {
        if (statusItem.getStatus().getRank() == screenStatus.getRank()) {
            throw new BusinessRuleViolationException("screen status " + screenStatus
                    + " is mutually exclusive with existing screen status " + statusItem.getStatus());
        }
        if (screenStatus.getRank() < statusItem.getStatus().getRank()) {
            if (statusDate.compareTo(statusItem.getStatusDate()) > 0) {
                throw new BusinessRuleViolationException(
                        "date of new screen status must not be after date of subsequent screen status");
            }
        } else {
            if (statusDate.compareTo(statusItem.getStatusDate()) < 0) {
                throw new BusinessRuleViolationException(
                        "date of new screen status must not be before the date of the previous screen status");
            }
        }
    }
    StatusItem newStatusItem = new StatusItem(statusDate, screenStatus);
    _statusItems.add(newStatusItem);
    return newStatusItem;
}

From source file:edu.harvard.med.screensaver.model.screens.Screen.java

License:Open Source License

public void setDataPrivacyExpirationDate(LocalDate dataPrivacyExpirationDate) {
    if (dataPrivacyExpirationDate == null) {
        if (_maxAllowedDataPrivacyExpirationDate != null || _minAllowedDataPrivacyExpirationDate != null) {
            throw new DataModelViolationException(
                    "null value not allowed for condition if(maxAllowedDataPrivacyExpirationDate != null || minAllowedDataPrivacyExpirationDate != null)");
        }/*from   w  ww  .j  ava 2  s . co  m*/
    }

    LocalDate min = _minAllowedDataPrivacyExpirationDate;
    LocalDate max = _maxAllowedDataPrivacyExpirationDate;
    if (max != null && dataPrivacyExpirationDate.compareTo(max) > 0) {
        dataPrivacyExpirationDate = max;
    } else if (min != null && dataPrivacyExpirationDate.compareTo(min) < 0) {
        dataPrivacyExpirationDate = min;
    }
    _dataPrivacyExpirationDate = dataPrivacyExpirationDate;
}

From source file:edu.harvard.med.screensaver.model.screens.Screen.java

License:Open Source License

/**
 * Call this to set the {@link Screen#getDataPrivacyExpirationDate()} after the 
 * {@link Screen#getMinAllowedDataPrivacyExpirationDate()} and the {@link Screen#getMaxAllowedDataPrivacyExpirationDate()}
 * have been set.<br>/*from   w  ww.j ava 2 s .  c  o m*/
 */
private void updateDataPrivacyExpirationDate() {
    LocalDate requestedDate = getDataPrivacyExpirationDate();
    LocalDate max = getMaxAllowedDataPrivacyExpirationDate();
    LocalDate min = getMinAllowedDataPrivacyExpirationDate();

    if (requestedDate.compareTo(max) > 0 & max != null) {
        _dataPrivacyExpirationDate = max;
    } else if (min != null && requestedDate.compareTo(min) < 0) {
        _dataPrivacyExpirationDate = min;
    } else {
        _dataPrivacyExpirationDate = requestedDate;
    }
}

From source file:edu.harvard.med.screensaver.model.users.ChecklistItemEvent.java

License:Open Source License

public ChecklistItemEvent createChecklistItemExpirationEvent(LocalDate datePerformed,
        AdministratorUser recordedBy) {/* ww  w  .  ja v  a2  s . c o m*/
    if (!getChecklistItem().isExpirable()) {
        throw new DataModelViolationException(
                "cannot expire checklist item " + getChecklistItem().getItemName());
    }
    SortedSet<ChecklistItemEvent> checklistItemEvents = getScreeningRoomUser()
            .getChecklistItemEvents(getChecklistItem());
    if (checklistItemEvents.isEmpty()) {
        throw new DataModelViolationException(
                "cannot add checklist item expiration when checklist item has not yet been activated");
    }
    ChecklistItemEvent previousEvent = checklistItemEvents.last();
    if (!previousEvent.equals(this)) {
        throw new DataModelViolationException(
                "can only apply expiration to the last checklist event of this type");
    }
    if (previousEvent.isExpiration()) {
        throw new DataModelViolationException("can only expire a previously active checklist item");
    }
    if (previousEvent.isNotApplicable()) {
        throw new DataModelViolationException(
                "can not expire a checklist item that has been marked \"not applicable\"");
    }
    if (datePerformed.compareTo(previousEvent.getDatePerformed()) < 0) {
        throw new DataModelViolationException(
                "checklist item expiration date must be on or after the previous activation date");
    }
    ChecklistItemEvent checklistItemExpiration = new ChecklistItemEvent(this.getChecklistItem(),
            this.getScreeningRoomUser(), datePerformed, recordedBy);
    checklistItemExpiration._isExpiration = true;
    this.getScreeningRoomUser().getChecklistItemEvents().add(checklistItemExpiration);
    return checklistItemExpiration;
}

From source file:edu.harvard.med.screensaver.model.users.ScreeningRoomUser.java

License:Open Source License

/**
 * Create a new checklist item activation/completed event for the user.
 * @param checklistItem the checklist item
 * @param datePerformed the date the checklist item was performed by the user or otherwise enacted
 * @return the new checklist item for the user
 * @see ChecklistItemEvent#createChecklistItemExpirationEvent(LocalDate, AdministratorUser)
 *//*from w  ww  .j a  va2s  .c  o m*/
public ChecklistItemEvent createChecklistItemActivationEvent(ChecklistItem checklistItem,
        LocalDate datePerformed, AdministratorUser recordedBy) {
    SortedSet<ChecklistItemEvent> checklistItemEvents = getChecklistItemEvents(checklistItem);
    if (checklistItemEvents.size() > 0) {
        if (!checklistItemEvents.last().isExpiration()) {
            throw new DataModelViolationException(
                    "cannot add checklist item activation when checklist item is already activated");
        }
        if (datePerformed.compareTo(checklistItemEvents.last().getDatePerformed()) < 0) {
            // throw new DataModelViolationException("checklist item activation date must be on or after the previous expiration date");
            log.info(
                    "Note: setting ChecklistItemEvent to a date that is on or before the previous expiration date:\n"
                            + "UserId: " + getEntityId() + "\nOld date: "
                            + checklistItemEvents.last().getDatePerformed() + "\nNew date: " + datePerformed);
        }
    }
    ChecklistItemEvent checklistItemEvent = new ChecklistItemEvent(checklistItem, this, datePerformed,
            recordedBy);
    _checklistItemEvents.add(checklistItemEvent);
    return checklistItemEvent;
}