Example usage for org.joda.time Interval getStart

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

Introduction

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

Prototype

public DateTime getStart() 

Source Link

Document

Gets the start of this time interval, which is inclusive, as a DateTime.

Usage

From source file:org.jasig.portlet.calendar.url.CalendarkeyUrlCreatorImpl.java

License:Apache License

public String constructUrl(CalendarConfiguration calendarListing, Interval interval, PortletRequest request) {
    String baseUrl = calendarListing.getCalendarDefinition().getParameters().get("baseUrl");
    StringBuilder finalUrl = new StringBuilder();
    finalUrl.append(baseUrl);//  w w  w .  j  av a  2s . c  om
    if (!baseUrl.endsWith("/")) {
        finalUrl.append("/");
    }
    String username = request.getRemoteUser();
    if (null == username || "".equals(username)) {
        throw new CalendarException("user not logged in");
    }
    finalUrl.append(username);
    finalUrl.append("/");

    finalUrl.append(formatter.print(interval.getStart()));
    finalUrl.append("/");
    finalUrl.append(formatter.print(interval.getEnd()));
    return finalUrl.toString();
}

From source file:org.jasig.portlet.calendar.url.StringTemplateUrlCreatorImpl.java

License:Apache License

/**
 *
 * @param configuration/*from  w  w w.  j  av  a 2  s. c om*/
 * @param interval
 * @param username
 * @return
 */
public String constructUrlInternal(CalendarConfiguration configuration, Interval interval, String username) {

    // get the template url from the calendar configuration
    String url = (String) configuration.getCalendarDefinition().getParameters().get("url");

    try {

        // replace the username in the url
        url = url.replace(USERNAME_TOKEN, URLEncoder.encode(username, URL_ENCODING));

        // replace the start and end dates in the url, using the configured date format
        if (url.contains(START_DATE_TOKEN) || url.contains(END_DATE_TOKEN)) {

            // get the configured date format from the calendar configuration, or if none is configured, use the
            // default date format
            String urlDateFormat = (String) configuration.getCalendarDefinition().getParameters()
                    .get("urlDateFormat");
            if (urlDateFormat == null) {
                urlDateFormat = DEFAULT_DATE_FORMAT;
            }

            // replace the start date in the url
            String startString = URLEncoder.encode(getDateFormatter(urlDateFormat).print(interval.getStart()),
                    URL_ENCODING);
            url = url.replace(START_DATE_TOKEN, startString);

            // replace the end date in the url
            String endString = URLEncoder.encode(getDateFormatter(urlDateFormat).print(interval.getEnd()),
                    URL_ENCODING);
            url = url.replace(END_DATE_TOKEN, endString);

        }

    } catch (UnsupportedEncodingException e) {
        log.error(e);
    }

    return url;
}

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

License:Open Source License

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

    List<List<JEVisSample>> allSamples = new ArrayList<>();
    for (Process task : mainTask.getSubProcesses()) {
        allSamples.add(task.getResult());
        System.out.println("Add input result: " + allSamples.size());
    }//from w ww .j av  a  2  s.  c  o m

    List<DateTime> allTimestamps = getAllTimestamps(allSamples);
    if (allTimestamps.isEmpty()) {
        return result;
    }
    List<Interval> intervals = ProcessOptions.getIntervals(mainTask, allTimestamps.get(0),
            allTimestamps.get(allTimestamps.size() - 1));

    System.out.println("intervals: " + intervals.size());

    int lastPos = 0;
    for (Interval interval : intervals) {
        List<JEVisSample> samplesInPeriod = new ArrayList<>();
        System.out.println("interval: " + interval);

        for (List<JEVisSample> samples : allSamples) {
            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());
                }
            }

            double sum = 0;
            for (JEVisSample sample : samplesInPeriod) {
                try {
                    sum += sample.getValueAsDouble();
                } catch (JEVisException ex) {
                    Logger.getLogger(AggrigatorFunction.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            JEVisSample resultSum = new VirtuelSample(interval.getStart(), sum, mainTask.getJEVisDataSource(),
                    new VirtualAttribute(null));
            result.add(resultSum);
            try {
                System.out.println(
                        "resultSum: " + resultSum.getTimestamp() + "  " + resultSum.getValueAsDouble());
            } catch (JEVisException ex) {
                Logger.getLogger(AggrigatorFunction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    return result;
}

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

License:Open Source License

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

    ///*from   w  w  w. j  a v  a  2  s. c  o m*/
    //       
    //        List<Interval> durations = ProcessController.buildIntervals(Period.days(1), ProcessController.getOffset(), samples.get(0).getTimestamp(), samples.get(samples.size() - 1).getTimestamp());
    List<Map<DateTime, JEVisSample>> sampleMaps = new ArrayList<>();
    List<List<JEVisSample>> allSamples = new ArrayList<>();
    for (Task task : mainTask.getSubTasks()) {
        allSamples.add(task.getResult());
        System.out.println("Add input result: " + allSamples.size());
    }

    List<DateTime> allTimestamps = getAllTimestamps(allSamples);
    List<Interval> intervals = Options.getIntervals(mainTask, allTimestamps.get(0),
            allTimestamps.get(allTimestamps.size() - 1));

    System.out.println("intervals: " + intervals.size());

    int lastPos = 0;
    for (Interval interval : intervals) {
        List<JEVisSample> samplesInPeriod = new ArrayList<>();
        System.out.println("interval: " + interval);

        for (List<JEVisSample> samples : allSamples) {
            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());
                }
            }

            double sum = 0;
            for (JEVisSample sample : samplesInPeriod) {
                try {
                    sum += sample.getValueAsDouble();
                } catch (JEVisException ex) {
                    Logger.getLogger(AggrigatorProcessor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            JEVisSample resultSum = new VirtuelSample(interval.getStart(), sum, mainTask.getJEVisDataSource(),
                    new VirtualAttribute(null));
            result.add(resultSum);
            try {
                System.out.println(
                        "resultSum: " + resultSum.getTimestamp() + "  " + resultSum.getValueAsDouble());
            } catch (JEVisException ex) {
                Logger.getLogger(AggrigatorProcessor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    return result;
}

From source file:org.kalypso.ui.rrm.internal.calccase.MultiCatchmentModelRunner.java

License:Open Source License

/**
 * This function runs the linear sum generator.
 * //from ww w . j  a v  a 2  s . co m
 * @param prefix
 *          This prefix is used when writing the timeseries.
 * @param simulation
 *          The simulation.
 * @param control
 *          The na control.
 * @param model
 *          The na model.
 * @param generator
 *          The rainfall generator.
 * @param targetLink
 *          The target link.
 * @param parameterType
 *          The parameter type.
 * @param hash
 *          The hash.
 * @param monitor
 *          A progress monitor.
 */
private void runGenerator(final String prefix, final RrmSimulation simulation, final NAControl control,
        final NaModell model, final ILinearSumGenerator generator, final QName targetLink,
        final String parameterType, final CatchmentTimeseriesHash hash, final IProgressMonitor monitor)
        throws Exception {
    try {
        /* Monitor. */
        monitor.beginTask(
                String.format(Messages.getString("MultiCatchmentModelRunner_7"), generator.getDescription()), //$NON-NLS-1$
                1000);
        monitor.subTask(Messages.getString("MultiCatchmentModelRunner_8")); //$NON-NLS-1$

        /* This object can calculate some values. */
        final LinearSumCatchmentModelInfo linearInfo = new LinearSumCatchmentModelInfo(simulation, control,
                model, generator, targetLink, parameterType);

        /* Get the timestep and timestamp. */
        final Period timestep = linearInfo.getTimestep();
        final LocalTime timestamp = linearInfo.getTimestamp();

        /* HINT: The range is the adjusted simulation range. */
        final DateRange simulationRange = linearInfo.getSimulationRange();

        /* Intersect adjusted simulation range with validity range of generator. */
        final Interval simulationInterval = new Interval(new DateTime(simulationRange.getFrom()),
                new DateTime(simulationRange.getTo()));

        /* Calculate range of current generator. */
        final Interval validityInterval = new Interval(new DateTime(generator.getValidFrom()),
                new DateTime(generator.getValidTo()));

        /* Intersect complete simulation with this generator, only this range will be calculated. */
        final Interval interval = validityInterval.overlap(simulationInterval);

        // FIXME: The intersected interval does now NOT cover the extended range (3 steps before, 1 step after).
        // So the complete result does NOT cover the extended range.

        final DateRange range = new DateRange(interval.getStart().toDate(), interval.getEnd().toDate());

        /* The catchment model runner should be executed with this generic info. */
        final ICatchmentModelInfo genericInfo = new GenericCatchmentModelInfo(simulation, control, model,
                generator, targetLink, parameterType, timestep, timestamp, range, range);

        /* Create the linear sum catchment model runner. */
        final LinearSumCatchmentModelRunner runner = new LinearSumCatchmentModelRunner(prefix);

        /* Calculate the catchment model. */
        runner.executeCatchmentModel(genericInfo, new SubProgressMonitor(monitor, 500));

        /* Get the catchments. */
        final IFeatureBindingCollection<Catchment> catchments = model.getCatchments();
        for (final Catchment catchment : catchments) {
            /* The feature id of the catchment must be unique. */
            final String id = catchment.getId();

            /* Get the link of the timeseries. */
            ZmlLink link = null;
            if (parameterType.equals(ITimeseriesConstants.TYPE_RAINFALL))
                link = catchment.getPrecipitationLink();
            else if (parameterType.equals(ITimeseriesConstants.TYPE_EVAPORATION_LAND_BASED))
                link = catchment.getEvaporationLink();
            else if (parameterType.equals(ITimeseriesConstants.TYPE_MEAN_TEMPERATURE))
                link = catchment.getTemperatureLink();
            else
                throw new IllegalArgumentException(Messages.getString("MultiCatchmentModelRunner_9")); //$NON-NLS-1$

            /* Store the timeseries link. */
            hash.put(id, link.getTimeseriesLink());
        }

        /* Monitor. */
        monitor.worked(500);
    } finally {
        /* Monitor. */
        monitor.done();
    }
}

From source file:org.kalypso.ui.rrm.internal.timeseries.view.actions.MergeTimeseriesOperation.java

License:Open Source License

private void validateTimeseries(final DateRange baseRange, final Period baseTimestep,
        final DateRange importRange, final Period importTimestep) throws CoreException {
    /* The timesteps must be equal. */
    final Minutes baseMinutes = baseTimestep.toStandardMinutes();
    final Minutes importMinutes = importTimestep.toStandardMinutes();
    if (baseMinutes.getMinutes() != importMinutes.getMinutes())
        throw new CoreException(new Status(IStatus.ERROR, KalypsoUIRRMPlugin.getID(),
                String.format(Messages.getString("MergeTimeseriesOperation.0"), baseTimestep.toString(), //$NON-NLS-1$
                        importTimestep.toString())));

    /* Create the intervals. */
    final Interval baseInterval = new Interval(new DateTime(baseRange.getFrom()),
            new DateTime(baseRange.getTo()));
    final Interval importInterval = new Interval(new DateTime(importRange.getFrom()),
            new DateTime(importRange.getTo()));

    /* Is the base range before the import range? */
    /* Only a gap with one timestep is allowed. */
    if (baseInterval.isBefore(importInterval)) {
        final DateTime baseEnd = baseInterval.getEnd();
        final DateTime importStart = importInterval.getStart();

        final Period gap = new Period(baseEnd, importStart);
        final Minutes gapMinutes = gap.toStandardMinutes();
        if (gapMinutes.getMinutes() > 0 && baseMinutes.getMinutes() != gapMinutes.getMinutes())
            throw new CoreException(new Status(IStatus.ERROR, KalypsoUIRRMPlugin.getID(),
                    String.format(Messages.getString("MergeTimeseriesOperation.1"), baseMinutes.toString(), //$NON-NLS-1$
                            gapMinutes.toString())));
    }//  w  w  w. j  av  a 2 s .  c o m

    /* Is the base range after the import range? */
    /* Only a gap with one timestep is allowed. */
    if (baseInterval.isAfter(importInterval)) {
        final DateTime importEnd = importInterval.getEnd();
        final DateTime baseStart = baseInterval.getStart();

        final Period gap = new Period(importEnd, baseStart);
        final Minutes gapMinutes = gap.toStandardMinutes();
        if (gapMinutes.getMinutes() > 0 && baseMinutes.getMinutes() != gapMinutes.getMinutes())
            throw new CoreException(new Status(IStatus.ERROR, KalypsoUIRRMPlugin.getID(),
                    String.format(Messages.getString("MergeTimeseriesOperation.1"), baseMinutes.toString(), //$NON-NLS-1$
                            gapMinutes.toString())));
    }

    /* Here the intervals touch or overlap. */
}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.KPMEAccrualCategoryBucket.java

License:Educational Community License

private void adjustAsOfDates(CalendarEntry calendarEntry, List<CalendarEntry> calendarEntries) {

    LocalDate newAsOfDate = null;

    //determine if the bucket is being switched to the current leave year
    //also compute max end date to determine if the bucket is being switched to a future leave year. ( could use leave plan service's getRollOverDate )
    boolean switchingToCurrentLeaveYear = false;
    LocalDate maxEndDate = LocalDate.now();
    for (CalendarEntry entry : calendarEntries) {
        if (entry.getHrCalendarEntryId().equals(calendarEntry.getHrCalendarEntryId())
                && entry.getHrCalendarId().equals(calendarEntry.getHrCalendarId())) {
            switchingToCurrentLeaveYear = true;
        }//from   w ww.  j a  v a 2s .co m
        if (entry.getEndPeriodDate().after(maxEndDate.toDate()))
            maxEndDate = LocalDate.fromDateFields(entry.getEndPeriodDate());
    }

    if (switchingToCurrentLeaveYear) {
        Interval otherCalendarInterval = new Interval(calendarEntry.getBeginPeriodDate().getTime(),
                calendarEntry.getEndPeriodDate().getTime());
        if (otherCalendarInterval.contains(LocalDate.now().toDate().getTime())) {
            //switching to the present calendar.
            newAsOfDate = LocalDate.now();
        } else if (otherCalendarInterval.getEnd().isBefore(LocalDate.now().toDate().getTime())) {
            //switching to a historical calendar in the current leave plan year, use calendar end date
            newAsOfDate = otherCalendarInterval.getEnd().toLocalDate().minusDays(1);
        } else {
            //switching to a future/planning calendar in the current leave plan year, use calendar start date.
            newAsOfDate = otherCalendarInterval.getStart().toLocalDate().minusDays(1);
        }
    } else if (calendarEntry.getEndPeriodDate().after(maxEndDate.toDate())) {
        //switching to a leave year beyond the current leave year, same as future/planning calendar in current leave year.
        newAsOfDate = LocalDate.fromDateFields(calendarEntry.getBeginPeriodDate()).minusDays(1);
    } else {
        //switching to a calendar period within a past leave calendar year.
        DateTime otherCalendarRolloverDate = HrServiceLocator.getLeavePlanService().getRolloverDayOfLeavePlan(
                principalCalendar.getLeavePlan(), LocalDate.fromDateFields(calendarEntry.getEndPeriodDate()));
        //for past leave calendar years, regardless of calendar period, we require values as of the rollover day.
        newAsOfDate = LocalDate.fromDateFields(otherCalendarRolloverDate.toDate()).minusDays(1);
    }

    //update asOfDates and calendar period end point dates for all leave balance objects
    for (Entry<String, List<LeaveBalance>> entry : leaveBalances.entrySet()) {
        for (LeaveBalance leaveBalance : entry.getValue()) {
            leaveBalance.asOfDate = newAsOfDate;
            leaveBalance.calendarPeriodBeginDate = LocalDate.fromDateFields(calendarEntry.getBeginPeriodDate());
            leaveBalance.calendarPeriodEndDate = LocalDate.fromDateFields(calendarEntry.getEndPeriodDate());
        }
    }

    //reset this buckets asOfDate
    asOfDate = newAsOfDate;

}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxBalanceServiceImpl.java

License:Educational Community License

protected CalendarBlockContract retreivePreviousInfraction(Set<LeaveBlock> eligibleLeaveBlocks, LeaveBlock lb,
        Interval leavePeriodInterval, Interval yearEndPeriodInterval, Interval thisEntryInterval,
        AccrualCategoryRule asOfLeaveDateRule) {
    CalendarBlockContract tempLB = null;
    for (LeaveBlock block : eligibleLeaveBlocks) {
        AccrualCategoryRule blockRule = HrServiceLocator.getAccrualCategoryRuleService()
                .getAccrualCategoryRule(block.getAccrualCategoryRuleId());
        if (StringUtils.equals(asOfLeaveDateRule.getLmAccrualCategoryRuleId(),
                blockRule.getLmAccrualCategoryRuleId())) {
            if ((StringUtils.equals(asOfLeaveDateRule.getMaxBalanceActionFrequency(),
                    HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND)
                    && StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                            HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND))
                    || (leavePeriodInterval != null && leavePeriodInterval.contains(lb.getLeaveDate().getTime())
                            && leavePeriodInterval.contains(block.getLeaveDate().getTime()))
                    || (leavePeriodInterval == null
                            && thisEntryInterval.contains(block.getLeaveDate().getTime())
                            && thisEntryInterval.contains(lb.getLeaveDate().getTime()))
                    || (StringUtils.equals(asOfLeaveDateRule.getMaxBalanceActionFrequency(),
                            HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                            && StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                                    HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                            && (yearEndPeriodInterval == null
                                    || (yearEndPeriodInterval.contains(block.getLeaveDate().getTime())
                                            && yearEndPeriodInterval.contains(lb.getLeaveDate().getTime())))
                            //year end we replace if the two infractions are not within the same leave period.
                            //if yearEndPeriodInterval != null, the conditional for leave approve should have already evaluated to true.
                            //i.e. yearEndPeriodInterval != null will never be evaluated.
                            || block.getLeaveDate().before(thisEntryInterval.getStart().toDate()))) {
                tempLB = block;//from  w ww.  ja v  a 2 s . c  om
                break;
            }
        } else if (StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND)
                //always supersede on-demand action frequencies
                || (StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                        HrConstants.MAX_BAL_ACTION_FREQ.LEAVE_APPROVE)
                        && ((leavePeriodInterval != null
                                && leavePeriodInterval.contains(block.getLeaveDate().getTime())
                                && leavePeriodInterval.contains(lb.getLeaveDate().getTime()))
                                || (leavePeriodInterval == null
                                        && thisEntryInterval.contains(block.getLeaveDate().getTime())
                                        && thisEntryInterval.contains(lb.getLeaveDate().getTime()))))
                //leave approve is replaced only if the replacement lies within the same leave period.
                || (StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                        HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                        && (yearEndPeriodInterval == null
                                || (yearEndPeriodInterval.contains(block.getLeaveDate().getTime())
                                        && yearEndPeriodInterval.contains(lb.getLeaveDate().getTime()))))
                //year end is superseded only if the new rule goes into effect before the current leave plan calendar year end date.
                || block.getLeaveDate().before(thisEntryInterval.getStart().toDate())) {
            tempLB = block;
            break;
        }
    }
    return tempLB;
}

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

License:Educational Community License

/**
 * Provides the option to refer to the time zone adjusted time for the current
 * user./*  w ww  . j  a  v a 2s .  co m*/
 * @param LeaveBlocks
 * @param leaveCalendarEntry
 * @param leaveCalendar
 */
public LeaveBlockAggregate(List<LeaveBlock> leaveBlocks, CalendarEntry leaveCalendarEntry,
        LeaveCalendar leaveCalendar) {
    this.leaveCalendarEntry = leaveCalendarEntry;
    this.leaveCalendar = leaveCalendar;
    List<Interval> dayIntervals = TKUtils.getDaySpanForCalendarEntry(leaveCalendarEntry);
    for (Interval dayInt : dayIntervals) {
        List<LeaveBlock> dayLeaveBlocks = new ArrayList<LeaveBlock>();
        for (LeaveBlock leaveBlock : leaveBlocks) {
            LocalDate localDate = leaveBlock.getLeaveLocalDate();
            LocalDate dayIntBegin = dayInt.getStart().toLocalDate();
            if (localDate.equals(dayIntBegin)) {
                dayLeaveBlocks.add(leaveBlock);
            }
        }
        dayLeaveBlockList.add(dayLeaveBlocks);
    }
}

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

License:Educational Community License

public LeaveBlockAggregate(List<LeaveBlock> leaveBlocks, CalendarEntry leaveCalendarEntry) {
    this.leaveCalendarEntry = leaveCalendarEntry;
    List<Interval> dayIntervals = TKUtils.getDaySpanForCalendarEntry(leaveCalendarEntry);
    for (Interval dayInt : dayIntervals) {
        List<LeaveBlock> dayLeaveBlocks = new ArrayList<LeaveBlock>();
        for (LeaveBlock leaveBlock : leaveBlocks) {
            LocalDate localDate = leaveBlock.getLeaveLocalDate();
            LocalDate dayIntBegin = dayInt.getStart().toLocalDate();
            if (localDate.equals(dayIntBegin)) {
                dayLeaveBlocks.add(leaveBlock);
            }//from w ww.j  a v  a2  s.  co  m
        }
        dayLeaveBlockList.add(dayLeaveBlocks);
    }
}