Example usage for org.joda.time LocalDate isAfter

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

Introduction

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

Prototype

public boolean isAfter(ReadablePartial partial) 

Source Link

Document

Is this partial later than the specified partial.

Usage

From source file:com.stagecents.gl.api.service.CalendarCommandHandler.java

License:Open Source License

/**
 * Returns true if the given period start and end dates overlap with some
 * other period that is not an adjustment period.
 * /*w  w w .  ja v  a2 s .  c om*/
 * @param periods The array of periods that make up the calendar.
 * @param index The index number of the given period within the array.
 * @return True if the given period start and end dates overlap with some
 *         other period that is not an adjustment period.
 */
private boolean overlappingPeriod(PeriodDTO[] periods, int index) {
    LocalDate startDate = periods[index].getStartDate();
    LocalDate endDate = periods[index].getEndDate();
    for (int i = 0; i < periods.length; i++) {
        if (i != index && !(periods[i].isAdjustmentPeriod())) {
            if (startDate.isBefore(periods[i].getStartDate()) && endDate.isAfter(periods[i].getEndDate())) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.stagecents.pa.api.ActivityService.java

License:Open Source License

private void updateTimecardHours(Timecard timecard, Position position, LocalDate startDate, LocalDate endDate) {
    while (timecard.isEffective(startDate)) {
        Interval duration = new Interval(startDate.toDateTime(activity.getScheduledStart()),
                startDate.toDateTime(activity.getScheduledEnd()));

        // Update the time card hours for each element type
        Iterator<ElementType> iter = position.getElements().iterator();
        while (iter.hasNext()) {
            ElementType e = iter.next();
            e.processHours(duration, activity, timecard, position);
        }//from   w  ww.j  a  v a 2  s.co  m

        // Increment the day
        startDate = startDate.plusDays(1);
        if (startDate.isAfter(endDate)) {
            return;
        }
    }
}

From source file:com.the.todo.Logic.java

License:MIT License

private void sortByDate(Map<DateCategory, List<ToDo>> todoMap, List<ToDo> todoList) {
    todoMap.clear();//  w  ww  .j  av a  2 s  .c o m

    Type todoType;
    LocalDate startDate;
    LocalDate endDate;
    LocalDate today = new LocalDate();
    LocalDate tomorrow = new LocalDate().plusDays(1);

    List<ToDo> todoOverdue = new ArrayList<ToDo>();
    List<ToDo> todoToday = new ArrayList<ToDo>();
    List<ToDo> todoTomorrow = new ArrayList<ToDo>();
    List<ToDo> todoUpcoming = new ArrayList<ToDo>();
    List<ToDo> todoSomeday = new ArrayList<ToDo>();

    for (ToDo todo : todoList) {
        todoType = todo.getType();
        startDate = todo.getStartDate().toLocalDate();
        endDate = todo.getEndDate().toLocalDate();

        if (todoType == Type.FLOATING) {
            todoSomeday.add(todo);
        }

        if (todoType == Type.DEADLINE) {
            if (endDate.isBefore(today)) {
                todoOverdue.add(todo);
            } else if (endDate.equals(today)) {
                todoToday.add(todo);
            } else if (endDate.equals(tomorrow)) {
                todoTomorrow.add(todo);
            }
        }

        if (todoType == Type.TIMED) {
            if (endDate.isBefore(today)) {
                todoOverdue.add(todo);
            }
            if (!today.isBefore(startDate) && !today.isAfter(endDate)) {
                todoToday.add(todo);
            }
            if (!tomorrow.isBefore(startDate) && !tomorrow.isAfter(endDate)) {
                todoTomorrow.add(todo);
            }
        }

        if (displayType == DisplayType.SEARCH) {
            if (todoType == Type.DEADLINE) {
                if (endDate.isAfter(tomorrow)) {
                    todoUpcoming.add(todo);
                }
            } else if (todoType == Type.TIMED) {
                if (endDate.isAfter(tomorrow)) {
                    todoUpcoming.add(todo);
                }
            }
        }
    }

    if (todoOverdue.size() > 0) {
        todoMap.put(DateCategory.OVERDUE, todoOverdue);
    }
    if (todoToday.size() > 0) {
        todoMap.put(DateCategory.TODAY, todoToday);
    }
    if (todoTomorrow.size() > 0) {
        todoMap.put(DateCategory.TOMORROW, todoTomorrow);
    }
    if (todoUpcoming.size() > 0) {
        todoMap.put(DateCategory.UPCOMING, todoUpcoming);
    }
    if (todoSomeday.size() > 0) {
        todoMap.put(DateCategory.SOMEDAY, todoSomeday);
    }

    for (Entry<DateCategory, List<ToDo>> entry : todoMap.entrySet()) {
        Collections.sort(entry.getValue());
    }
}

From source file:com.tomtom.speedtools.apivalidation.ApiValidator.java

License:Apache License

public void checkLocalDate(final boolean required, @Nonnull final String name, @Nullable final String value,
        @Nonnull final LocalDate minDate, @Nonnull final LocalDate maxDate) {
    checkNotNull(required, name, value);
    if (value != null) {
        try {/*from www.ja  va  2 s .  c  o m*/
            final LocalDate localDate = LocalDate.parse(value);
            // Check range.
            if (localDate.isBefore(minDate) || localDate.isAfter(maxDate)) {
                errors.add(new ApiLocalDateOutOfRangeError(name, localDate, minDate, maxDate));
            }
        } catch (final IllegalArgumentException ignored) {
            errors.add(new ApiLocalDateFormatError(name, value, FORMAT_DATE_ISO));
        }
    }
}

From source file:cz.krtinec.birthday.dto.Zodiac.java

License:Open Source License

public static Zodiac toZodiac(LocalDate birthday) {
    for (Zodiac zodiac : values()) {
        LocalDate fromWithYear = zodiac.from.withYear(birthday.getYear());
        LocalDate toWithYear = zodiac.to.withYear(birthday.getYear());

        if (birthday.getMonthOfYear() == 12 && Zodiac.CAPRICORN.equals(zodiac)) {
            toWithYear = toWithYear.plusYears(1);
        } else if (birthday.getMonthOfYear() == 1 && Zodiac.CAPRICORN.equals(zodiac)) {
            fromWithYear = fromWithYear.minusYears(1);
        }//from  w ww. j a  va  2s.  c  o m

        if ((fromWithYear.isBefore(birthday) || fromWithYear.isEqual(birthday))
                && (toWithYear.isAfter(birthday) || toWithYear.isEqual(birthday))) {
            return zodiac;
        }
    }

    throw new IllegalArgumentException("Cannot find zodiac sign for date: " + birthday);
}

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"));
    }/*  w w w .  ja v a 2 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.appsolve.padelcampus.controller.bookings.BookingsVoucherController.java

@RequestMapping(value = "booking/{UUID}/voucher", method = POST)
public ModelAndView onPostVoucher(@PathVariable("UUID") String UUID,
        @RequestParam(required = false) String voucherUUID) {
    Booking booking = bookingDAO.findByUUID(UUID);
    ModelAndView mav = getVoucherView(booking);
    try {// ww  w  .j  a  va 2 s .  com
        if (booking.getConfirmed()) {
            throw new Exception(msg.get("BookingAlreadyConfirmed"));
        }
        if (StringUtils.isEmpty(voucherUUID)) {
            throw new Exception(msg.get("MissingRequiredVoucher"));
        }
        Voucher voucher = voucherDAO.findByUUID(voucherUUID);
        LocalDate now = new LocalDate();

        if (voucher == null) {
            throw new Exception(msg.get("VoucherDoesNotExist"));
        }

        if (voucher.getUsed()) {
            throw new Exception(msg.get("VoucherHasAlreadyBeenUsed"));
        }

        if (now.isAfter(voucher.getValidUntil())) {
            throw new Exception(msg.get("VoucherHasExpired"));
        }

        if (voucher.getDuration().compareTo(booking.getDuration()) < 0) {
            throw new Exception(
                    msg.get("VoucherIsOnlyValidForDuration", new Object[] { voucher.getDuration() }));
        }

        if (!voucher.getOffers().contains(booking.getOffer())) {
            throw new Exception(msg.get("VoucherIsOnlyValidForOffer", new Object[] { voucher.getOffers() }));
        }

        LocalTime validUntilTime = voucher.getValidUntilTime();
        LocalTime bookingEndTime = booking.getBookingEndTime();
        if (bookingEndTime.isAfter(validUntilTime)) {
            throw new Exception(msg.get("VoucherIsOnlyValidForBookingsBefore",
                    new Object[] { validUntilTime.toString(TIME_HUMAN_READABLE) }));
        }

        //update legacy vouchers
        if (voucher.getCalendarWeekDays().isEmpty()) {
            voucher.setCalendarWeekDays(new HashSet<>(Arrays.asList(CalendarWeekDay.values())));
        }

        Set<CalendarWeekDay> validWeekDays = voucher.getCalendarWeekDays();
        CalendarWeekDay bookingWeekDay = CalendarWeekDay.values()[booking.getBookingDate().getDayOfWeek() - 1];
        if (!validWeekDays.contains(bookingWeekDay)) {
            throw new Exception(msg.get("VoucherIsOnlyValidForBookingsOn", new Object[] { validWeekDays }));
        }

        voucher.setUsed(true);
        voucherDAO.saveOrUpdate(voucher);
        booking.setPaymentConfirmed(true);
        booking.setVoucher(voucher);
        bookingDAO.saveOrUpdate(booking);
        return BookingsController.getRedirectToSuccessView(booking);
    } catch (Exception e) {
        log.error(e);
        mav.addObject("error", e.getMessage());
        return mav;
    }
}

From source file:de.appsolve.padelcampus.controller.teams.TeamsController.java

private ModelAndView getTeamView(Team team) {
    if (team == null) {
        throw new ResourceNotFoundException();
    }// w  w  w .  j a v a2 s  .co m
    ModelAndView mav = new ModelAndView("teams/team", "Team", team);

    //get upcoming events
    List<Event> currentEvents = eventDAO.findAllUpcomingWithParticipant(team);

    //get past events from actual game data so that teams that have not played will not be shown and so that pull events are considered
    Set<Event> pastEvents = new TreeSet<>();
    LocalDate today = LocalDate.now();
    List<Game> games = gameDAO.findByParticipant(team);
    for (Game game : games) {
        Event event = game.getEvent();
        if (today.isAfter(event.getEndDate())) {
            pastEvents.add(event);
        }
    }
    mav.addObject("Events", currentEvents);
    mav.addObject("PastEvents", pastEvents);
    return mav;
}

From source file:de.appsolve.padelcampus.utils.BookingUtil.java

public List<TimeSlot> getTimeSlotsForDate(LocalDate selectedDate, List<CalendarConfig> allCalendarConfigs,
        List<Booking> existingBookings, Boolean onlyFutureTimeSlots, Boolean preventOverlapping)
        throws CalendarConfigException {

    List<CalendarConfig> calendarConfigs = calendarConfigUtil.getCalendarConfigsMatchingDate(allCalendarConfigs,
            selectedDate);//from w w  w. j  a  v  a 2  s.  c  om
    Iterator<CalendarConfig> iterator = calendarConfigs.iterator();
    while (iterator.hasNext()) {
        CalendarConfig calendarConfig = iterator.next();
        if (isHoliday(selectedDate, calendarConfig)) {
            iterator.remove();
        }
    }

    List<TimeSlot> timeSlots = new ArrayList<>();
    if (calendarConfigs.size() > 0) {
        LocalDate today = new LocalDate(DEFAULT_TIMEZONE);

        //sort all calendar configurations for selected date by start time
        Collections.sort(calendarConfigs);

        CalendarConfig previousConfig = null;
        LocalDateTime time = null;
        LocalDateTime now = new LocalDateTime(DEFAULT_TIMEZONE);

        //generate list of bookable time slots
        int i = 0;
        for (CalendarConfig config : calendarConfigs) {
            i++;
            LocalDateTime startDateTime = getLocalDateTime(selectedDate, config.getStartTime());
            if (time == null) {
                //on first iteration
                time = startDateTime;
            } else if (!time.plusMinutes(previousConfig.getMinInterval()).equals(startDateTime)) {
                //reset basePriceLastConfig as this is a non contiguous offer
                previousConfig = null;
                time = startDateTime;
            }
            LocalDateTime endDateTime = getLocalDateTime(selectedDate, config.getEndTime());
            while (time.plusMinutes(config.getMinDuration()).compareTo(endDateTime) <= 0) {
                BigDecimal pricePerMinDuration;
                if (previousConfig == null) {
                    pricePerMinDuration = config.getBasePrice();
                } else {
                    BigDecimal previousConfigBasePricePerMinute = getPricePerMinute(previousConfig);
                    pricePerMinDuration = previousConfigBasePricePerMinute
                            .multiply(new BigDecimal(previousConfig.getMinInterval()), MathContext.DECIMAL128);
                    BigDecimal basePricePerMinute = getPricePerMinute(config);
                    pricePerMinDuration = pricePerMinDuration.add(basePricePerMinute.multiply(
                            new BigDecimal(config.getMinDuration() - previousConfig.getMinInterval()),
                            MathContext.DECIMAL128));
                    previousConfig = null;
                }
                pricePerMinDuration = pricePerMinDuration.setScale(2, RoundingMode.HALF_EVEN);
                if (onlyFutureTimeSlots) {
                    if (selectedDate.isAfter(today) || time.isAfter(now)) {
                        addTimeSlot(timeSlots, time, config, pricePerMinDuration);
                    }
                } else {
                    addTimeSlot(timeSlots, time, config, pricePerMinDuration);
                }
                time = time.plusMinutes(config.getMinInterval());
            }
            //make sure to display the last min interval of the day
            if (config.getMinInterval() < config.getMinDuration() && i == calendarConfigs.size()) {
                if (time.plusMinutes(config.getMinInterval()).compareTo(endDateTime) <= 0) {
                    addTimeSlot(timeSlots, time, config, null);
                }
            }
            previousConfig = config;
        }
        //sort time slots by time
        Collections.sort(timeSlots);

        //decrease court count for every blocking booking
        for (TimeSlot timeSlot : timeSlots) {
            checkForBookedCourts(timeSlot, existingBookings, preventOverlapping);
        }
    }
    return timeSlots;
}

From source file:de.appsolve.padelcampus.utils.BookingUtil.java

public void addWeekView(HttpServletRequest request, LocalDate selectedDate, List<Facility> selectedFacilities,
        ModelAndView mav, Boolean onlyFutureTimeSlots, Boolean preventOverlapping)
        throws JsonProcessingException {
    //calculate date configuration for datepicker
    LocalDate today = new LocalDate(DEFAULT_TIMEZONE);
    LocalDate firstDay = today.dayOfMonth().withMinimumValue();
    LocalDate lastDay = getLastBookableDay(request).plusDays(1);
    List<CalendarConfig> calendarConfigs = calendarConfigDAO.findBetween(firstDay, lastDay);
    Collections.sort(calendarConfigs);
    Map<String, DatePickerDayConfig> dayConfigs = getDayConfigMap(firstDay, lastDay, calendarConfigs);

    List<Booking> confirmedBookings = bookingDAO.findBlockedBookingsBetween(firstDay, lastDay);

    //calculate available time slots
    List<TimeSlot> timeSlots = new ArrayList<>();
    List<LocalDate> weekDays = new ArrayList<>();
    for (int i = 1; i <= CalendarWeekDay.values().length; i++) {
        LocalDate date = selectedDate.withDayOfWeek(i);
        weekDays.add(date);//ww w .j  a v  a  2s .  c om
        if ((!onlyFutureTimeSlots || !date.isBefore(today)) && lastDay.isAfter(date)) {
            try {
                //generate list of bookable time slots
                timeSlots.addAll(getTimeSlotsForDate(date, calendarConfigs, confirmedBookings,
                        onlyFutureTimeSlots, preventOverlapping));
            } catch (CalendarConfigException e) {
                //safe to ignore
            }
        }
    }

    SortedSet<Offer> offers = new TreeSet<>();
    List<TimeRange> rangeList = new ArrayList<>();
    //Map<TimeRange, List<TimeSlot>> rangeList = new TreeMap<>();
    for (TimeSlot slot : timeSlots) {
        Set<Offer> slotOffers = slot.getConfig().getOffers();
        offers.addAll(slotOffers);

        TimeRange range = new TimeRange();
        range.setStartTime(slot.getStartTime());
        range.setEndTime(slot.getEndTime());

        if (rangeList.contains(range)) {
            range = rangeList.get(rangeList.indexOf(range));
        } else {
            rangeList.add(range);
        }

        List<TimeSlot> slotis = range.getTimeSlots();
        slotis.add(slot);
        range.setTimeSlots(slotis);
    }
    Collections.sort(rangeList);

    List<Offer> selectedOffers = new ArrayList<>();
    if (selectedFacilities.isEmpty()) {
        selectedOffers = offerDAO.findAll();
    } else {
        for (Facility facility : selectedFacilities) {
            selectedOffers.addAll(facility.getOffers());
        }
    }
    Collections.sort(selectedOffers);

    mav.addObject("dayConfigs", objectMapper.writeValueAsString(dayConfigs));
    mav.addObject("maxDate", lastDay.toString());
    mav.addObject("Day", selectedDate);
    mav.addObject("NextMonday", selectedDate.plusDays(8 - selectedDate.getDayOfWeek()));
    mav.addObject("PrevSunday", selectedDate.minusDays(selectedDate.getDayOfWeek()));
    mav.addObject("WeekDays", weekDays);
    mav.addObject("RangeMap", rangeList);
    mav.addObject("Offers", offers);
    mav.addObject("SelectedOffers", selectedOffers);
    mav.addObject("SelectedFacilities", selectedFacilities);
    mav.addObject("Facilities", facilityDAO.findAll());
}