Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

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

Prototype

public Duration(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:org.cook_e.cook_e.CookActivity.java

License:Open Source License

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Step step;//from   w w w .jav  a  2s. c  o  m
    switch (item.getItemId()) {
    case R.id.previous:
        // User chose the "previous" item,
        step = mSchedule.getPrevStep();
        if (step != null) {
            setCurrentStep(step, mSchedule.getCurrentStepRecipe(), false);
        }
        return true;

    case R.id.next:
        // User chose the "next" item,
        boolean nextIsNew = mSchedule.getCurrStepIndex() == mSchedule.getMaxVisitedStepIndex();
        Step originalStep = mSchedule.getCurrStep();
        Recipe originalRecipe = mSchedule.getCurrentStepRecipe();
        step = mSchedule.getNextStep();
        Recipe recipe = mSchedule.getCurrentStepRecipe();

        if (nextIsNew) {
            // updates learner
            Instant mEndInstant = new Instant();
            Duration stepDuration = new Duration(mStartInstant, mEndInstant);
            mStartInstant = mEndInstant;
            if (!originalStep.isSimultaneous()) {
                try {
                    mTimeLearner.learnStep(originalRecipe, originalStep, stepDuration);
                } catch (SQLException e) {
                    new Builder(this).setTitle(R.string.failed_to_learn_time)
                            .setMessage(e.getLocalizedMessage()).show();
                }
            }
        }

        if (step != null) {
            setCurrentStep(step, recipe, nextIsNew);
        } else if (mActiveSimultaneousSteps != 0) {
            // Explain to the user why they cannot advance
            new AlertDialog.Builder(this).setTitle(R.string.dialog_title_waiting_for_step)
                    .setMessage(R.string.dialog_waiting_for_step).show();
        } else {
            // The final step has been completed!
            Instant mLastInstant = new Instant();
            Duration cookDuration = new Duration(mFirstInstant, mLastInstant);
            String exitMessage = "Unoptimized: " + mSchedule.mOriginalEstimatedTime + " min." + "\nOptimized: "
                    + mSchedule.mOptimizedEstimatedTime + " min." + "\n\nActual: "
                    + cookDuration.getStandardMinutes() + " min.";
            new AlertDialog.Builder(this).setTitle(R.string.meal_completed).setMessage(exitMessage)
                    .setCancelable(false).setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).show();
        }
        return true;

    default:
        // If we got here, the user's action was not recognized.
        // Invoke the superclass to handle it.
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.emonocot.harvest.common.JobStatusNotifierImpl.java

License:Open Source License

public final void notify(final JobExecutionInfo jobExecutionInfo) {
    logger.debug("In notify " + jobExecutionInfo.getId());

    Resource resource = service.find(jobExecutionInfo.getResourceIdentifier(), "job-with-source");
    if (resource != null) {

        resource.setDuration(new Duration(new DateTime(0), jobExecutionInfo.getDuration()));
        resource.setExitCode(jobExecutionInfo.getExitCode());
        resource.setExitDescription(jobExecutionInfo.getExitDescription());
        if (jobExecutionInfo.getJobInstance() != null) {
            resource.setJobInstance(jobExecutionInfo.getJobInstance());
        }/*from w w  w.j  a v  a  2s  .  c om*/
        resource.setJobId(jobExecutionInfo.getId());
        resource.setBaseUrl(jobExecutionInfo.getBaseUrl());
        resource.setResource(jobExecutionInfo.getResource());
        resource.setStartTime(jobExecutionInfo.getStartTime());
        resource.setStatus(jobExecutionInfo.getStatus());
        resource.setProcessSkip(jobExecutionInfo.getProcessSkip());
        resource.setRecordsRead(jobExecutionInfo.getRecordsRead());
        resource.setReadSkip(jobExecutionInfo.getReadSkip());
        resource.setWriteSkip(jobExecutionInfo.getWriteSkip());
        resource.setWritten(jobExecutionInfo.getWritten());
        switch (resource.getStatus()) {
        case COMPLETED:
            if (resource.getExitCode().equals("COMPLETED")) {
                resource.setLastHarvestedJobId(jobExecutionInfo.getId());
                resource.setLastHarvested(jobExecutionInfo.getStartTime());
                resource.updateNextAvailableDate();
            } else if (resource.getExitCode().equals("NOT_MODIFIED")) {
                // it is NOT_MODIFIED, so leave the job id as it is, because
                // we don't have any new annotations
                resource.setLastHarvested(jobExecutionInfo.getStartTime());
                resource.updateNextAvailableDate();
            } else if (resource.getExitCode().equals("FAILED")) {
                // The Job failed in a (slightly) controlled manner, but it still failed
                resource.setNextAvailableDate(null);
                resource.setLastHarvestedJobId(jobExecutionInfo.getId());
            }

            break;
        case FAILED:
            // It completed on its own, but some part failed
        case ABANDONED:
            // It has been stopped and abandoned manually, and will not be restarted
            resource.setNextAvailableDate(null);
            resource.setJobId(jobExecutionInfo.getId());
            break;
        case STOPPED:
        default:
        }
        service.saveOrUpdate(resource);
        solrIndexingListener.indexObject(resource);
    }
}

From source file:org.fenixedu.bennu.core.filters.ProfilingFilter.java

License:Open Source License

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        final long start = System.currentTimeMillis();
        try {//w  w  w.  j  ava  2 s .  co m
            chain.doFilter(request, response);
        } finally {
            log(((HttpServletRequest) request).getRequestURI(),
                    new Duration(start, System.currentTimeMillis()));
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.georchestra.analytics.StatisticsController.java

License:Open Source License

/**
 * Calculates the appropriate granularity given the begin date and the end date.
 *
 * @param beginDate the begin date./*from  ww  w. j a v a2s .  c o m*/
 * @param endDate the end date.
 * @return the most relevant GRANULARITY.
 */
private GRANULARITY guessGranularity(String beginDate, String endDate) {
    DateTime from = DateTime.parse(beginDate, this.dbOutputFormatter);
    DateTime to = DateTime.parse(endDate, this.dbOutputFormatter);

    Duration duration = new Duration(from, to);
    long numdays = duration.getStandardDays();
    if (numdays < 2) {
        return GRANULARITY.HOUR;
    } else if (numdays < 90) {
        return GRANULARITY.DAY;
    } else if (numdays < 365) {
        return GRANULARITY.WEEK;
    } else {
        return GRANULARITY.MONTH;
    }
}

From source file:org.graylog.plugins.pipelineprocessor.ast.expressions.AdditionExpression.java

License:Open Source License

@Nullable
@Override// w  w  w.j a v  a2 s  .c o  m
public Object evaluateUnsafe(EvaluationContext context) {
    final Object leftValue = left.evaluateUnsafe(context);
    final Object rightValue = right.evaluateUnsafe(context);

    // special case for date arithmetic
    final boolean leftDate = DateTime.class.equals(leftValue.getClass());
    final boolean leftPeriod = Period.class.equals(leftValue.getClass());
    final boolean rightDate = DateTime.class.equals(rightValue.getClass());
    final boolean rightPeriod = Period.class.equals(rightValue.getClass());

    if (leftDate && rightPeriod) {
        final DateTime date = (DateTime) leftValue;
        final Period period = (Period) rightValue;

        return isPlus() ? date.plus(period) : date.minus(period);
    } else if (leftPeriod && rightDate) {
        final DateTime date = (DateTime) rightValue;
        final Period period = (Period) leftValue;

        return isPlus() ? date.plus(period) : date.minus(period);
    } else if (leftPeriod && rightPeriod) {
        final Period period1 = (Period) leftValue;
        final Period period2 = (Period) rightValue;

        return isPlus() ? period1.plus(period2) : period1.minus(period2);
    } else if (leftDate && rightDate) {
        // the most uncommon, this is only defined for - really and means "interval between them"
        // because adding two dates makes no sense
        if (isPlus()) {
            // makes no sense to compute and should be handles in the parser already
            return null;
        }
        final DateTime left = (DateTime) leftValue;
        final DateTime right = (DateTime) rightValue;

        if (left.isBefore(right)) {
            return new Duration(left, right);
        } else {
            return new Duration(right, left);
        }
    }
    if (isIntegral()) {
        final long l = (long) leftValue;
        final long r = (long) rightValue;
        if (isPlus) {
            return l + r;
        } else {
            return l - r;
        }
    } else {
        final double l = (double) leftValue;
        final double r = (double) rightValue;
        if (isPlus) {
            return l + r;
        } else {
            return l - r;
        }
    }
}

From source file:org.imsglobal.lti.toolProvider.ResourceLinkShareKey.java

License:Apache License

/**
 * Load the resource link share key from the database.
 *///from w  w  w.j a  v a 2  s. c  o m
private void load() {

    initialize();
    dataConnector.loadResourceLinkShareKey(this);
    if (id != null) {
        length = String.valueOf(id).length();
    }
    if (expires != null) {
        Duration duration = new Duration(expires, DateTime.now());
        life = duration.getStandardHours();
    }

}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionImpl.java

License:Apache License

@Override
public String getTimeFancyText(DateTime from, DateTime to) {
    final String prefix = "Join in ";
    if (to != null) {
        Duration d = new Duration(to, from);
        Period timeUntil = new Period(to.toInstant(), from.toInstant(), PeriodType.dayTime());

        long standardDays = d.getStandardDays();

        if (standardDays > 0) {
            PeriodFormatter daysHours = new PeriodFormatterBuilder().appendDays().appendSuffix(" day", " days")
                    .appendSeparator(", and ").appendHours().appendSuffix(" hour", " hours").toFormatter();
            return prefix + daysHours.print(timeUntil.normalizedStandard(PeriodType.dayTime()));
        } else {/* w ww .  jav a  2  s.c o m*/
            PeriodFormatter dafaultFormatter = new PeriodFormatterBuilder().appendHours()
                    .appendSuffix(" hour", " hours").appendSeparator(", and ").appendMinutes()
                    .appendSuffix(" minute", " minutes").toFormatter();
            return prefix + dafaultFormatter.print(timeUntil.normalizedStandard(PeriodType.dayTime()));
        }

    } else {
        return null;
    }
}

From source file:org.jasig.portlet.notice.service.classloader.DemoNotificationService.java

License:Apache License

@Override
public NotificationResponse fetch(PortletRequest req) {

    NotificationResponse rslt = EMPTY_RESPONSE; // default

    // Are we active?
    if (active) {
        log.debug("Sending a non-empty response because we are ACTIVE");
        rslt = super.fetch(req);

        // A dash of post-processing to make the demo data more relevant.

        // Calculate days adjustment factor for all student jobs date values.  Use number of days from from
        // 05/15/2014 to the current date.
        int jobDaysAdjustment = (int) new Duration(new LocalDate(2014, 5, 15).toDateTimeAtStartOfDay(),
                new LocalDate().toDateTimeAtStartOfDay()).getStandardDays();

        for (NotificationCategory nc : rslt.getCategories()) {
            for (NotificationEntry y : nc.getEntries()) {

                // Make all the due dates at or near today
                if (y.getDueDate() != null) {
                    // Just manipulate the ones that actually have 
                    // a due date;  leave the others blank
                    y.setDueDate(generateRandomDueDate());
                }/*from  w w  w . jav  a  2s  .c  o m*/

                // For student jobs demo data, set relevant postDate, dateClosed, and startDate values based on
                // current data.
                updateDateAttributeIfPresent(y.getAttributes(), "postDate", jobDaysAdjustment);
                updateDateAttributeIfPresent(y.getAttributes(), "dateClosed", jobDaysAdjustment);
                updateDateAttributeIfPresent(y.getAttributes(), "startDate", jobDaysAdjustment);
            }
        }

    } else {
        log.debug("Sending an empty response because we are INACTIVE");
    }

    return rslt;
}

From source file:org.jbpm.process.core.timer.BusinessCalendarImpl.java

License:Apache License

protected String adoptISOFormat(String timeExpression) {

    try {/*from  www  . j av  a  2 s .  c  o  m*/
        Period p = null;
        if (DateTimeUtils.isPeriod(timeExpression)) {
            p = ISOPeriodFormat.standard().parsePeriod(timeExpression);
        } else {
            DateTime dt = ISODateTimeFormat.dateTimeParser().parseDateTime(timeExpression);
            Duration duration = new Duration(System.currentTimeMillis(), dt.getMillis());

            p = duration.toPeriod();
        }
        int days = p.getDays();
        int hours = p.getHours();
        int minutes = p.getMinutes();
        int seconds = p.getSeconds();
        int milis = p.getMillis();

        StringBuffer time = new StringBuffer();
        if (days > 0) {
            time.append(days + "d");
        }
        if (hours > 0) {
            time.append(hours + "h");
        }
        if (minutes > 0) {
            time.append(minutes + "m");
        }
        if (seconds > 0) {
            time.append(seconds + "s");
        }
        if (milis > 0) {
            time.append(milis + "ms");
        }

        return time.toString();
    } catch (Exception e) {
        return timeExpression;
    }
}

From source file:org.jbpm.process.core.timer.DateTimeUtils.java

License:Apache License

public static long parseDateAsDuration(String dateTimeStr) {
    try {/*from  w  w w .ja  v  a  2s . c  om*/

        DateTime dt = ISODateTimeFormat.dateTimeParser().parseDateTime(dateTimeStr);
        Duration duration = new Duration(System.currentTimeMillis(), dt.getMillis());

        return duration.getMillis();
    } catch (Exception e) {
        return TimeUtils.parseTimeString(dateTimeStr);
    }
}