Example usage for org.joda.time Interval equals

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

Introduction

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

Prototype

public boolean equals(Object readableInterval) 

Source Link

Document

Compares this object with the specified object for equality based on start and end millis plus the chronology.

Usage

From source file:io.druid.server.ClientInfoResource.java

License:Apache License

@GET
@Path("/{dataSourceName}")
@Produces(MediaType.APPLICATION_JSON)//from w  ww. j av  a2s  .c om
public Map<String, Object> getDatasource(@PathParam("dataSourceName") String dataSourceName,
        @QueryParam("interval") String interval, @QueryParam("full") String full) {
    if (full == null) {
        return ImmutableMap.<String, Object>of(KEY_DIMENSIONS,
                getDatasourceDimensions(dataSourceName, interval), KEY_METRICS,
                getDatasourceMetrics(dataSourceName, interval));
    }

    Interval theInterval;
    if (interval == null || interval.isEmpty()) {
        DateTime now = getCurrentTime();
        theInterval = new Interval(segmentMetadataQueryConfig.getDefaultHistory(), now);
    } else {
        theInterval = new Interval(interval);
    }

    TimelineLookup<String, ServerSelector> timeline = timelineServerView
            .getTimeline(new TableDataSource(dataSourceName));
    Iterable<TimelineObjectHolder<String, ServerSelector>> serversLookup = timeline != null
            ? timeline.lookup(theInterval)
            : null;
    if (serversLookup == null || Iterables.isEmpty(serversLookup)) {
        return Collections.EMPTY_MAP;
    }
    Map<Interval, Object> servedIntervals = new TreeMap<>(new Comparator<Interval>() {
        @Override
        public int compare(Interval o1, Interval o2) {
            if (o1.equals(o2) || o1.overlaps(o2)) {
                return 0;
            } else {
                return o1.isBefore(o2) ? -1 : 1;
            }
        }
    });

    for (TimelineObjectHolder<String, ServerSelector> holder : serversLookup) {
        final Set<Object> dimensions = Sets.newHashSet();
        final Set<Object> metrics = Sets.newHashSet();
        final PartitionHolder<ServerSelector> partitionHolder = holder.getObject();
        if (partitionHolder.isComplete()) {
            for (ServerSelector server : partitionHolder.payloads()) {
                final DataSegment segment = server.getSegment();
                dimensions.addAll(segment.getDimensions());
                metrics.addAll(segment.getMetrics());
            }
        }

        servedIntervals.put(holder.getInterval(),
                ImmutableMap.of(KEY_DIMENSIONS, dimensions, KEY_METRICS, metrics));
    }

    //collapse intervals if they abut and have same set of columns
    Map<String, Object> result = Maps.newLinkedHashMap();
    Interval curr = null;
    Map<String, Set<String>> cols = null;
    for (Map.Entry<Interval, Object> e : servedIntervals.entrySet()) {
        Interval ival = e.getKey();
        if (curr != null && curr.abuts(ival) && cols.equals(e.getValue())) {
            curr = curr.withEnd(ival.getEnd());
        } else {
            if (curr != null) {
                result.put(curr.toString(), cols);
            }
            curr = ival;
            cols = (Map<String, Set<String>>) e.getValue();
        }
    }
    //add the last one in
    if (curr != null) {
        result.put(curr.toString(), cols);
    }
    return result;
}

From source file:org.apache.druid.query.aggregation.FilteredAggregatorFactory.java

License:Apache License

@Override
public AggregatorFactory optimizeForSegment(PerSegmentQueryOptimizationContext optimizationContext) {
    if (dimFilter instanceof IntervalDimFilter) {
        IntervalDimFilter intervalDimFilter = ((IntervalDimFilter) dimFilter);
        if (intervalDimFilter.getExtractionFn() != null) {
            // no support for extraction functions right now
            return this;
        }//from  w  w w  .  ja v a 2 s  .c o  m

        if (!intervalDimFilter.getDimension().equals(ColumnHolder.TIME_COLUMN_NAME)) {
            // segment time boundary optimization only applies when we filter on __time
            return this;
        }

        Interval segmentInterval = optimizationContext.getSegmentDescriptor().getInterval();
        List<Interval> filterIntervals = intervalDimFilter.getIntervals();
        List<Interval> excludedFilterIntervals = new ArrayList<>();
        List<Interval> effectiveFilterIntervals = new ArrayList<>();

        boolean segmentIsCovered = false;
        for (Interval filterInterval : filterIntervals) {
            Interval overlap = filterInterval.overlap(segmentInterval);
            if (overlap == null) {
                excludedFilterIntervals.add(filterInterval);
                continue;
            }

            if (overlap.equals(segmentInterval)) {
                segmentIsCovered = true;
                break;
            } else {
                // clip the overlapping interval to the segment time boundaries
                effectiveFilterIntervals.add(overlap);
            }
        }

        // we can skip applying this filter, everything in the segment will match
        if (segmentIsCovered) {
            return delegate;
        }

        // we can skip this filter, nothing in the segment would match
        if (excludedFilterIntervals.size() == filterIntervals.size()) {
            return new SuppressedAggregatorFactory(delegate);
        }

        return new FilteredAggregatorFactory(delegate,
                new IntervalDimFilter(intervalDimFilter.getDimension(), effectiveFilterIntervals,
                        intervalDimFilter.getExtractionFn(), intervalDimFilter.getFilterTuning()),
                this.name);
    } else {
        return this;
    }
}

From source file:org.apache.druid.server.ClientInfoResource.java

License:Apache License

@GET
@Path("/{dataSourceName}")
@Produces(MediaType.APPLICATION_JSON)/*from   w  w w . j  a  va 2 s  .  com*/
@ResourceFilters(DatasourceResourceFilter.class)
public Map<String, Object> getDatasource(@PathParam("dataSourceName") String dataSourceName,
        @QueryParam("interval") String interval, @QueryParam("full") String full) {
    if (full == null) {
        return ImmutableMap.of(KEY_DIMENSIONS, getDataSourceDimensions(dataSourceName, interval), KEY_METRICS,
                getDataSourceMetrics(dataSourceName, interval));
    }

    Interval theInterval;
    if (interval == null || interval.isEmpty()) {
        DateTime now = getCurrentTime();
        theInterval = new Interval(segmentMetadataQueryConfig.getDefaultHistory(), now);
    } else {
        theInterval = Intervals.of(interval);
    }

    TimelineLookup<String, ServerSelector> timeline = timelineServerView
            .getTimeline(new TableDataSource(dataSourceName));
    Iterable<TimelineObjectHolder<String, ServerSelector>> serversLookup = timeline != null
            ? timeline.lookup(theInterval)
            : null;
    if (serversLookup == null || Iterables.isEmpty(serversLookup)) {
        return Collections.EMPTY_MAP;
    }
    Map<Interval, Object> servedIntervals = new TreeMap<>(new Comparator<Interval>() {
        @Override
        public int compare(Interval o1, Interval o2) {
            if (o1.equals(o2) || o1.overlaps(o2)) {
                return 0;
            } else {
                return o1.isBefore(o2) ? -1 : 1;
            }
        }
    });

    for (TimelineObjectHolder<String, ServerSelector> holder : serversLookup) {
        final Set<Object> dimensions = new HashSet<>();
        final Set<Object> metrics = new HashSet<>();
        final PartitionHolder<ServerSelector> partitionHolder = holder.getObject();
        if (partitionHolder.isComplete()) {
            for (ServerSelector server : partitionHolder.payloads()) {
                final DataSegment segment = server.getSegment();
                dimensions.addAll(segment.getDimensions());
                metrics.addAll(segment.getMetrics());
            }
        }

        servedIntervals.put(holder.getInterval(),
                ImmutableMap.of(KEY_DIMENSIONS, dimensions, KEY_METRICS, metrics));
    }

    //collapse intervals if they abut and have same set of columns
    Map<String, Object> result = Maps.newLinkedHashMap();
    Interval curr = null;
    Map<String, Set<String>> cols = null;
    for (Map.Entry<Interval, Object> e : servedIntervals.entrySet()) {
        Interval ival = e.getKey();
        if (curr != null && curr.abuts(ival) && cols.equals(e.getValue())) {
            curr = curr.withEnd(ival.getEnd());
        } else {
            if (curr != null) {
                result.put(curr.toString(), cols);
            }
            curr = ival;
            cols = (Map<String, Set<String>>) e.getValue();
        }
    }
    //add the last one in
    if (curr != null) {
        result.put(curr.toString(), cols);
    }
    return result;
}

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

License:Apache License

/**
 * Identify whether an event date and a year, month, and day are consistent, where consistent 
 * means that either the eventDate is a single day and the year-month-day represent the same day
 * or that eventDate is a date range that defines the same date range as year-month (where day is 
 * null) or the same date range as year (where day and month are null).  If all of eventDate, 
 * year, month, and day are null or empty, then returns true.  If eventDate specifies an interval
 * of more than one day and day is specified, then result is true if the day is the first day of the 
 * interval.  If eventDate is not null and year, month, and day are, then result is false (data is 
 * not consistent with no data)./*from   w ww .j  av  a2s. c  o m*/
 * 
 * Provides: EVENTDATE_CONSISTENT_WITH_DAY_MONTH_YEAR 
 * 
 * @param eventDate dwc:eventDate
 * @param year dwc:year
 * @param month dwc:month
 * @param day dwc:day
 * 
 * @return true if eventDate is consistent with year-month-day.
 */
public static boolean isConsistent(String eventDate, String year, String month, String day) {
    boolean result = false;
    StringBuffer date = new StringBuffer();
    if (!isEmpty(eventDate)) {
        if (!isEmpty(year) && !isEmpty(month) && !isEmpty(day)) {
            date.append(year).append("-").append(month).append("-").append(day);
            if (!isRange(eventDate)) {
                DateMidnight eventDateDate = extractDate(eventDate);
                DateMidnight bitsDate = extractDate(date.toString());
                if (eventDateDate != null && bitsDate != null) {
                    if (eventDateDate.year().compareTo(bitsDate) == 0
                            && eventDateDate.monthOfYear().compareTo(bitsDate) == 0
                            && eventDateDate.dayOfMonth().compareTo(bitsDate) == 0) {
                        result = true;
                    }
                }
            } else {
                Interval eventDateDate = extractDateInterval(eventDate);
                DateMidnight bitsDate = extractDate(date.toString());
                if (eventDateDate != null && bitsDate != null) {
                    if (eventDateDate.getStart().year().compareTo(bitsDate) == 0
                            && eventDateDate.getStart().monthOfYear().compareTo(bitsDate) == 0
                            && eventDateDate.getStart().dayOfMonth().compareTo(bitsDate) == 0) {
                        result = true;
                    }
                }

            }
        }
        if (!isEmpty(year) && !isEmpty(month) && isEmpty(day)) {
            date.append(year).append("-").append(month);
            Interval eventDateInterval = extractDateInterval(eventDate);
            Interval bitsInterval = extractDateInterval(date.toString());
            if (eventDateInterval.equals(bitsInterval)) {
                result = true;
            }
        }
        if (!isEmpty(year) && isEmpty(month) && isEmpty(day)) {
            date.append(year);
            Interval eventDateInterval = extractDateInterval(eventDate);
            Interval bitsInterval = extractDateInterval(date.toString());
            if (eventDateInterval.equals(bitsInterval)) {
                result = true;
            }
        }
    } else {
        if (isEmpty(year) && isEmpty(month) && isEmpty(day)) {
            // eventDate, year, month, and day are all empty, treat as consistent.
            result = true;
        }
    }
    return result;
}

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

License:Apache License

/**
 * Compare two strings that should represent event dates (ingoring time, if not a date range)
 * // w  w  w  . j  a  v a2 s  .  c o m
 * @param eventDate to compare with second event date
 * @param secondEventDate to compare with
 * @return true if the two provided event dates represent the same interval.
 */
public static Boolean eventsAreSameInterval(String eventDate, String secondEventDate) {
    boolean result = false;
    try {
        Interval interval = null;
        Interval secondInterval = null;
        interval = DateUtils.extractDateInterval(eventDate);
        secondInterval = DateUtils.extractDateInterval(secondEventDate);
        logger.debug(interval.toString());
        logger.debug(secondInterval.toString());
        result = interval.equals(secondInterval);
    } catch (IllegalFieldValueException ex) {
        // field format error, can't parse as date, log at debug level.
        logger.debug(ex.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    return result;
}

From source file:org.jasig.portlet.calendar.mvc.CalendarDisplayEvent.java

License:Apache License

/**
 * Constructs an object from specified data.
 *
 * @param event "Raw" Event object//w w  w .j  a v  a  2 s  .  c o m
 * @param eventInterval Interval portion of the event that applies to this specific day
 * @param theSpecificDay Interval of the specific day in question
 * @param df date formatter to represent date displays
 * @param tf time formatter to represent time displays
 */
public CalendarDisplayEvent(VEvent event, Interval eventInterval, Interval theSpecificDay, DateTimeFormatter df,
        DateTimeFormatter tf) {
    assert theSpecificDay.abuts(eventInterval)
            || theSpecificDay.overlaps(eventInterval) : "Event interval is not in the specified day!";

    this.summary = event.getSummary() != null ? event.getSummary().getValue() : null;
    this.description = event.getDescription() != null ? event.getDescription().getValue() : null;
    this.location = event.getLocation() != null ? event.getLocation().getValue() : null;

    boolean multi = false;
    if (eventInterval.getStart().isBefore(theSpecificDay.getStart())) {
        dayStart = theSpecificDay.getStart();
        multi = true;
    } else {
        dayStart = eventInterval.getStart();
    }

    if (event.getEndDate() == null) {
        dayEnd = dayStart;
    } else if (eventInterval.getEnd().isAfter(theSpecificDay.getEnd())) {
        dayEnd = theSpecificDay.getEnd();
        multi = true;
    } else {
        dayEnd = eventInterval.getEnd();
    }
    this.isMultiDay = multi;

    this.dateStartTime = tf.print(dayStart);
    this.startTime = tf.print(eventInterval.getStart());
    this.startDate = df.print(eventInterval.getStart());

    if (event.getEndDate() != null) {
        this.dateEndTime = tf.print(dayEnd);
        this.endTime = tf.print(eventInterval.getEnd());
        this.endDate = df.print(eventInterval.getEnd());
    } else {
        this.dateEndTime = null;
        this.endTime = null;
        this.endDate = null;
    }

    Interval dayEventInterval = new Interval(dayStart, dayEnd);
    this.isAllDay = dayEventInterval.equals(theSpecificDay);

}

From source file:org.kuali.kpme.tklm.time.clock.web.ClockAction.java

License:Educational Community License

public ActionForward validateNewTimeBlock(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from  w  w w.j  a va2s .com
    ClockActionForm caf = (ClockActionForm) form;
    String tbId = caf.getTbId();
    String[] assignments = caf.getNewAssignDesCol().split(SEPERATOR);
    String[] beginDates = caf.getNewBDCol().split(SEPERATOR);
    String[] beginTimes = caf.getNewBTCol().split(SEPERATOR);
    String[] endDates = caf.getNewEDCol().split(SEPERATOR);
    String[] endTimes = caf.getNewETCol().split(SEPERATOR);
    String[] hrs = caf.getNewHrsCol().split(SEPERATOR);

    List<Interval> newIntervals = new ArrayList<Interval>();
    JSONArray errorMsgList = new JSONArray();

    // validates that all fields are available
    if (assignments.length != beginDates.length || assignments.length != beginTimes.length
            || assignments.length != endDates.length || assignments.length != endTimes.length
            || assignments.length != hrs.length) {
        errorMsgList.add("All fields are required");
        caf.setOutputString(JSONValue.toJSONString(errorMsgList));
        return mapping.findForward("ws");
    }

    for (int i = 0; i < hrs.length; i++) {
        String index = String.valueOf(i + 1);

        // validate the hours field
        BigDecimal dc = new BigDecimal(hrs[i]);
        if (dc.compareTo(new BigDecimal("0")) == 0) {
            errorMsgList.add("The entered hours for entry " + index + " is not valid.");
            caf.setOutputString(JSONValue.toJSONString(errorMsgList));
            return mapping.findForward("ws");
        }

        // check if the begin / end time are valid
        // should not include time zone in consideration when conparing time intervals
        DateTime beginDateTime = TKUtils.convertDateStringToDateTimeWithoutZone(beginDates[i], beginTimes[i]);
        DateTime endDateTime = TKUtils.convertDateStringToDateTimeWithoutZone(endDates[i], endTimes[i]);
        if ((beginDateTime.compareTo(endDateTime) > 0 || endDateTime.compareTo(beginDateTime) < 0)) {
            errorMsgList.add("The time or date for entry " + index + " is not valid.");
            caf.setOutputString(JSONValue.toJSONString(errorMsgList));
            return mapping.findForward("ws");
        }

        // check if new time blocks overlap with existing time blocks
        Interval addedTimeblockInterval = new Interval(beginDateTime, endDateTime);
        newIntervals.add(addedTimeblockInterval);
        for (TimeBlock timeBlock : caf.getTimesheetDocument().getTimeBlocks()) {
            if (timeBlock.getTkTimeBlockId().equals(tbId)) { // ignore the original time block
                continue;
            }
            if (timeBlock.getHours().compareTo(BigDecimal.ZERO) == 0) { // ignore time blocks with zero hours
                continue;
            }
            DateTimeZone dateTimeZone = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
            DateTime timeBlockBeginTimestamp = new DateTime(timeBlock.getBeginTimestamp().getTime(),
                    dateTimeZone).withZone(TKUtils.getSystemDateTimeZone());
            DateTime timeBlockEndTimestamp = new DateTime(timeBlock.getEndTimestamp().getTime(), dateTimeZone)
                    .withZone(TKUtils.getSystemDateTimeZone());
            Interval timeBlockInterval = new Interval(timeBlockBeginTimestamp, timeBlockEndTimestamp);
            if (timeBlockInterval.overlaps(addedTimeblockInterval)) {
                errorMsgList.add("The time block you are trying to add for entry " + index
                        + " overlaps with an existing time block.");
                caf.setOutputString(JSONValue.toJSONString(errorMsgList));
                return mapping.findForward("ws");
            }
        }
    }
    // check if new time blocks overlap with each other
    if (newIntervals.size() > 1) {
        for (Interval intv1 : newIntervals) {
            for (Interval intv2 : newIntervals) {
                if (intv1.equals(intv2)) {
                    continue;
                }
                if (intv1.overlaps(intv2)) {
                    errorMsgList.add("There is time overlap between the entries.");
                    caf.setOutputString(JSONValue.toJSONString(errorMsgList));
                    return mapping.findForward("ws");
                }
            }
        }
    }

    caf.setOutputString(JSONValue.toJSONString(errorMsgList));
    return mapping.findForward("ws");
}