Example usage for org.joda.time DateTime toLocalDate

List of usage examples for org.joda.time DateTime toLocalDate

Introduction

In this page you can find the example usage for org.joda.time DateTime toLocalDate.

Prototype

public LocalDate toLocalDate() 

Source Link

Document

Converts this object to a LocalDate with the same date and chronology.

Usage

From source file:com.qcadoo.mes.productionPerShift.dates.OrderRealizationDaysResolver.java

License:Open Source License

public OrderRealizationDay find(final DateTime orderStartDateTime, final int startingFrom,
        final boolean isFirstDay, final List<Shift> shifts) {
    OrderRealizationDay firstWorkingDay = findFirstWorkingDayFrom(orderStartDateTime.toLocalDate(),
            startingFrom, shifts);//from ww w  . j av a  2  s.co m
    if (isFirstDay) {
        return tryResolveFirstDay(firstWorkingDay, orderStartDateTime).or(firstWorkingDay);
    }
    return firstWorkingDay;
}

From source file:com.qcadoo.mes.productionPerShift.dates.OrderRealizationDaysResolver.java

License:Open Source License

private Optional<OrderRealizationDay> tryResolveFirstDay(final OrderRealizationDay firstWorkingDay,
        final DateTime orderStartDateTime) {
    LocalDate orderStartDate = orderStartDateTime.toLocalDate();
    LocalTime orderStartTime = orderStartDateTime.toLocalTime();

    Optional<Shift> shiftStartingOrder = firstWorkingDay.findShiftWorkingAt(orderStartTime);
    Optional<TimeRange> workTimeRange = FluentOptional.wrap(shiftStartingOrder).flatMap(shift -> {
        int prevDayOfWeek = firstWorkingDay.getDate().minusDays(1).getDayOfWeek();
        return shift.findWorkTimeAt(prevDayOfWeek, orderStartTime);
    }).toOpt();//  www.  ja v  a 2s .c  om

    if (shiftWorkTimeMatchPredicate(shiftStartingOrder, workTimeRange, startsDayBefore(orderStartTime))) {
        return Optional.of(new OrderRealizationDay(orderStartDate,
                firstWorkingDay.getRealizationDayNumber() - 1, Lists.newArrayList(shiftStartingOrder.asSet())));
    }
    if (shiftWorkTimeMatchPredicate(shiftStartingOrder, workTimeRange, endsNextDay(orderStartTime))) {
        return Optional.of(new OrderRealizationDay(firstWorkingDay.getDate(),
                firstWorkingDay.getRealizationDayNumber(), Lists.newArrayList(shiftStartingOrder.asSet())));
    }
    return Optional.absent();
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

License:Open Source License

public LinkedHashSet<String> calculateAvailabilitySpans(int minRange, UserProfileId pid, DateTime fromDate,
        DateTime toDate, DateTimeZone userTz, boolean busy) throws WTException {
    CalendarDAO calDao = CalendarDAO.getInstance();
    EventDAO evtDao = EventDAO.getInstance();
    LinkedHashSet<String> hours = new LinkedHashSet<>();
    Connection con = null;//w ww  . ja  v a2s. c om

    //TODO: review this method

    try {
        con = WT.getConnection(SERVICE_ID);

        // Lists desired calendars by profile
        final List<VVEventInstance> veis = new ArrayList<>();
        for (OCalendar ocal : calDao.selectByProfile(con, pid.getDomainId(), pid.getUserId())) {
            for (VVEvent ve : evtDao.viewByCalendarRangeCondition(con, ocal.getCalendarId(), fromDate, toDate,
                    null)) {
                veis.add(new VVEventInstance(ve));
            }
            for (VVEvent ve : evtDao.viewRecurringByCalendarRangeCondition(con, ocal.getCalendarId(), fromDate,
                    toDate, null)) {
                veis.add(new VVEventInstance(ve));
            }
        }

        DateTime startDt, endDt;
        for (VVEventInstance vei : veis) {
            if (vei.getBusy() != busy)
                continue; // Ignore events that are not marked as busy!

            if (vei.getRecurrenceId() == null) {
                startDt = vei.getStartDate().withZone(userTz);
                endDt = vei.getEndDate().withZone(userTz);
                hours.addAll(generateTimeSpans(minRange, startDt.toLocalDate(), endDt.toLocalDate(),
                        startDt.toLocalTime(), endDt.toLocalTime(), userTz));
            } else {
                final List<VVEventInstance> instances = calculateRecurringInstances(con,
                        new VVEventInstanceMapper(vei), fromDate, toDate, userTz);
                for (VVEventInstance instance : instances) {
                    startDt = instance.getStartDate().withZone(userTz);
                    endDt = instance.getEndDate().withZone(userTz);
                    hours.addAll(generateTimeSpans(minRange, startDt.toLocalDate(), endDt.toLocalDate(),
                            startDt.toLocalTime(), endDt.toLocalTime(), userTz));
                }
            }
        }

    } catch (SQLException | DAOException ex) {
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
    }
    return hours;
}

From source file:com.sonicle.webtop.calendar.rpt.AbstractAgenda.java

License:Open Source License

public void setDataSource(CalendarManager manager, DateTime fromDate, DateTime toDate, DateTimeZone utz,
        Map<Integer, Calendar> calendars, Collection<SchedEventInstance> instances) throws WTException {
    int days = -1;
    if (DateTimeUtils.isEndOfDay(toDate, true)) {
        days = Days.daysBetween(fromDate, toDate).getDays() + 1;
    } else if (DateTimeUtils.isMidnight(toDate)) {
        days = Days.daysBetween(fromDate, toDate).getDays();
    }//ww w  . j  a v a  2s . c om

    DateTime dayDateFrom = null;
    ArrayList<Date> dayDates = new ArrayList<>();
    ArrayList<ArrayList<RBAgendaEvent>> daysSpanningEvents = new ArrayList<>();
    ArrayList<ArrayList<RBAgendaEvent>> daysEvents = new ArrayList<>();

    // Prepare structures...
    for (int i = 0; i < days; i++) {
        dayDateFrom = fromDate.plusDays(i);
        dayDates.add(dayDateFrom.toDate());
        daysSpanningEvents.add(new ArrayList<RBAgendaEvent>());
        daysEvents.add(new ArrayList<RBAgendaEvent>());
    }

    // Arranges events by day...
    for (SchedEventInstance sei : instances) {
        for (int i = 0; i < days; i++) {
            dayDateFrom = fromDate.plusDays(i);
            if (isInDay(utz, dayDateFrom, sei.getStartDate(), sei.getEndDate())) {
                Calendar calendar = calendars.get(sei.getCalendarId());
                boolean spanning = true;
                Integer spanLeft = null, spanRight = null;
                if (!sei.getAllDay() && startsInDay(utz, dayDateFrom, sei.getStartDate())
                        && endsInDay(utz, dayDateFrom, sei.getEndDate())) {
                    spanning = false;
                } else {
                    if (startsInDay(utz, dayDateFrom, sei.getStartDate())) {
                        spanRight = DateTimeUtils.datesBetween(dayDateFrom, sei.getEndDate().withZone(utz));
                    }
                    if (endsInDay(utz, dayDateFrom, sei.getEndDate())) {
                        spanLeft = DateTimeUtils.datesBetween(sei.getStartDate().withZone(utz), dayDateFrom);
                    }
                    if (!startsInDay(utz, dayDateFrom, sei.getStartDate())
                            && !endsInDay(utz, dayDateFrom, sei.getEndDate())) {
                        spanLeft = DateTimeUtils.datesBetween(sei.getStartDate().withZone(utz), dayDateFrom);
                        spanRight = DateTimeUtils.datesBetween(dayDateFrom, sei.getEndDate().withZone(utz));
                    }
                }
                if (spanning) {
                    daysSpanningEvents.get(i).add(new RBAgendaEvent(calendar, sei, spanLeft, spanRight));
                } else {
                    daysEvents.get(i).add(new RBAgendaEvent(calendar, sei, spanLeft, spanRight));
                }
            }
        }
    }

    setDataSource(createBeanCollection(new Data(utz, fromDate.toLocalDate(), toDate.minusDays(1).toLocalDate(),
            dayDates, daysSpanningEvents, daysEvents)));
}

From source file:com.sonicle.webtop.calendar.Service.java

License:Open Source License

public void processGetPlanning(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    CoreUserSettings cus = getEnv().getCoreUserSettings();
    CoreManager core = WT.getCoreManager();
    ArrayList<MapItem> items = new ArrayList<>();
    Connection con = null;//from  w w  w  . ja  va  2 s.c o  m

    try {
        String eventStartDate = ServletUtils.getStringParameter(request, "startDate", true);
        String eventEndDate = ServletUtils.getStringParameter(request, "endDate", true);
        String timezone = ServletUtils.getStringParameter(request, "timezone", true);
        JsEvent.Attendee.List attendees = ServletUtils.getObjectParameter(request, "attendees",
                new JsEvent.Attendee.List(), JsEvent.Attendee.List.class);
        //JsAttendeeList attendees = ServletUtils.getObjectParameter(request, "attendees", new JsAttendeeList(), JsAttendeeList.class);

        // Parses string parameters
        DateTimeZone eventTz = DateTimeZone.forID(timezone);
        DateTime eventStartDt = DateTimeUtils.parseYmdHmsWithZone(eventStartDate, eventTz);
        DateTime eventEndDt = DateTimeUtils.parseYmdHmsWithZone(eventEndDate, eventTz);

        UserProfile up = getEnv().getProfile();
        DateTimeZone profileTz = up.getTimeZone();

        LocalTime localStartTime = eventStartDt.toLocalTime();
        LocalTime localEndTime = eventEndDt.toLocalTime();
        LocalTime fromTime = DateTimeUtils.min(localStartTime, us.getWorkdayStart());
        LocalTime toTime = DateTimeUtils.max(localEndTime, us.getWorkdayEnd());

        // Defines useful date/time formatters
        DateTimeFormatter ymdhmFmt = DateTimeUtils.createYmdHmFormatter();
        DateTimeFormatter tFmt = DateTimeUtils.createFormatter(cus.getShortTimeFormat());
        DateTimeFormatter dFmt = DateTimeUtils.createFormatter(cus.getShortDateFormat());

        ArrayList<String> spans = manager.generateTimeSpans(60, eventStartDt.toLocalDate(),
                eventEndDt.toLocalDate(), us.getWorkdayStart(), us.getWorkdayEnd(), profileTz);

        // Generates fields and columnsInfo dynamically
        ArrayList<FieldMeta> fields = new ArrayList<>();
        ArrayList<GridColumnMeta> colsInfo = new ArrayList<>();

        GridColumnMeta col = null;
        fields.add(new FieldMeta("recipient"));
        colsInfo.add(new GridColumnMeta("recipient"));
        for (String spanKey : spans) {
            LocalDateTime ldt = ymdhmFmt.parseLocalDateTime(spanKey);
            fields.add(new FieldMeta(spanKey));
            col = new GridColumnMeta(spanKey, tFmt.print(ldt));
            col.put("date", dFmt.print(ldt));
            col.put("overlaps", (ldt.compareTo(eventStartDt.toLocalDateTime()) >= 0)
                    && (ldt.compareTo(eventEndDt.toLocalDateTime()) < 0));
            colsInfo.add(col);
        }

        // Collects attendees availability...
        OUser user = null;
        UserProfileId profileId = null;
        LinkedHashSet<String> busyHours = null;
        MapItem item = null;
        for (JsEvent.Attendee attendee : attendees) {
            item = new MapItem();
            item.put("recipient", attendee.recipient);

            user = guessUserByAttendee(core, attendee.recipient);
            if (user != null) {
                profileId = new UserProfileId(user.getDomainId(), user.getUserId());
                busyHours = manager.calculateAvailabilitySpans(60, profileId, eventStartDt.withTime(fromTime),
                        eventEndDt.withTime(toTime), eventTz, true);
                for (String hourKey : spans) {
                    item.put(hourKey, busyHours.contains(hourKey) ? "busy" : "free");
                }
            } else {
                for (String spanKey : spans) {
                    item.put(spanKey, "unknown");
                }
            }
            items.add(item);
        }

        GridMetadata meta = new GridMetadata(true);
        meta.setFields(fields);
        meta.setColumnsInfo(colsInfo);
        new JsonResult(items, meta, items.size()).printTo(out);

    } catch (Exception ex) {
        logger.error("Error in GetPlanning", ex);
        new JsonResult(false, "Error").printTo(out);

    } finally {
        DbUtils.closeQuietly(con);
    }
}

From source file:com.sonicle.webtop.contacts.ContactsManager.java

License:Open Source License

public List<BaseReminder> getRemindersToBeNotified(DateTime now) {
    ArrayList<BaseReminder> alerts = new ArrayList<>();
    HashMap<UserProfileId, Boolean> okCache = new HashMap<>();
    HashMap<UserProfileId, DateTime> dateTimeCache = new HashMap<>();
    HashMap<UserProfileId, String> deliveryCache = new HashMap<>();
    ContactDAO cdao = ContactDAO.getInstance();
    Connection con = null;/* ww w.  j a va2s .co  m*/

    // Valid reminder times (see getAnniversaryReminderTime in options) 
    // are only at 0 and 30 min of each hour. So skip unuseful runs...
    if ((now.getMinuteOfHour() == 0) || (now.getMinuteOfHour() == 30)) {
        try {
            con = WT.getConnection(SERVICE_ID);
            LocalDate date = now.toLocalDate();

            List<VContact> bdays = cdao.viewOnBirthdayByDate(con, date);
            for (VContact cont : bdays) {
                boolean ok = false;
                if (!okCache.containsKey(cont.getCategoryProfileId())) {
                    ok = getAnniversaryReminderTime(dateTimeCache, cont.getCategoryProfileId(), date)
                            .withZone(DateTimeZone.UTC).equals(now);
                    okCache.put(cont.getCategoryProfileId(), ok);
                }

                if (ok) {
                    DateTime dateTime = getAnniversaryReminderTime(dateTimeCache, cont.getCategoryProfileId(),
                            date);
                    String delivery = getAnniversaryReminderDelivery(deliveryCache,
                            cont.getCategoryProfileId());
                    UserProfile.Data ud = WT.getUserData(cont.getCategoryProfileId());

                    if (delivery.equals(ContactsSettings.ANNIVERSARY_REMINDER_DELIVERY_EMAIL)) {
                        alerts.add(createAnniversaryEmailReminder(ud.getLocale(), ud.getEmail(), true, cont,
                                dateTime));
                    } else if (delivery.equals(ContactsSettings.ANNIVERSARY_REMINDER_DELIVERY_APP)) {
                        alerts.add(createAnniversaryInAppReminder(ud.getLocale(), true, cont, dateTime));
                    }
                }
            }

            List<VContact> anns = cdao.viewOnAnniversaryByDate(con, date);
            for (VContact cont : anns) {
                boolean ok = false;
                if (!okCache.containsKey(cont.getCategoryProfileId())) {
                    ok = getAnniversaryReminderTime(dateTimeCache, cont.getCategoryProfileId(), date)
                            .withZone(DateTimeZone.UTC).equals(now);
                    okCache.put(cont.getCategoryProfileId(), ok);
                }

                if (ok) {
                    DateTime dateTime = getAnniversaryReminderTime(dateTimeCache, cont.getCategoryProfileId(),
                            date);
                    String delivery = getAnniversaryReminderDelivery(deliveryCache,
                            cont.getCategoryProfileId());
                    UserProfile.Data ud = WT.getUserData(cont.getCategoryProfileId());

                    if (delivery.equals(ContactsSettings.ANNIVERSARY_REMINDER_DELIVERY_EMAIL)) {
                        alerts.add(createAnniversaryEmailReminder(ud.getLocale(), ud.getEmail(), false, cont,
                                dateTime));
                    } else if (delivery.equals(ContactsSettings.ANNIVERSARY_REMINDER_DELIVERY_APP)) {
                        alerts.add(createAnniversaryInAppReminder(ud.getLocale(), false, cont, dateTime));
                    }
                }
            }

        } catch (Exception ex) {
            logger.error("Error collecting reminder alerts", ex);
        } finally {
            DbUtils.closeQuietly(con);
        }
    }
    return alerts;
}

From source file:com.stagecents.pay.domain.Overtime.java

License:Open Source License

@Override
public void processHours(Interval interval, Activity activity, Timecard timecard, Position position) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();//from   www. ja v a2 s  .  c om

    // 1. Test start time against normal start time.
    DateTime regStart = start;
    if (position.getNormalStart() != null) {
        DateTime normalStart = start.toLocalDate().toDateTime(position.getNormalStart());
        regStart = regStart.isBefore(normalStart) ? normalStart : regStart;
    }

    // Update the time card with any premium time prior to the position's
    // normal start
    if (start.isBefore(regStart)) {
        updateTimecard(timecard, activity, new Interval(start, regStart));
    }

    // 2. Test end time against minimum call.
    MinimumCallValue mc = getMinimumCall(new Interval(start, end));
    if (mc != null) {
        long minCall = (long) mc.getDefaultValue() * 1000 * 60 * 60;
        DateTime minCallEnd = end.plus(minCall);
        end = end.isBefore(minCallEnd) ? minCallEnd : end;
    }

    // Test end time against normal end time.
    DateTime regEnd = end;
    if (position.getNormalEnd() != null) {
        DateTime normalEnd = end.toLocalDate().toDateTime(position.getNormalEnd());
        regEnd = normalEnd.isBefore(regEnd) ? normalEnd : regEnd;
    }

    // Test end time against maximum time for position.
    if (position.getMaximumHours() > 0) {
        float priorHrs = getPriorHours(timecard, regStart.toLocalDate());
        long availMillis = (long) (position.getMaximumHours() - priorHrs) * 1000 * 60 * 60;
        DateTime availEnd = regStart.plus(availMillis);
        regEnd = availEnd.isBefore(regEnd) ? availEnd : regEnd;
    }

    // Update the timecard with any premium time after the position's normal
    // end
    if (regEnd.isBefore(end)) {
        updateTimecard(timecard, activity, new Interval(regEnd, end));
    }
}

From source file:com.stagecents.pay.domain.RegularWages.java

License:Open Source License

protected void doProcessHours(Interval interval, Activity activity, Timecard timecard, Position position) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();//from  w  w w.  j  av  a 2 s .c  om

    // Test start time against normal start time.
    if (position.getNormalStart() != null) {
        DateTime normalStart = start.toLocalDate().toDateTime(position.getNormalStart());
        start = start.isBefore(normalStart) ? normalStart : start;
    }

    // Test end time against minimum call.
    MinimumCallValue mc = getMinimumCall(activity.duration());
    if (mc != null) {
        long minCall = (long) mc.getDefaultValue() * 1000 * 60 * 60;
        DateTime minCallEnd = end.plus(minCall);
        end = end.isBefore(minCallEnd) ? minCallEnd : end;
    }

    // Test end time against normal end time.
    if (position.getNormalEnd() != null) {
        DateTime normalEnd = end.toLocalDate().toDateTime(position.getNormalEnd());
        end = end.isAfter(normalEnd) ? normalEnd : end;
    }

    // Test end time against maximum time for position.
    if (position.getMaximumHours() > 0) {
        float priorHours = getPriorHours(timecard, start.toLocalDate());
        long availMillis = (long) (position.getMaximumHours() - priorHours) * 1000 * 60 * 60;
        DateTime availEnd = start.plus(availMillis);
        end = availEnd.isBefore(end) ? availEnd : end;
    }

    updateTimecard(timecard, activity, new Interval(start, end));
}

From source file:dao.OuvrageDao.java

private JsonObject ObjectToJson(Ouvrage ouvrage) {
    DateTime date = new DateTime(ouvrage.getDatePublication());
    JsonObject ouvrageJson = JsonObject.empty().put("isbn", ouvrage.getIsbn()).put("titre", ouvrage.getTitre())
            .put("auteur", ouvrage.getAuteur()).put("numBL", ouvrage.getNumBL())
            .put("numBC", ouvrage.getNumBC()).put("categorie", ouvrage.getCategorie().getId())
            .put("prix", ouvrage.getPrixUnitaire()).put("librairie", ouvrage.getLibrairie())
            .put("datePublication", date.toLocalDate().toString()).put("edition", ouvrage.getEdition());
    return ouvrageJson;
}

From source file:dao.PretDao.java

private JsonObject ObjectToJson(Pret pret) {
    DateTime datePret = new DateTime(pret.getDatePret());
    DateTime dateRetour = new DateTime(pret.getDateRetour());

    JsonObject pretJson = JsonObject.empty()

            .put("idOuvrage", pret.getOuvrage().getId()).put("idEtudiant", pret.getEtudiant().getId())
            .put("idProfesseur", pret.getProfesseur().getId())
            .put("dateRetour", dateRetour.toLocalDate().toString())
            .put("datePret", datePret.toLocalDate().toString());
    return pretJson;
}