Example usage for org.joda.time Duration minus

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

Introduction

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

Prototype

public Duration minus(ReadableDuration amount) 

Source Link

Document

Returns a new duration with this length minus that specified.

Usage

From source file:au.id.hazelwood.xmltvguidebuilder.postprocessor.ListingVerifier.java

License:Apache License

public void verifyListing(ChannelListings listings, DateTime from, DateTime to, DateTime subsetTo) {
    Duration listingDurationTotal = new Interval(from, to).toDuration();
    Duration listingDurationSubset = new Interval(from, subsetTo).toDuration();
    LOGGER.info(repeat("-", 100));
    for (ChannelDetail channelDetail : listings.getChannels()) {
        Duration missingDurationTotal = Duration.ZERO;
        Duration missingDurationSubset = Duration.ZERO;
        StringBuilder allMissingIntervalDetails = new StringBuilder();
        for (Interval missing : findMissingIntervals(listings, from, to, channelDetail.getId())) {
            missingDurationTotal = missingDurationTotal.plus(missing.toDuration());
            if (missing.getStart().isBefore(subsetTo)) {
                if (missing.getEnd().isBefore(subsetTo)) {
                    missingDurationSubset = missingDurationSubset.plus(missing.toDuration());
                } else {
                    missingDurationSubset = missingDurationSubset
                            .plus(new Duration(missing.getStart(), subsetTo));
                }/*from   w  w  w  .j a  v a  2  s .c  o  m*/
            }
            allMissingIntervalDetails.append(allMissingIntervalDetails.length() == 0 ? "missing " : ", ");
            allMissingIntervalDetails.append(
                    format("{0}-{1}", toISODateTime(missing.getStart()), toISODateTime(missing.getEnd())));
        }
        Duration availableDurationTotal = listingDurationTotal.minus(missingDurationTotal);
        Duration availableDurationSubset = listingDurationSubset.minus(missingDurationSubset);
        Integer availablePercentageTotal = getPercentage(availableDurationTotal, listingDurationTotal);
        Integer availablePercentageSubset = getPercentage(availableDurationSubset, listingDurationSubset);
        LOGGER.info("{} {} [{}|{}] {}", rightPad(channelDetail.getId() + " - " + channelDetail.getName(), 42),
                formatDurationDHM(availableDurationTotal.getMillis()),
                leftPad(availablePercentageSubset + "%", 4), leftPad(availablePercentageTotal + "%", 4),
                allMissingIntervalDetails.toString());
    }
    LOGGER.info(repeat("-", 100));
}

From source file:ch.eitchnet.android.util.JodaHelper.java

License:Open Source License

public static String toDays(Duration duration) {
    Duration tmp = duration;
    double days = tmp.getStandardDays();
    if (days >= Integer.MAX_VALUE)
        throw new RuntimeException("Buffer overflow for number of days in duration: " + tmp);
    tmp = tmp.minus(Days.days((int) days).toStandardDuration());
    double hours = tmp.getStandardHours();
    if (hours >= Integer.MAX_VALUE)
        throw new RuntimeException("Buffer overflow for number of hours in duration: " + tmp);

    return Double.toString(days + (hours / 24));
}

From source file:com.aliakseipilko.flightdutytracker.presenter.impl.HourPresenter.java

License:Open Source License

@Override
public void subscribeAllCallbacks() {
    getMultipleFlightsDutyHoursCallback = new IFlightRepository.OnGetMultipleFlightsCallback() {
        @Override//w ww . j a v a2  s  .  com
        public void OnSuccess(RealmResults<Flight> flights) {
            double dutyMillis = 0;

            for (Flight flight : flights) {
                dutyMillis += (flight.getEndDutyTime().getTime() - flight.getStartDutyTime().getTime());
            }

            Duration dutyDuration = Duration.millis((long) dutyMillis);
            long hours = dutyDuration.getStandardHours();
            long minutes = dutyDuration.minus(hours * 60 * 60 * 1000).getStandardMinutes();
            if (minutes < 10) {
                view.showDutyHours(hours + ":0" + minutes, dutyMillis);
            } else {
                view.showDutyHours(hours + ":" + minutes, dutyMillis);
            }
        }

        @Override
        public void OnError(String message) {
            view.showError(message);
        }
    };
    getMultipleFlightsFlightHoursCallback = new IFlightRepository.OnGetMultipleFlightsCallback() {
        @Override
        public void OnSuccess(RealmResults<Flight> flights) {
            double flightMillis = 0;

            for (Flight flight : flights) {
                flightMillis += (flight.getEndFlightTime().getTime() - flight.getStartFlightTime().getTime());
            }

            Duration dutyDuration = Duration.standardSeconds((long) (flightMillis / 1000));
            long hours = dutyDuration.getStandardHours();
            long minutes = dutyDuration.minus(hours * 60 * 60 * 1000).getStandardMinutes();
            if (minutes < 10) {
                view.showFlightHours(hours + ":0" + minutes, flightMillis);
            } else {
                view.showFlightHours(hours + ":" + minutes, flightMillis);
            }
        }

        @Override
        public void OnError(String message) {
            view.showError(message);
        }
    };
}

From source file:com.daemon.Minion.java

License:Open Source License

/**
 * Calculates the interval length for the given search term (and its meta data).
 * @param metaData The meta data with search term for which the new interval length
 * should be calculated.//from  w  w w.jav a 2 s . c  o m
 * @param logger The log file that is used by the daemon.
 * @param props The properties file that is used by the daemon.
 * @param name The name of the Twitter profile that is used.
 * @return Returns the interval length for the meta data object.
 */
public static Duration calculateIntervalLength(SearchTermMetaData metaData, Logger logger,
        DaemonProperties props, String name) {
    SearchTerm term = metaData.getSearchTerm();
    int count = metaData.getTweetCount();

    double priorityFactor = props.priorityFactors[props.defaultPriorityIndex];

    // Try setting the priority factor
    try {
        priorityFactor = (int) mapPriority(term.getPriority(), props);
    } catch (IllegalArgumentException ex) {
        try {
            if (logger != null) {
                logger.log("Cannot read priority from search term " + term.getTerm() + "(id " + term.getId()
                        + "). Using default value.", name);
            }
        } catch (Exception _) {
        }
    }

    // Time difference between newest tweet and oldest acceptable tweet in minutes
    double timeDiff = 0;

    // If we have no new tweets, this field is empty
    if (metaData.getNewestTweetDate() != null) {
        timeDiff = metaData.getNewestTweetDate().minus(metaData.getOldestTweetDate().getMillis()).getMillis()
                / 60000d;
    }

    long intervalLengthInMin = 0;
    if (timeDiff != 0) {
        // Tweets per minute
        double tpm = ((double) count) / timeDiff;

        // The formula for the interval length in minutes
        intervalLengthInMin = (int) (priorityFactor * (1 / tpm) * props.throttleFactor * 100);
    } else if (count <= 1) {
        // Here: timeDiff == 0
        // This may be a statistical outlier, so we increase the interval length
        // manually and not by formula
        intervalLengthInMin = term.getIntervalLength().getMillis() / 60000 * props.outlierFactor;
    }

    // if timeDiff == 0, but count > 1, we have A LOT of tweets, so interval length
    // should be as low as possible (so it is set to 0).

    // Make sure the interval length does not fall below the given default value
    Duration intervalLength = new Duration(intervalLengthInMin * 60000L);
    if (intervalLength.minus(props.defaultIntervalLength.getMillis()).getMillis() < 0)
        intervalLength = props.defaultIntervalLength;
    else if (intervalLength.minus(props.maxIntervalLength.getMillis()).getMillis() > 0)
        intervalLength = props.maxIntervalLength;

    return intervalLength;
}

From source file:com.google.cloud.dataflow.sdk.runners.DataflowPipelineJob.java

License:Apache License

/**
 * Wait for the job to finish and return the final status.
 *
 * @param duration The total time to wait for the job to finish.
 *     Provide a value less than 1 ms for an infinite wait.
 * @param messageHandler If non null this handler will be invoked for each
 *   batch of messages received./*from   ww w  . j  a va2 s . com*/
 * @param sleeper A sleeper to use to sleep between attempts.
 * @param nanoClock A nanoClock used to time the total time taken.
 * @return The final state of the job or null on timeout or if the
 *   thread is interrupted.
 * @throws IOException If there is a persistent problem getting job
 *   information.
 * @throws InterruptedException
 */
@Nullable
@VisibleForTesting
State waitToFinish(Duration duration, MonitoringUtil.JobMessagesHandler messageHandler, Sleeper sleeper,
        NanoClock nanoClock) throws IOException, InterruptedException {
    MonitoringUtil monitor = new MonitoringUtil(projectId, dataflowClient);

    long lastTimestamp = 0;
    BackOff backoff;
    if (!duration.isLongerThan(Duration.ZERO)) {
        backoff = MESSAGES_BACKOFF_FACTORY.backoff();
    } else {
        backoff = MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(duration).backoff();
    }

    // This function tracks the cumulative time from the *first request* to enforce the wall-clock
    // limit. Any backoff instance could, at best, track the the time since the first attempt at a
    // given request. Thus, we need to track the cumulative time ourselves.
    long startNanos = nanoClock.nanoTime();

    State state;
    do {
        // Get the state of the job before listing messages. This ensures we always fetch job
        // messages after the job finishes to ensure we have all them.
        state = getStateWithRetries(STATUS_BACKOFF_FACTORY.withMaxRetries(0).backoff(), sleeper);
        boolean hasError = state == State.UNKNOWN;

        if (messageHandler != null && !hasError) {
            // Process all the job messages that have accumulated so far.
            try {
                List<JobMessage> allMessages = monitor.getJobMessages(jobId, lastTimestamp);

                if (!allMessages.isEmpty()) {
                    lastTimestamp = fromCloudTime(allMessages.get(allMessages.size() - 1).getTime())
                            .getMillis();
                    messageHandler.process(allMessages);
                }
            } catch (GoogleJsonResponseException | SocketTimeoutException e) {
                hasError = true;
                LOG.warn("There were problems getting current job messages: {}.", e.getMessage());
                LOG.debug("Exception information:", e);
            }
        }

        if (!hasError) {
            // We can stop if the job is done.
            if (state.isTerminal()) {
                return state;
            }

            // The job is not done, so we must keep polling.
            backoff.reset();

            // If a total duration for all backoff has been set, update the new cumulative sleep time to
            // be the remaining total backoff duration, stopping if we have already exceeded the
            // allotted time.
            if (duration.isLongerThan(Duration.ZERO)) {
                long nanosConsumed = nanoClock.nanoTime() - startNanos;
                Duration consumed = Duration.millis((nanosConsumed + 999999) / 1000000);
                Duration remaining = duration.minus(consumed);
                if (remaining.isLongerThan(Duration.ZERO)) {
                    backoff = MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(remaining).backoff();
                } else {
                    // If there is no time remaining, don't bother backing off.
                    backoff = BackOff.STOP_BACKOFF;
                }
            }
        }
    } while (BackOffUtils.next(sleeper, backoff));
    LOG.warn("No terminal state was returned.  State value {}", state);
    return null; // Timed out.
}

From source file:com.kopysoft.chronos.adapter.clock.PayPeriodAdapterList.java

License:Open Source License

public static Duration getTime(List<PunchPair> punches, boolean allowNegative) {
    Duration dur = new Duration(0);

    for (PunchPair pp : punches) {
        if (enableLog)
            Log.d(TAG, "Punch Size: " + pp.getDuration());
        if (!pp.getInPunch().getTask().getEnablePayOverride())
            dur = dur.plus(pp.getDuration());
        else if (pp.getInPunch().getTask().getPayOverride() > 0)
            dur = dur.plus(pp.getDuration());
        else/*from w ww .j  av  a2 s.c  o  m*/
            dur = dur.minus(pp.getDuration());
    }

    if (dur.getMillis() < 0 && !allowNegative)
        dur = new Duration(0);

    return dur;
}

From source file:com.kopysoft.chronos.adapter.clock.TodayAdapterPair.java

License:Open Source License

public static Duration getTime(List<PunchPair> punches, boolean allowNegative) {
    Duration dur = new Duration(0);

    for (PunchPair pp : punches) {
        if (enableLog)
            Log.d(TAG, "Punch Size: " + pp.getDuration());
        if (!pp.getInPunch().getTask().getEnablePayOverride())
            dur = dur.plus(pp.getDuration());
        else if (pp.getTask().getPayOverride() == 0)
            continue;
        else if (pp.getInPunch().getTask().getPayOverride() > 0)
            dur = dur.plus(pp.getDuration());
        else/*from  w w  w  . java  2s  . co  m*/
            dur = dur.minus(pp.getDuration());
    }

    if (dur.getMillis() < 0 && !allowNegative)
        dur = new Duration(0);

    return dur;
}

From source file:com.mirth.connect.server.util.LoginRequirementsChecker.java

License:Open Source License

public long getStrikeTimeRemaining() {
    Duration lockoutPeriod = Duration.standardHours(passwordRequirements.getLockoutPeriod());

    synchronized (userLoginStrikes) {
        Duration strikeDuration = new Duration(
                userLoginStrikes.get(username).getLastStrikeTime().getTimeInMillis(),
                System.currentTimeMillis());
        return lockoutPeriod.minus(strikeDuration).getMillis();
    }/*from w  w  w  .  ja va 2 s  . c o m*/
}

From source file:com.mirth.connect.server.util.LoginRequirementsChecker.java

License:Open Source License

private Duration getDurationRemainingFromDays(long passwordTime, long currentTime, int durationDays) {
    Duration expirationDuration = Duration.standardDays(durationDays);
    Duration passwordDuration = new Duration(passwordTime, currentTime);

    return expirationDuration.minus(passwordDuration);
}

From source file:com.vaushell.superpipes.nodes.A_Node.java

License:Open Source License

/**
 * Pop the last message.//from   w  ww  .j  a v  a  2  s .  co m
 *
 * @param timeout max time to wait. If timeout is smaller than antiburst, use antiburst.
 * @return the message (or null if empty)
 * @throws InterruptedException
 */
protected Message getLastMessageOrWait(final Duration timeout) throws InterruptedException {
    if (timeout == null) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getNodeID() + "] getLastMessageOrWait() : timeout=" + timeout);
    }

    final Message message;
    synchronized (internalStack) {
        DateTime start = new DateTime();
        Duration remaining = timeout;
        while (internalStack.isEmpty() && remaining.getMillis() > 0L) {
            internalStack.wait(remaining.getMillis());

            final DateTime now = new DateTime();

            final Duration elapsed = new Duration(start, now);

            remaining = remaining.minus(elapsed);

            start = now;
        }

        message = internalStack.pollLast();
    }

    if (lastPop != null && antiBurst != null) {
        // Null for now
        final Duration elapsed = new Duration(lastPop, null);

        final Duration remaining = antiBurst.minus(elapsed);
        if (remaining.getMillis() > 0L) {
            Thread.sleep(remaining.getMillis());
        }
    }

    lastPop = new DateTime();

    if (LOGGER.isDebugEnabled()) {
        if (message == null) {
            LOGGER.debug("[" + getNodeID() + "] wait message for " + timeout + "ms and get nothing");
        } else {
            LOGGER.debug("[" + getNodeID() + "] wait message for " + timeout + "ms and get message="
                    + Message.formatSimple(message));
        }
    }

    return message;
}