Example usage for org.joda.time Interval toDuration

List of usage examples for org.joda.time Interval toDuration

Introduction

In this page you can find the example usage for org.joda.time Interval toDuration.

Prototype

public Duration toDuration() 

Source Link

Document

Gets the duration of this time interval.

Usage

From source file:jp.furplag.util.time.lunisolar.LunisolarDateTimeUtils.java

License:Apache License

public static int getDayOfMonth(final double firstDayOfMonth, final double julianDay, DateTimeZone zone) {
    DateTime firstDay = toDT(firstDayOfMonth, zone, true);
    if (firstDay == null)
        throw new IllegalArgumentException("\"firstDayOfMonth\" must NOT be empty.");
    DateTime then = toDT(julianDay, zone).withTimeAtStartOfDay();
    Interval interval = firstDayOfMonth > julianDay ? new Interval(then, firstDay.withTimeAtStartOfDay())
            : new Interval(firstDay.withTimeAtStartOfDay(), then);

    return (int) interval.toDuration().getStandardDays() + 1;
}

From source file:mobi.daytoday.DayToDay.DateWrap.java

License:Apache License

/**
 * Find the difference in days between the given dates and return the result
 * /* w ww. j a  v a  2 s.  com*/
 * @param dateOne
 *          - date in DATE_FORMAT format
 * @param dateTwo
 *          - date in DATE_FORMAT format
 * @return number of days between the two given dates
 * @throws Exception
 *           - if there is any error
 */
public static long daysBetween(String dateOne, String dateTwo) throws Exception {
    DateTime firstDate = dtForm.parseDateTime(dateOne);
    DateTime secondDate = dtForm.parseDateTime(dateTwo);

    Interval difference;
    if (firstDate.isAfter(secondDate)) {
        difference = new Interval(secondDate, firstDate);
    } else {
        difference = new Interval(firstDate, secondDate);
    }

    return difference.toDuration().getStandardDays();
}

From source file:module.workflow.domain.FileUploadLog.java

License:Open Source License

/**
 * /*from  ww w . j  av  a 2 s.  com*/
 * @return true if FileUploadLog has a date 1min within processFile's
 *         creation date, and the names and other details match
 */
private static boolean matches(FileUploadLog fileUploadLog, ProcessFile processFile) {
    DateTime creationDate = processFile.getCreationDate();
    if (creationDate == null) {
        throw new IllegalArgumentException("File: " + processFile.getExternalId() + " of class: "
                + processFile.getClass().getSimpleName() + " has no creation date");
    }

    DateTime whenOperationWasRan = fileUploadLog.getWhenOperationWasRan();

    Interval interval = null;
    if (creationDate.isBefore(whenOperationWasRan)) {
        interval = new Interval(creationDate, whenOperationWasRan);
    } else {

        interval = new Interval(whenOperationWasRan, creationDate);
    }
    if (interval.toDuration().isLongerThan(new Duration(60000))) {
        return false;
    }
    Strings descriptionArguments = fileUploadLog.getDescriptionArguments();
    if (!descriptionArguments.hasStringIgnoreCase(processFile.getFilename())) {
        return false;
    }
    if (!descriptionArguments.hasStringIgnoreCase(processFile.getDisplayName())) {
        return false;
    }

    return true;

}

From source file:org.apache.druid.indexing.overlord.http.OverlordResource.java

License:Apache License

@GET
@Path("/tasks")
@Produces(MediaType.APPLICATION_JSON)/*from   ww w .  j a  v a 2  s  .  c  o m*/
public Response getTasks(@QueryParam("state") final String state,
        @QueryParam("datasource") final String dataSource,
        @QueryParam("createdTimeInterval") final String createdTimeInterval,
        @QueryParam("max") final Integer maxCompletedTasks, @QueryParam("type") final String type,
        @Context final HttpServletRequest req) {
    //check for valid state
    if (state != null) {
        if (!API_TASK_STATES.contains(StringUtils.toLowerCase(state))) {
            return Response
                    .status(Status.BAD_REQUEST).entity(StringUtils
                            .format("Invalid state : %s, valid values are: %s", state, API_TASK_STATES))
                    .build();
        }
    }
    // early authorization check if datasource != null
    // fail fast if user not authorized to access datasource
    if (dataSource != null) {
        final ResourceAction resourceAction = new ResourceAction(
                new Resource(dataSource, ResourceType.DATASOURCE), Action.READ);
        final Access authResult = AuthorizationUtils.authorizeResourceAction(req, resourceAction,
                authorizerMapper);
        if (!authResult.isAllowed()) {
            throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                    .entity(StringUtils.format("Access-Check-Result: %s", authResult.toString())).build());
        }
    }
    List<TaskStatusPlus> finalTaskList = new ArrayList<>();
    Function<AnyTask, TaskStatusPlus> activeTaskTransformFunc = workItem -> new TaskStatusPlus(
            workItem.getTaskId(), workItem.getTaskType(), workItem.getCreatedTime(),
            workItem.getQueueInsertionTime(), workItem.getTaskState(), workItem.getRunnerTaskState(), null,
            workItem.getLocation(), workItem.getDataSource(), null);

    Function<TaskInfo<Task, TaskStatus>, TaskStatusPlus> completeTaskTransformFunc = taskInfo -> new TaskStatusPlus(
            taskInfo.getId(), taskInfo.getTask() == null ? null : taskInfo.getTask().getType(),
            taskInfo.getCreatedTime(),
            // Would be nice to include the real queue insertion time, but the
            // TaskStorage API doesn't yet allow it.
            DateTimes.EPOCH, taskInfo.getStatus().getStatusCode(), RunnerTaskState.NONE,
            taskInfo.getStatus().getDuration(),
            taskInfo.getStatus().getLocation() == null ? TaskLocation.unknown()
                    : taskInfo.getStatus().getLocation(),
            taskInfo.getDataSource(), taskInfo.getStatus().getErrorMsg());

    //checking for complete tasks first to avoid querying active tasks if user only wants complete tasks
    if (state == null || "complete".equals(StringUtils.toLowerCase(state))) {
        Duration createdTimeDuration = null;
        if (createdTimeInterval != null) {
            final Interval theInterval = Intervals.of(StringUtils.replace(createdTimeInterval, "_", "/"));
            createdTimeDuration = theInterval.toDuration();
        }
        final List<TaskInfo<Task, TaskStatus>> taskInfoList = taskStorageQueryAdapter
                .getCompletedTaskInfoByCreatedTimeDuration(maxCompletedTasks, createdTimeDuration, dataSource);
        final List<TaskStatusPlus> completedTasks = taskInfoList.stream().map(completeTaskTransformFunc::apply)
                .collect(Collectors.toList());
        finalTaskList.addAll(completedTasks);
    }

    final List<TaskInfo<Task, TaskStatus>> allActiveTaskInfo;
    final List<AnyTask> allActiveTasks = new ArrayList<>();
    if (state == null || !"complete".equals(StringUtils.toLowerCase(state))) {
        allActiveTaskInfo = taskStorageQueryAdapter.getActiveTaskInfo(dataSource);
        for (final TaskInfo<Task, TaskStatus> task : allActiveTaskInfo) {
            allActiveTasks
                    .add(new AnyTask(task.getId(), task.getTask() == null ? null : task.getTask().getType(),
                            SettableFuture.create(), task.getDataSource(), null, null, task.getCreatedTime(),
                            DateTimes.EPOCH, TaskLocation.unknown()));
        }
    }
    if (state == null || "waiting".equals(StringUtils.toLowerCase(state))) {
        final List<AnyTask> waitingWorkItems = filterActiveTasks(RunnerTaskState.WAITING, allActiveTasks);
        List<TaskStatusPlus> transformedWaitingList = waitingWorkItems.stream()
                .map(activeTaskTransformFunc::apply).collect(Collectors.toList());
        finalTaskList.addAll(transformedWaitingList);
    }
    if (state == null || "pending".equals(StringUtils.toLowerCase(state))) {
        final List<AnyTask> pendingWorkItems = filterActiveTasks(RunnerTaskState.PENDING, allActiveTasks);
        List<TaskStatusPlus> transformedPendingList = pendingWorkItems.stream()
                .map(activeTaskTransformFunc::apply).collect(Collectors.toList());
        finalTaskList.addAll(transformedPendingList);
    }
    if (state == null || "running".equals(StringUtils.toLowerCase(state))) {
        final List<AnyTask> runningWorkItems = filterActiveTasks(RunnerTaskState.RUNNING, allActiveTasks);
        List<TaskStatusPlus> transformedRunningList = runningWorkItems.stream()
                .map(activeTaskTransformFunc::apply).collect(Collectors.toList());
        finalTaskList.addAll(transformedRunningList);
    }
    final List<TaskStatusPlus> authorizedList = securedTaskStatusPlus(finalTaskList, dataSource, type, req);
    return Response.ok(authorizedList).build();
}

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Test if an event date specifies a duration of one day or less.
 * /*from ww  w  . ja  v a  2s  .  c o  m*/
 * @param eventDate to test.
 * @return true if duration is one day or less.
 */
public static boolean specificToDay(String eventDate) {
    boolean result = false;
    if (!isEmpty(eventDate)) {
        Interval eventDateInterval = extractInterval(eventDate);
        logger.debug(eventDateInterval);
        logger.debug(eventDateInterval.toDuration());
        if (eventDateInterval.toDuration().getStandardDays() < 1l) {
            result = true;
        } else if (eventDateInterval.toDuration().getStandardDays() == 1l
                && eventDateInterval.getStart().getDayOfYear() == eventDateInterval.getEnd().getDayOfYear()) {
            result = true;
        }
    }
    return result;
}

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Test if an event date specifies a duration of 31 days or less.
 * /*from w  w  w.ja  v  a 2  s  . c o m*/
 * Provides: EVENTDATE_PRECISON_MONTH_OR_BETTER
 * 
 * @param eventDate to test.
 * @return true if duration is 31 days or less.
 */
public static boolean specificToMonthScale(String eventDate) {
    boolean result = false;
    if (!isEmpty(eventDate)) {
        Interval eventDateInterval = extractDateInterval(eventDate);
        if (eventDateInterval.toDuration().getStandardDays() <= 31l) {
            result = true;
        }
    }
    return result;
}

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Test if an event date specifies a duration of one year or less.
 * // w  w  w  . j ava2  s.c o  m
 * Provides: EVENTDATE_PRECISON_YEAR_OR_BETTER
 * 
 * @param eventDate to test.
 * @return true if duration is 365 days or less.
 */
public static boolean specificToYearScale(String eventDate) {
    boolean result = false;
    if (!isEmpty(eventDate)) {
        Interval eventDateInterval = extractDateInterval(eventDate);
        if (eventDateInterval.toDuration().getStandardDays() <= 365l) {
            result = true;
        }
    }
    return result;
}

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Test if an event date specifies a duration of 10 years or less.
 * //from  w  w  w.  j a  va 2 s .  c o m
 * @param eventDate to test.
 * @return true if duration is 10 years or or less.
 */
public static boolean specificToDecadeScale(String eventDate) {
    boolean result = false;
    if (!isEmpty(eventDate)) {
        Interval eventDateInterval = extractDateInterval(eventDate);
        if (eventDateInterval.toDuration().getStandardDays() <= 3650l) {
            result = true;
        }
    }
    return result;
}

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Measure the duration of an event date in seconds, when a time is 
 * specified, ceiling to the nearest second, when a time is not 
 * specified, from the date midnight at the beginning of a date 
 * range to the last second of the day at the end of the range.  This 
 * may return one second less than your expectation for the number 
 * of seconds in the interval (e.g. 86399 seconds for the duration of 
 * a day specified as 1980-01-01./* w w w.j  a v a2s. co  m*/
 * 
 * Provides: EVENT_DATE_DURATION_SECONDS
 * 
 * Suggested by Alex Thompson in a TDWG data quality task group call.
 * 
 * @param eventDate to test.
 * @return the duration of eventDate in seconds.
 */
public static long measureDurationSeconds(String eventDate) {
    long result = 0l;
    if (!isEmpty(eventDate)) {
        Interval eventDateInterval = DateUtils.extractInterval(eventDate);
        logger.debug(eventDateInterval.toDuration().getStandardDays());
        logger.debug(eventDateInterval);
        long mills = eventDateInterval.toDurationMillis();
        result = (long) Math.ceil(mills / 1000l);
    }
    return result;
}

From source file:org.jasig.portlet.calendar.mvc.controller.CalendarController.java

License:Apache License

@RequestMapping
public ModelAndView getCalendar(@RequestParam(required = false, value = "interval") String intervalString,
        RenderRequest request) {/*w  ww .j a v  a2  s.  c  o  m*/

    PortletSession session = request.getPortletSession(true);

    PortletPreferences prefs = request.getPreferences();

    Map<String, Object> model = new HashMap<String, Object>();

    // get the list of hidden calendars
    @SuppressWarnings("unchecked")
    HashMap<Long, String> hiddenCalendars = (HashMap<Long, String>) session.getAttribute("hiddenCalendars");

    // indicate if the current user is a guest (unauthenticated) user
    model.put("guest", request.getRemoteUser() == null);

    /**
     * Add and remove calendars from the hidden list.  Hidden calendars
     * will be fetched, but rendered invisible in the view.
     */

    // check the request parameters to see if we need to add any
    // calendars to the list of hidden calendars
    String hideCalendar = request.getParameter("hideCalendar");
    if (hideCalendar != null) {
        hiddenCalendars.put(Long.valueOf(hideCalendar), "true");
        session.setAttribute("hiddenCalendars", hiddenCalendars);
    }

    // check the request parameters to see if we need to remove
    // any calendars from the list of hidden calendars
    String showCalendar = request.getParameter("showCalendar");
    if (showCalendar != null) {
        hiddenCalendars.remove(Long.valueOf(showCalendar));
        session.setAttribute("hiddenCalendars", hiddenCalendars);
    }

    // See if we're configured to show or hide the jQueryUI DatePicker.
    // By default, we assume we are to show the DatePicker because that's
    // the classic behavior.
    String showDatePicker = prefs.getValue("showDatePicker", "true");
    model.put("showDatePicker", showDatePicker);

    /**
     * Find our desired starting and ending dates.
     */

    Interval interval = null;

    if (!StringUtils.isEmpty(intervalString)) {
        interval = Interval.parse(intervalString);
        model.put("startDate", new DateMidnight(interval.getStart()).toDate());
        model.put("days", interval.toDuration().getStandardDays());
        model.put("endDate", new DateMidnight(interval.getEnd()));
    } else {
        //StartDate can only be changed via an AJAX request
        DateMidnight startDate = (DateMidnight) session.getAttribute("startDate");
        log.debug("startDate from session is: " + startDate);
        model.put("startDate", startDate.toDate());

        // find how many days into the future we should display events
        int days = (Integer) session.getAttribute("days");
        model.put("days", days);

        // set the end date based on our desired time period
        DateMidnight endDate = startDate.plusDays(days);
        model.put("endDate", endDate.toDate());

        interval = new Interval(startDate, endDate);
    }

    // define "today" and "tomorrow" so we can display these specially in the
    // user interface
    // get the user's configured time zone
    String timezone = (String) session.getAttribute("timezone");
    DateMidnight today = new DateMidnight(DateTimeZone.forID(timezone));
    model.put("today", today.toDate());
    model.put("tomorrow", today.plusDays(1).toDate());

    /**
     * retrieve the calendars defined for this portlet instance
     */

    CalendarSet<?> set = calendarSetDao.getCalendarSet(request);
    List<CalendarConfiguration> calendars = new ArrayList<CalendarConfiguration>();
    calendars.addAll(set.getConfigurations());
    Collections.sort(calendars, new CalendarConfigurationByNameComparator());
    model.put("calendars", calendars);

    Map<Long, Integer> colors = new HashMap<Long, Integer>();
    Map<Long, String> links = new HashMap<Long, String>();
    int index = 0;
    for (CalendarConfiguration callisting : calendars) {

        // don't bother to fetch hidden calendars
        if (hiddenCalendars.get(callisting.getId()) == null) {

            try {

                // get an instance of the adapter for this calendar
                ICalendarAdapter adapter = (ICalendarAdapter) applicationContext
                        .getBean(callisting.getCalendarDefinition().getClassName());

                //get hyperlink to calendar
                String link = adapter.getLink(callisting, interval, request);
                if (link != null) {
                    links.put(callisting.getId(), link);
                }

            } catch (NoSuchBeanDefinitionException ex) {
                log.error("Calendar class instance could not be found: " + ex.getMessage());
            } catch (CalendarLinkException linkEx) {
                // Not an error. Ignore
            } catch (Exception ex) {
                log.error(ex);
            }
        }

        // add this calendar's id to the color map
        colors.put(callisting.getId(), index);
        index++;

    }

    model.put("timezone", session.getAttribute("timezone"));
    model.put("colors", colors);
    model.put("links", links);
    model.put("hiddenCalendars", hiddenCalendars);

    /*
     * Check if we need to disable either the preferences and/or administration links
     */

    Boolean disablePrefs = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_PREFERENCES, "false"));
    model.put(PREFERENCE_DISABLE_PREFERENCES, disablePrefs);
    Boolean disableAdmin = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_ADMINISTRATION, "false"));
    model.put(PREFERENCE_DISABLE_ADMINISTRATION, disableAdmin);

    return new ModelAndView(viewSelector.getCalendarViewName(request), "model", model);
}