Example usage for org.joda.time Interval getEndMillis

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

Introduction

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

Prototype

public long getEndMillis() 

Source Link

Document

Gets the end of this time interval which is exclusive.

Usage

From source file:org.hawkular.metrics.api.jaxrs.influx.InfluxSeriesHandler.java

License:Apache License

private void select(AsyncResponse asyncResponse, String tenantId, SelectQueryContext selectQueryContext) {

    SelectQueryDefinitionsParser definitionsParser = new SelectQueryDefinitionsParser();
    parseTreeWalker.walk(definitionsParser, selectQueryContext);

    SelectQueryDefinitions queryDefinitions = definitionsParser.getSelectQueryDefinitions();

    try {//from w w  w . jav  a  2 s  .co m
        queryValidator.validateSelectQuery(queryDefinitions);
    } catch (IllegalQueryException e) {
        StringValue errMsg = new StringValue("Illegal query: " + e.getMessage());
        asyncResponse.resume(Response.status(Status.BAD_REQUEST).entity(errMsg).build());
        return;
    }

    String metric = queryDefinitions.getFromClause().getName(); // metric to query from backend
    BooleanExpression whereClause = queryDefinitions.getWhereClause();
    Interval timeInterval;
    if (whereClause == null) {
        timeInterval = new Interval(new Instant(0), Instant.now());
    } else {
        timeInterval = toIntervalTranslator.toInterval(whereClause);
    }
    if (timeInterval == null) {
        StringValue errMsg = new StringValue("Invalid time interval");
        asyncResponse.resume(Response.status(Status.BAD_REQUEST).entity(errMsg).build());
        return;
    }
    String columnName = getColumnName(queryDefinitions);

    ListenableFuture<Boolean> idExistsFuture = metricsService.idExists(metric);
    ListenableFuture<List<NumericData>> loadMetricsFuture = Futures.transform(idExistsFuture,
            (AsyncFunction<Boolean, List<NumericData>>) idExists -> {
                if (idExists != Boolean.TRUE) {
                    return Futures.immediateFuture(null);
                }
                return metricsService.findData(new NumericMetric(tenantId, new MetricId(metric)),
                        timeInterval.getStartMillis(), timeInterval.getEndMillis());
            });
    ListenableFuture<List<InfluxObject>> influxObjectTranslatorFuture = Futures.transform(loadMetricsFuture,
            (List<NumericData> metrics) -> {
                if (metrics == null) {
                    return null;
                }

                if (shouldApplyMapping(queryDefinitions)) {
                    GroupByClause groupByClause = queryDefinitions.getGroupByClause();
                    InfluxTimeUnit bucketSizeUnit = groupByClause.getBucketSizeUnit();
                    long bucketSizeSec = bucketSizeUnit.convertTo(SECONDS, groupByClause.getBucketSize());
                    AggregatedColumnDefinition aggregatedColumnDefinition = (AggregatedColumnDefinition) queryDefinitions
                            .getColumnDefinitions().get(0);
                    metrics = applyMapping(aggregatedColumnDefinition.getAggregationFunction(),
                            aggregatedColumnDefinition.getAggregationFunctionArguments(), metrics,
                            (int) bucketSizeSec, timeInterval.getStartMillis(), timeInterval.getEndMillis());
                }

                if (!queryDefinitions.isOrderDesc()) {
                    metrics = Lists.reverse(metrics);
                }

                if (queryDefinitions.getLimitClause() != null) {
                    metrics = metrics.subList(0, queryDefinitions.getLimitClause().getLimit());
                }

                List<InfluxObject> objects = new ArrayList<>(1);

                List<String> columns = new ArrayList<>(2);
                columns.add("time");
                columns.add(columnName);

                InfluxObject.Builder builder = new InfluxObject.Builder(metric, columns)
                        .withForeseenPoints(metrics.size());

                for (NumericData m : metrics) {
                    List<Object> data = new ArrayList<>();
                    data.add(m.getTimestamp());
                    data.add(m.getValue());
                    builder.addPoint(data);
                }

                objects.add(builder.createInfluxObject());

                return objects;
            });
    Futures.addCallback(influxObjectTranslatorFuture, new FutureCallback<List<InfluxObject>>() {
        @Override
        public void onSuccess(List<InfluxObject> objects) {
            if (objects == null) {
                StringValue val = new StringValue("Metric with id [" + metric + "] not found. ");
                asyncResponse.resume(Response.status(404).entity(val).build());
            } else {
                ResponseBuilder builder = Response.ok(objects);
                asyncResponse.resume(builder.build());
            }
        }

        @Override
        public void onFailure(Throwable t) {
            asyncResponse.resume(t);
        }
    });
}

From source file:org.jasig.portlet.calendar.adapter.CalDavCalendarAdapter.java

License:Apache License

protected final Set<VEvent> convertCalendarToEvents(net.fortuna.ical4j.model.Calendar calendar,
        Interval interval) throws CalendarException {

    Period period = new Period(new net.fortuna.ical4j.model.DateTime(interval.getStartMillis()),
            new net.fortuna.ical4j.model.DateTime(interval.getEndMillis()));

    Set<VEvent> events = new HashSet<VEvent>();

    // if the calendar is null, return empty set
    if (calendar == null) {
        log.info("calendar empty, returning empty set");
        return Collections.emptySet();
    }/*  w w  w.j a va  2  s . c  o  m*/

    // retrieve the list of events for this calendar within the
    // specified time period
    for (Iterator<Component> i = calendar.getComponents().iterator(); i.hasNext();) {
        Component component = i.next();
        if (component.getName().equals("VEVENT")) {
            VEvent event = (VEvent) component;
            if (log.isTraceEnabled()) {
                log.trace("processing event " + event.getSummary().getValue());
            }
            // calculate the recurrence set for this event
            // for the specified time period
            PeriodList periods = event.calculateRecurrenceSet(period);

            // add each recurrence instance to the event list
            for (Iterator<Period> iter = periods.iterator(); iter.hasNext();) {
                Period eventper = iter.next();

                PropertyList props = event.getProperties();

                // create a new property list, setting the date
                // information to this event period
                PropertyList newprops = new PropertyList();
                newprops.add(new DtStart(eventper.getStart()));
                newprops.add(new DtEnd(eventper.getEnd()));
                for (Iterator<Property> iter2 = props.iterator(); iter2.hasNext();) {
                    Property prop = iter2.next();

                    // only add non-date-related properties
                    if (!(prop instanceof DtStart) && !(prop instanceof DtEnd) && !(prop instanceof Duration)
                            && !(prop instanceof RRule))
                        newprops.add(prop);
                }

                // create the new event from our property list
                VEvent newevent = new VEvent(newprops);
                events.add(newevent);
                if (log.isTraceEnabled()) {
                    log.trace("added event " + newevent);
                }
            }
        }
    }

    return events;
}

From source file:org.jasig.portlet.calendar.processor.ICalendarContentProcessorImpl.java

License:Apache License

/**
 * //from  w ww . j  av a 2s  . c o  m
 * @param calendar
 * @param interval
 * @return
 * @throws CalendarException
 */
@SuppressWarnings("unchecked")
protected final Set<VEvent> convertCalendarToEvents(net.fortuna.ical4j.model.Calendar calendar,
        Interval interval) throws CalendarException {

    Period period = new Period(new net.fortuna.ical4j.model.DateTime(interval.getStartMillis()),
            new net.fortuna.ical4j.model.DateTime(interval.getEndMillis()));

    Set<VEvent> events = new HashSet<VEvent>();

    // if the calendar is null, return empty set
    if (calendar == null) {
        log.warn("calendar was empty, returning empty set");
        return Collections.emptySet();
    }

    // retrieve the list of events for this calendar within the
    // specified time period
    for (Iterator<Component> it = calendar.getComponents().iterator(); it.hasNext();) {
        /*
         * CAP-143:  Log a warning and ignore events that cannot be 
         * processed at this stage
         */
        Component component = it.next();
        try {
            if (component.getName().equals("VEVENT")) {
                VEvent event = (VEvent) component;
                if (log.isTraceEnabled()) {
                    log.trace("processing event " + event.getSummary());
                }
                // calculate the recurrence set for this event
                // for the specified time period
                PeriodList periods = event.calculateRecurrenceSet(period);

                // add each recurrence instance to the event list
                for (Iterator<Period> iter = periods.iterator(); iter.hasNext();) {
                    Period eventper = iter.next();
                    if (log.isDebugEnabled()) {
                        log.debug("Found time period staring at " + eventper.getStart().isUtc() + ", "
                                + eventper.getStart().getTimeZone() + ", " + event.getStartDate().getTimeZone()
                                + ", " + event.getStartDate().isUtc());
                    }

                    PropertyList props = event.getProperties();

                    // create a new property list, setting the date
                    // information to this event period
                    PropertyList newprops = new PropertyList();
                    DtStart start;
                    if (event.getStartDate().getDate() instanceof net.fortuna.ical4j.model.DateTime) {
                        start = new DtStart(new net.fortuna.ical4j.model.DateTime(eventper.getStart()));
                    } else {
                        start = new DtStart(new net.fortuna.ical4j.model.Date(eventper.getStart()));
                    }
                    newprops.add(start);
                    if (event.getEndDate() != null) {
                        DtEnd end;
                        if (event.getEndDate().getDate() instanceof net.fortuna.ical4j.model.DateTime) {
                            end = new DtEnd(new net.fortuna.ical4j.model.DateTime(eventper.getEnd()));
                        } else {
                            end = new DtEnd(new net.fortuna.ical4j.model.Date(eventper.getEnd()));
                        }
                        newprops.add(end);
                    }
                    for (Iterator<Property> iter2 = props.iterator(); iter2.hasNext();) {
                        Property prop = iter2.next();

                        // only add non-date-related properties
                        if (!(prop instanceof DtStart) && !(prop instanceof DtEnd)
                                && !(prop instanceof Duration) && !(prop instanceof RRule)
                                && !(prop instanceof RDate) && !(prop instanceof ExRule)
                                && !(prop instanceof ExDate)) {
                            newprops.add(prop);
                        }
                    }

                    // create the new event from our property list
                    VEvent newevent = new VEvent(newprops);
                    events.add(newevent);
                    log.trace("added event " + newevent);
                }
            }
        } catch (Exception e) {
            final String msg = "Failed to process the following ical4j component:  " + component;
            log.warn(msg, e);
        }
    }

    return events;
}

From source file:org.jevis.commons.dataprocessing.function.ImpulsFunction.java

License:Open Source License

@Override
public List<JEVisSample> getResult(Process mainTask) {
    List<JEVisSample> result = new ArrayList<>();

    if (mainTask.getSubProcesses().size() > 1) {
        System.out.println("Impuscleaner cannot work with more than one imput, using first only.");
    } else if (mainTask.getSubProcesses().size() < 1) {
        System.out.println("Impuscleaner, no input nothing to do");
    }/*  w  ww  . j a  v a2  s.  co  m*/

    List<JEVisSample> samples = mainTask.getSubProcesses().get(0).getResult();

    DateTime firstTS = DateTime.now();
    DateTime lastTS = DateTime.now();
    try {
        firstTS = samples.get(0).getTimestamp();
        lastTS = samples.get(samples.size()).getTimestamp();
    } catch (JEVisException ex) {
        Logger.getLogger(ImpulsFunction.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Interval> intervals = ProcessOptions.getIntervals(mainTask, firstTS, lastTS);

    int lastPos = 0;
    for (Interval interval : intervals) {
        List<JEVisSample> samplesInPeriod = new ArrayList<>();

        for (int i = lastPos; i < samples.size(); i++) {
            try {
                if (interval.contains(samples.get(i).getTimestamp())) {
                    //                        System.out.println("add sample: " + samples.get(i));
                    samplesInPeriod.add(samples.get(i));
                } else if (samples.get(i).getTimestamp().isAfter(interval.getEnd())) {
                    lastPos = i;
                    break;
                }
            } catch (JEVisException ex) {
                System.out.println("JEVisExeption while going trou sample: " + ex.getMessage());
            }
        }

        //TODO: thi sis an dummy for
        JEVisSample bestmatch = null;
        for (JEVisSample sample : samplesInPeriod) {

            long bestDiff = 99999999999999999l;
            try {
                long middelMili = ((interval.getEndMillis() - interval.getStartMillis()) / 2)
                        + interval.getStartMillis();
                long diff = Math.abs(sample.getTimestamp().getMillis() - middelMili);
                //                    System.out.println("Diff for: " + sample.getTimestamp() + "      -> " + diff);

                if (bestmatch != null) {
                    if (bestDiff < diff) {
                        bestDiff = diff;
                        bestmatch = sample;
                    }
                } else {
                    bestmatch = sample;
                    bestDiff = diff;
                }

            } catch (JEVisException ex) {
                System.out.println("JEVisExeption while going trou sample2: " + ex.getMessage());
            }
        }
        if (bestmatch != null) {
            System.out.println("Best match: " + bestmatch);
            result.add(bestmatch);
        }
    }

    return result;
}

From source file:org.jevis.commons.dataprocessing.function.ImpulsFunction.java

License:Open Source License

public List<JEVisSample> getResult(ProcessOptions options, List<List<JEVisSample>> allSamples) {
    List<JEVisSample> result = new ArrayList<>();
    for (List<JEVisSample> samples : allSamples) {

        try {//from  w ww  . ja v a  2s. c o  m
            _durations = ProcessOptions.buildIntervals(Period.minutes(15), _offset,
                    samples.get(0).getTimestamp(), samples.get(samples.size() - 1).getTimestamp());
        } catch (JEVisException ex) {
            Logger.getLogger(ImpulsFunction.class.getName()).log(Level.SEVERE, null, ex);
        }

        //Samples list is sorted by default
        int lastPos = 0;
        for (Interval interval : _durations) {
            //            System.out.println("Interval: " + interval);
            List<JEVisSample> samplesInPeriod = new ArrayList<>();

            for (int i = lastPos; i < samples.size(); i++) {
                try {
                    if (interval.contains(samples.get(i).getTimestamp())) {
                        //                        System.out.println("add sample: " + samples.get(i));
                        samplesInPeriod.add(samples.get(i));
                    } else if (samples.get(i).getTimestamp().isAfter(interval.getEnd())) {
                        lastPos = i;
                        break;
                    }
                } catch (JEVisException ex) {
                    System.out.println("JEVisExeption while going trou sample: " + ex.getMessage());
                }
            }

            //TODO: thi sis an dummy for
            JEVisSample bestmatch = null;
            for (JEVisSample sample : samplesInPeriod) {

                long bestDiff = 99999999999999999l;
                try {
                    long middelMili = ((interval.getEndMillis() - interval.getStartMillis()) / 2)
                            + interval.getStartMillis();
                    long diff = Math.abs(sample.getTimestamp().getMillis() - middelMili);
                    //                    System.out.println("Diff for: " + sample.getTimestamp() + "      -> " + diff);

                    if (bestmatch != null) {
                        if (bestDiff < diff) {
                            bestDiff = diff;
                            bestmatch = sample;
                        }
                    } else {
                        bestmatch = sample;
                        bestDiff = diff;
                    }

                } catch (JEVisException ex) {
                    System.out.println("JEVisExeption while going trou sample2: " + ex.getMessage());
                }
            }
            if (bestmatch != null) {
                System.out.println("Best match: " + bestmatch);
                result.add(bestmatch);
            }

        }

    }
    return result;
}

From source file:org.jevis.commons.dataprocessing.processor.ImpulsProcessor.java

License:Open Source License

@Override
public List<JEVisSample> getResult(Task mainTask) {
    List<JEVisSample> result = new ArrayList<>();

    if (mainTask.getSubTasks().size() > 1) {
        System.out.println("Impuscleaner cannot work with more than one imput, using first only.");
    } else if (mainTask.getSubTasks().size() < 1) {
        System.out.println("Impuscleaner, no input nothing to do");
    }/*from   w w w  .j a  v  a2s. c om*/

    List<JEVisSample> samples = mainTask.getSubTasks().get(0).getResult();

    DateTime firstTS = DateTime.now();
    DateTime lastTS = DateTime.now();
    try {
        firstTS = samples.get(0).getTimestamp();
        lastTS = samples.get(samples.size()).getTimestamp();
    } catch (JEVisException ex) {
        Logger.getLogger(ImpulsProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Interval> intervals = Options.getIntervals(mainTask, firstTS, lastTS);

    int lastPos = 0;
    for (Interval interval : intervals) {
        List<JEVisSample> samplesInPeriod = new ArrayList<>();

        for (int i = lastPos; i < samples.size(); i++) {
            try {
                if (interval.contains(samples.get(i).getTimestamp())) {
                    //                        System.out.println("add sample: " + samples.get(i));
                    samplesInPeriod.add(samples.get(i));
                } else if (samples.get(i).getTimestamp().isAfter(interval.getEnd())) {
                    lastPos = i;
                    break;
                }
            } catch (JEVisException ex) {
                System.out.println("JEVisExeption while going trou sample: " + ex.getMessage());
            }
        }

        //TODO: thi sis an dummy for 
        JEVisSample bestmatch = null;
        for (JEVisSample sample : samplesInPeriod) {

            long bestDiff = 99999999999999999l;
            try {
                long middelMili = ((interval.getEndMillis() - interval.getStartMillis()) / 2)
                        + interval.getStartMillis();
                long diff = Math.abs(sample.getTimestamp().getMillis() - middelMili);
                //                    System.out.println("Diff for: " + sample.getTimestamp() + "      -> " + diff);

                if (bestmatch != null) {
                    if (bestDiff < diff) {
                        bestDiff = diff;
                        bestmatch = sample;
                    }
                } else {
                    bestmatch = sample;
                    bestDiff = diff;
                }

            } catch (JEVisException ex) {
                System.out.println("JEVisExeption while going trou sample2: " + ex.getMessage());
            }
        }
        if (bestmatch != null) {
            System.out.println("Best match: " + bestmatch);
            result.add(bestmatch);
        }
    }

    return result;
}

From source file:org.jevis.commons.dataprocessing.processor.ImpulsProcessor.java

License:Open Source License

public List<JEVisSample> getResult(Options options, List<List<JEVisSample>> allSamples) {
    List<JEVisSample> result = new ArrayList<>();
    for (List<JEVisSample> samples : allSamples) {

        try {/*from   ww w  .  j ava 2 s  .  c o  m*/
            _durations = Options.buildIntervals(Period.minutes(15), _offset, samples.get(0).getTimestamp(),
                    samples.get(samples.size() - 1).getTimestamp());
        } catch (JEVisException ex) {
            Logger.getLogger(ImpulsProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }

        //Samples list is sorted by default
        int lastPos = 0;
        for (Interval interval : _durations) {
            //            System.out.println("Interval: " + interval);
            List<JEVisSample> samplesInPeriod = new ArrayList<>();

            for (int i = lastPos; i < samples.size(); i++) {
                try {
                    if (interval.contains(samples.get(i).getTimestamp())) {
                        //                        System.out.println("add sample: " + samples.get(i));
                        samplesInPeriod.add(samples.get(i));
                    } else if (samples.get(i).getTimestamp().isAfter(interval.getEnd())) {
                        lastPos = i;
                        break;
                    }
                } catch (JEVisException ex) {
                    System.out.println("JEVisExeption while going trou sample: " + ex.getMessage());
                }
            }

            //TODO: thi sis an dummy for 
            JEVisSample bestmatch = null;
            for (JEVisSample sample : samplesInPeriod) {

                long bestDiff = 99999999999999999l;
                try {
                    long middelMili = ((interval.getEndMillis() - interval.getStartMillis()) / 2)
                            + interval.getStartMillis();
                    long diff = Math.abs(sample.getTimestamp().getMillis() - middelMili);
                    //                    System.out.println("Diff for: " + sample.getTimestamp() + "      -> " + diff);

                    if (bestmatch != null) {
                        if (bestDiff < diff) {
                            bestDiff = diff;
                            bestmatch = sample;
                        }
                    } else {
                        bestmatch = sample;
                        bestDiff = diff;
                    }

                } catch (JEVisException ex) {
                    System.out.println("JEVisExeption while going trou sample2: " + ex.getMessage());
                }
            }
            if (bestmatch != null) {
                System.out.println("Best match: " + bestmatch);
                result.add(bestmatch);
            }

        }

    }
    return result;
}

From source file:org.kalypso.ogc.sensor.filter.filters.interval.IntervalIndex.java

License:Open Source License

public void insert(final IntervalData sourceData) {
    final Interval interval = sourceData.getInterval();
    m_sourceTree.insert(interval.getStartMillis(), interval.getEndMillis(), sourceData);
    m_itemCount++;//from w  ww .  j a  v  a2s  .  c o m
}

From source file:org.kalypso.ogc.sensor.filter.filters.interval.IntervalIndex.java

License:Open Source License

public IntervalData[] query(final Interval targetInterval) {
    // BUGFIX: SortedPackedIntervalRTree runs into endless loop if queried when empty
    if (m_itemCount == 0)
        return new IntervalData[0];

    final ItemCollector visitor = new ItemCollector();
    m_sourceTree.query(targetInterval.getStartMillis(), targetInterval.getEndMillis(), visitor);
    return visitor.getItems();
}

From source file:org.kuali.kpme.tklm.leave.block.service.LeaveBlockServiceImpl.java

License:Educational Community License

@Override
public void addLeaveBlocks(DateTime beginDate, DateTime endDate, CalendarEntry ce, String selectedEarnCode,
        BigDecimal hours, String description, Assignment selectedAssignment, String spanningWeeks,
        String leaveBlockType, String principalId) {

    DateTimeZone timezone = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
    DateTime calBeginDateTime = beginDate;
    DateTime calEndDateTime = endDate;/*w w w  .  j a v  a  2  s  .c  om*/

    if (ce != null) {
        calBeginDateTime = ce.getBeginPeriodLocalDateTime().toDateTime();
        calEndDateTime = ce.getEndPeriodLocalDateTime().toDateTime();
    } else {
        LOG.error("Calendar Entry parameter is null.");
        return;
        //          throw new RuntimeException("Calendar Entry parameter is null.");
    }

    Interval calendarInterval = new Interval(calBeginDateTime, calEndDateTime);

    // To create the correct interval by the given begin and end dates,
    // we need to plus one day on the end date to include that date
    List<Interval> leaveBlockIntervals = TKUtils.createDaySpan(beginDate.toLocalDate().toDateTimeAtStartOfDay(),
            endDate.toLocalDate().toDateTimeAtStartOfDay().plusDays(1), TKUtils.getSystemDateTimeZone());

    // need to use beginDate and endDate of the calendar to find all leaveBlocks since LeaveCalendarDocument Id is not always available
    List<LeaveBlock> currentLeaveBlocks = getLeaveBlocks(principalId, calBeginDateTime.toLocalDate(),
            calEndDateTime.toLocalDate());

    // use the current calendar's begin and end date to figure out if this pay period has a leaveDocument
    LeaveCalendarDocumentHeader lcdh = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
            .getDocumentHeader(principalId, ce.getBeginPeriodLocalDateTime().toDateTime(),
                    ce.getEndPeriodLocalDateTime().toDateTime());
    String docId = lcdh == null ? null : lcdh.getDocumentId();

    // TODO: need to integrate with the scheduled timeoff.
    Interval firstDay = null;
    DateTime currentDate = beginDate;
    for (Interval leaveBlockInt : leaveBlockIntervals) {
        if (calendarInterval.contains(leaveBlockInt)) {
            // KPME-1446 if "Include weekends" check box is checked, don't add Sat and Sun to the leaveblock list
            if (StringUtils.isEmpty(spanningWeeks)
                    && (leaveBlockInt.getStart().getDayOfWeek() == DateTimeConstants.SATURDAY
                            || leaveBlockInt.getStart().getDayOfWeek() == DateTimeConstants.SUNDAY)) {

                // do nothing
            } else {

                // Currently, we store the accrual category value in the leave code table, but store accrual category id in the leaveBlock.
                // That's why there is a two step server call to get the id. This might be changed in the future.

                CalendarEntry calendarEntry = HrServiceLocator.getCalendarEntryService()
                        .getCurrentCalendarEntryByCalendarId(ce.getHrCalendarId(),
                                new LocalDate().toDateTimeAtStartOfDay());
                DateTime leaveBlockDate = leaveBlockInt.getStart();

                String requestStatus = HrConstants.REQUEST_STATUS.USAGE;
                if (LmServiceLocator.getLeaveApprovalService().isActiveAssignmentFoundOnJobFlsaStatus(
                        principalId, HrConstants.FLSA_STATUS_NON_EXEMPT, true)) {
                    TimesheetDocumentHeader tdh = TkServiceLocator.getTimesheetDocumentHeaderService()
                            .getDocumentHeaderForDate(principalId, leaveBlockDate);
                    if (tdh != null) {
                        if (DateUtils.isSameDay(leaveBlockDate.toDate(), tdh.getEndDate())
                                || leaveBlockDate.isAfter(tdh.getEndDateTime())) {
                            requestStatus = HrConstants.REQUEST_STATUS.PLANNED;
                        }
                    } else {
                        requestStatus = HrConstants.REQUEST_STATUS.PLANNED;
                    }
                } else {
                    if (DateUtils.isSameDay(leaveBlockDate.toDate(), calendarEntry.getEndPeriodDateTime())
                            || leaveBlockDate.isAfter(calendarEntry.getEndPeriodFullDateTime())) {
                        requestStatus = HrConstants.REQUEST_STATUS.PLANNED;
                    }
                }

                EarnCode earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(selectedEarnCode,
                        ce.getEndPeriodLocalDateTime().toDateTime().toLocalDate());

                if (earnCodeObj != null
                        && earnCodeObj.getRecordMethod().equals(HrConstants.RECORD_METHOD.TIME)) {
                    if (firstDay != null) {
                        if (!leaveBlockInt.contains(endDate)) {
                            currentDate = leaveBlockInt.getStart();
                        } else if ((leaveBlockInt.getStartMillis() - endDate.getMillis()) != 0) {

                            hours = TKUtils.getHoursBetween(leaveBlockInt.getStartMillis(),
                                    endDate.getMillis());
                            hours = negateHoursIfNecessary(leaveBlockType, hours);

                            LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(),
                                    docId, principalId, selectedEarnCode, hours, description,
                                    earnCodeObj.getAccrualCategory(), selectedAssignment, requestStatus,
                                    leaveBlockType, leaveBlockInt.getStart(), endDate);

                            if (!currentLeaveBlocks.contains(leaveBlock)) {
                                currentLeaveBlocks.add(leaveBlock);
                            }
                            break;
                        }
                    }
                    if (leaveBlockInt.contains(currentDate)) {

                        firstDay = leaveBlockInt;

                        if (leaveBlockInt.contains(endDate)
                                || (endDate.getMillis() == leaveBlockInt.getEnd().getMillis())) {

                            hours = TKUtils.getHoursBetween(currentDate.getMillis(), endDate.getMillis());
                            hours = negateHoursIfNecessary(leaveBlockType, hours);

                            LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(),
                                    docId, principalId, selectedEarnCode, hours, description,
                                    earnCodeObj.getAccrualCategory(), selectedAssignment, requestStatus,
                                    leaveBlockType, currentDate, endDate);

                            if (!currentLeaveBlocks.contains(leaveBlock)) {
                                currentLeaveBlocks.add(leaveBlock);
                            }

                            break;

                        } else {
                            // create a leave block that wraps the 24 hr day
                            hours = TKUtils.getHoursBetween(currentDate.getMillis(), firstDay.getEndMillis());
                            hours = negateHoursIfNecessary(leaveBlockType, hours);

                            LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(),
                                    docId, principalId, selectedEarnCode, hours, description,
                                    earnCodeObj.getAccrualCategory(), selectedAssignment, requestStatus,
                                    leaveBlockType, currentDate, firstDay.getEnd());

                            if (!currentLeaveBlocks.contains(leaveBlock)) {
                                currentLeaveBlocks.add(leaveBlock);
                            }

                        }
                    }
                } else {
                    hours = negateHoursIfNecessary(leaveBlockType, hours);
                    LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(), docId,
                            principalId, selectedEarnCode, hours, description, earnCodeObj.getAccrualCategory(),
                            selectedAssignment, requestStatus, leaveBlockType, null, null);
                    if (!currentLeaveBlocks.contains(leaveBlock)) {
                        currentLeaveBlocks.add(leaveBlock);
                    }
                }
            }
        }
    }
    saveLeaveBlocks(currentLeaveBlocks);
}