Example usage for org.joda.time Duration isLongerThan

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

Introduction

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

Prototype

public boolean isLongerThan(ReadableDuration duration) 

Source Link

Document

Is the length of this duration longer than the duration passed in.

Usage

From source file:julian.lylly.model.Prospect.java

public boolean isSucceeded(Duration timespent) {
    return isOver() && !timespent.isShorterThan(min) && !timespent.isLongerThan(max);
}

From source file:julian.lylly.model.Prospect.java

public boolean tooHigh(Duration timespent) {
    return isOver() && timespent.isLongerThan(max);
}

From source file:julian.lylly.model.Prospect.java

static void checkMinMaxConstraint(Duration min, Duration max) {
    if (min.isLongerThan(max)) {
        throw new IllegalArgumentException("min must be less or equal max");
    }/*  ww w . j ava 2 s  .  c  o m*/
}

From source file:net.link.util.ws.security.x509.WSSecurityX509TokenHandler.java

License:Open Source License

private boolean handleInboundDocument(SOAPPart document, SOAPMessageContext soapMessageContext) {

    logger.dbg("In: WS-Security header validation");
    List<WSSecurityEngineResult> wsSecurityEngineResults;
    try {//from  ww w. j ava 2s .c om
        //noinspection unchecked
        wsSecurityEngineResults = new WSSecurityEngine().processSecurityHeader(document, null, null,
                new ServerCrypto());
    } catch (WSSecurityException e) {
        throw SOAPUtils.createSOAPFaultException("The signature or decryption was invalid", "FailedCheck", e);
    }
    logger.dbg("results: %s", wsSecurityEngineResults);
    if (null == wsSecurityEngineResults) {
        if (!getWSSecConfiguration().isInboundSignatureOptional())
            throw SOAPUtils.createSOAPFaultException("No WS-Security header was found but is required.",
                    "InvalidSecurity");

        logger.dbg("Allowing inbound message without signature: it's set to optional");
        return true;
    }

    Timestamp timestamp = null;
    List<WSDataRef> signedElements = null;
    for (WSSecurityEngineResult result : wsSecurityEngineResults) {

        @SuppressWarnings("unchecked")
        List<WSDataRef> resultSignedElements = (List<WSDataRef>) result
                .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
        //            Set<String> resultSignedElements = (Set<String>) result.get( WSSecurityEngineResult.TAG_SIGNED_ELEMENT_IDS );
        if (null != resultSignedElements)
            signedElements = resultSignedElements;

        X509Certificate[] certificateChain = (X509Certificate[]) result
                .get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
        X509Certificate certificate = (X509Certificate) result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
        if (null != certificateChain)
            setCertificateChain(soapMessageContext, certificateChain);
        else if (null != certificate)
            setCertificateChain(soapMessageContext, certificate);

        Timestamp resultTimestamp = (Timestamp) result.get(WSSecurityEngineResult.TAG_TIMESTAMP);
        if (null != resultTimestamp)
            timestamp = resultTimestamp;
    }

    if (null == signedElements)
        throw SOAPUtils.createSOAPFaultException("No signed elements found.", "FailedCheck");
    logger.dbg("# signed elements: %d", signedElements.size());
    soapMessageContext.put(SIGNED_ELEMENTS_CONTEXT_KEY, signedElements);

    // Check whether the SOAP Body has been signed.
    try {
        String bodyId = document.getEnvelope().getBody().getAttributeNS(WSConstants.WSU_NS, "Id");

        if (null == bodyId || bodyId.isEmpty())
            throw SOAPUtils.createSOAPFaultException("SOAP Body should have a wsu:Id attribute", "FailedCheck");
        if (!isElementSigned(soapMessageContext, bodyId))
            throw SOAPUtils.createSOAPFaultException("SOAP Body was not signed", "FailedCheck");
    } catch (SOAPException e) {
        throw SOAPUtils.createSOAPFaultException("error retrieving SOAP Body", "FailedCheck", e);
    }

    /*
    * Validate certificate.
    */
    CertificateChain certificateChain = findCertificateChain(soapMessageContext);
    if (null == certificateChain)
        throw SOAPUtils.createSOAPFaultException("missing X509Certificate chain in WS-Security header",
                "InvalidSecurity");
    if (!getWSSecConfiguration().isCertificateChainTrusted(certificateChain))
        throw SOAPUtils.createSOAPFaultException("can't trust X509Certificate chain in WS-Security header",
                "InvalidSecurity");

    /*
     * Check timestamp.
     */
    if (null == timestamp)
        throw SOAPUtils.createSOAPFaultException("missing Timestamp in WS-Security header", "InvalidSecurity");
    String timestampId = timestamp.getID();
    if (!isElementSigned(soapMessageContext, timestampId))
        throw SOAPUtils.createSOAPFaultException("Timestamp not signed", "FailedCheck");
    Duration age = new Duration(timestamp.getCreated().getTime(), System.currentTimeMillis());
    Duration maximumAge = getWSSecConfiguration().getMaximumAge();
    if (age.isLongerThan(maximumAge)) {
        logger.dbg("Maximum age exceeded by %s (since %s)", maximumAge.minus(age),
                timestamp.getCreated().getTime());
        throw SOAPUtils.createSOAPFaultException("Message too old", "FailedCheck");
    }

    return true;
}

From source file:org.agatom.springatom.web.validator.AppointmentValidator.java

License:Open Source License

private void validateDates(final NAppointment appointment, final ValidationContext context) {
    final MessageContext messageContext = context.getMessageContext();
    final MessageBuilder messageBuilder = new MessageBuilder();

    final DateTime begin = appointment.getBegin();
    final DateTime end = appointment.getEnd();

    final int beginHourOfDay = begin.getHourOfDay();
    final int endHourOfDay = end.getHourOfDay();
    if (beginHourOfDay < this.minTime) {
        messageContext.addMessage(messageBuilder.source("begin").error()
                .defaultText(String.format("Begin hour must not be lower than %d", this.minTime)).build());
    }/*from  w  w  w .  j  a v  a  2  s .  co m*/
    if (endHourOfDay > this.maxTime) {
        messageContext.addMessage(messageBuilder.source("end").error()
                .defaultText(String.format("End hour must not be higher than %d", this.maxTime)).build());
    }
    if (begin.isAfter(end)) {
        messageContext.addMessage(
                messageBuilder.source("begin").error().defaultText("Begin must be before End").build());
    } else {
        final Duration duration = new Duration(end.minus(begin.getMillis()).getMillis());
        if (duration.isShorterThan(new Duration(this.minDiffBetweenDates))) {
            messageContext
                    .addMessage(
                            messageBuilder.source("interval").warning()
                                    .defaultText(String.format("Time of appointment is shorter than %d minutes",
                                            TimeUnit.MILLISECONDS.toMinutes(this.minDiffBetweenDates)))
                                    .build());
        } else if (duration.isLongerThan(new Duration(this.maxDiffBetweenDates))) {
            messageContext.addMessage(messageBuilder.source("interval").warning()
                    .defaultText(String.format("Time of appointment is longer than %d days",
                            TimeUnit.MILLISECONDS.toDays(this.maxDiffBetweenDates)))
                    .build());
        }
    }
}

From source file:org.apache.beam.runners.dataflow.DataflowPipelineJob.java

License:Apache License

/**
 * Reset backoff. If duration is limited, calculate time remaining, otherwise just reset retry
 * count./*from ww w.j  ava  2 s .  c o m*/
 *
 * <p>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.
 */
private static BackOff resetBackoff(Duration duration, NanoClock nanoClock, long startNanos) {
    BackOff backoff;
    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 = getMessagesBackoff(remaining);
        } else {
            backoff = BackOff.STOP_BACKOFF;
        }
    } else {
        backoff = getMessagesBackoff(duration);
    }
    return backoff;
}

From source file:org.apache.beam.runners.spark.io.SourceDStream.java

License:Apache License

private Duration boundReadDuration(double readTimePercentage, long minReadTimeMillis) {
    long batchDurationMillis = ssc().graph().batchDuration().milliseconds();
    Duration proportionalDuration = new Duration(Math.round(batchDurationMillis * readTimePercentage));
    Duration lowerBoundDuration = new Duration(minReadTimeMillis);
    Duration readDuration = proportionalDuration.isLongerThan(lowerBoundDuration) ? proportionalDuration
            : lowerBoundDuration;//  ww w .  jav  a2  s.  c  o  m
    LOG.info("Read duration set to: " + readDuration);
    return readDuration;
}

From source file:org.apache.beam.sdk.nexmark.NexmarkLauncher.java

License:Apache License

/**
 * Monitor the performance and progress of a running job. Return final performance if it was
 * measured.//from   ww w .  ja  v a2  s .c  om
 */
@Nullable
private NexmarkPerf monitor(NexmarkQuery query) {
    if (!options.getMonitorJobs()) {
        return null;
    }

    if (configuration.debug) {
        NexmarkUtils.console("Waiting for main pipeline to 'finish'");
    } else {
        NexmarkUtils.console("--debug=false, so job will not self-cancel");
    }

    PipelineResult job = mainResult;
    PipelineResult publisherJob = publisherResult;
    List<NexmarkPerf.ProgressSnapshot> snapshots = new ArrayList<>();
    long startMsSinceEpoch = System.currentTimeMillis();
    long endMsSinceEpoch = -1;
    if (options.getRunningTimeMinutes() != null) {
        endMsSinceEpoch = startMsSinceEpoch
                + Duration.standardMinutes(options.getRunningTimeMinutes()).getMillis()
                - Duration.standardSeconds(configuration.preloadSeconds).getMillis();
    }
    long lastActivityMsSinceEpoch = -1;
    NexmarkPerf perf = null;
    boolean waitingForShutdown = false;
    boolean cancelJob = false;
    boolean publisherCancelled = false;
    List<String> errors = new ArrayList<>();

    while (true) {
        long now = System.currentTimeMillis();
        if (endMsSinceEpoch >= 0 && now > endMsSinceEpoch && !waitingForShutdown) {
            NexmarkUtils.console("Reached end of test, cancelling job");
            try {
                cancelJob = true;
                job.cancel();
            } catch (IOException e) {
                throw new RuntimeException("Unable to cancel main job: ", e);
            }
            if (publisherResult != null) {
                try {
                    publisherJob.cancel();
                } catch (IOException e) {
                    throw new RuntimeException("Unable to cancel publisher job: ", e);
                }
                publisherCancelled = true;
            }
            waitingForShutdown = true;
        }

        PipelineResult.State state = job.getState();
        NexmarkUtils.console("%s %s%s", state, queryName, waitingForShutdown ? " (waiting for shutdown)" : "");

        NexmarkPerf currPerf;
        if (configuration.debug) {
            currPerf = currentPerf(startMsSinceEpoch, now, job, snapshots, query.eventMonitor,
                    query.resultMonitor);
        } else {
            currPerf = null;
        }

        if (perf == null || perf.anyActivity(currPerf)) {
            lastActivityMsSinceEpoch = now;
        }

        if (options.isStreaming() && !waitingForShutdown) {
            Duration quietFor = new Duration(lastActivityMsSinceEpoch, now);
            long fatalCount = new MetricsReader(job, query.getName()).getCounterMetric("fatal");

            if (fatalCount == -1) {
                fatalCount = 0;
            }

            if (fatalCount > 0) {
                NexmarkUtils.console("ERROR: job has fatal errors, cancelling.");
                errors.add(String.format("Pipeline reported %s fatal errors", fatalCount));
                waitingForShutdown = true;
                cancelJob = true;
            } else if (configuration.debug && configuration.numEvents > 0
                    && currPerf.numEvents == configuration.numEvents && currPerf.numResults >= 0
                    && quietFor.isLongerThan(DONE_DELAY)) {
                NexmarkUtils.console("streaming query appears to have finished waiting for completion.");
                waitingForShutdown = true;
            } else if (quietFor.isLongerThan(STUCK_TERMINATE_DELAY)) {
                NexmarkUtils.console(
                        "ERROR: streaming query appears to have been stuck for %d minutes, cancelling job.",
                        quietFor.getStandardMinutes());
                errors.add(String.format("Cancelling streaming job since it appeared stuck for %d min.",
                        quietFor.getStandardMinutes()));
                waitingForShutdown = true;
                cancelJob = true;
            } else if (quietFor.isLongerThan(STUCK_WARNING_DELAY)) {
                NexmarkUtils.console("WARNING: streaming query appears to have been stuck for %d min.",
                        quietFor.getStandardMinutes());
            }

            if (cancelJob) {
                try {
                    job.cancel();
                } catch (IOException e) {
                    throw new RuntimeException("Unable to cancel main job: ", e);
                }
            }
        }

        perf = currPerf;

        boolean running = true;
        switch (state) {
        case UNKNOWN:
        case UNRECOGNIZED:
        case STOPPED:
        case RUNNING:
            // Keep going.
            break;
        case DONE:
            // All done.
            running = false;
            break;
        case CANCELLED:
            running = false;
            if (!cancelJob) {
                errors.add("Job was unexpectedly cancelled");
            }
            break;
        case FAILED:
        case UPDATED:
            // Abnormal termination.
            running = false;
            errors.add("Job was unexpectedly updated");
            break;
        }

        if (!running) {
            break;
        }

        if (lastActivityMsSinceEpoch == now) {
            NexmarkUtils.console("new perf %s", perf);
        } else {
            NexmarkUtils.console("no activity");
        }

        try {
            Thread.sleep(PERF_DELAY.getMillis());
        } catch (InterruptedException e) {
            Thread.interrupted();
            NexmarkUtils.console("Interrupted: pipeline is still running");
        }
    }

    perf.errors = errors;
    perf.snapshots = snapshots;

    if (publisherResult != null) {
        NexmarkUtils.console("Shutting down publisher pipeline.");
        try {
            if (!publisherCancelled) {
                publisherJob.cancel();
            }
            publisherJob.waitUntilFinish(Duration.standardMinutes(5));
        } catch (IOException e) {
            throw new RuntimeException("Unable to cancel publisher job: ", e);
        }
    }

    return perf;
}

From source file:org.kitodo.production.helper.tasks.TaskSitter.java

License:Open Source License

/**
 * The function run() examines the task list, deletes threads that have
 * died, replaces threads that are to be restarted by new copies of
 * themselves and finally starts new threads up to the given limit.
 *
 * <p>//from w  w  w .ja  v  a  2 s.c  o  m
 * Several limits are configurable: There are both limits in number and in
 * time for successfully finished or erroneous threads which can be set in
 * the configuration. There are internal default values for these settings
 * too, which will be applied in case of missing configuration entries.
 * Since zombie processes will still occupy all their resources and arent
 * available for garbage collection, these values have been chosen rather
 * restrictive. For the limit for auto starting threads, see
 * {@link #setAutoRunningThreads(boolean)}.
 * </p>
 *
 * <p>
 * If the task list is empty, the method will exit without further delay,
 * otherwise it will initialise its variables and read the configuration.
 * Reading the configuration is done again in each iteration so
 * configuration changes will propagate here.
 * </p>
 *
 * <p>
 * Then the function iterates along the task list and takes care for each
 * task. To be able to modify the list in passing, we need a
 * {@link java.util.ListIterator} here.
 * </p>
 *
 * <p>
 * Running tasks reduce the clearance to run new tasks. (However, the
 * clearance must not become negative.) New tasks will be added to the
 * launch list, except if they have already been marked for removal, of
 * course. If a task has terminated, it is handled as specified by its
 * behaviour variable: All tasks that are marked DELETE_IMMEDIATELY will
 * instantly be disposed of; otherwise, they will be kept as long as
 * configured and only be removed if their dead body has become older. Tasks
 * marked PREPARE_FOR_RESTART will be replaced (because a
 * {@link java.lang.Thread} cannot be started a second time) by a copy of
 * them.
 * </p>
 *
 * <p>
 * If a ConcurrentModificationException arises during list examination, the
 * method will behave like a polite servant and retire silently until the
 * lordship has scarpered. This is not a pity because it will be started
 * every some seconds.
 * </p>
 *
 * </p>
 * After having finished iterating, the method will reduce the absolute
 * number of expired threads as configured. (Since new threads will be added
 * to the bottom of the list and we therefore want to remove older ones
 * top-down we cannot do this before we know their count, thus we cannot do
 * this while iterating.) Last, new threads will be started up to the
 * remaining available clearance.
 * </p>
 *
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    TaskManager taskManager = TaskManager.singleton();
    if (taskManager.taskList.isEmpty()) {
        return;
    }

    LinkedList<EmptyTask> launchableThreads = new LinkedList<>();
    LinkedList<EmptyTask> finishedThreads = new LinkedList<>();
    LinkedList<EmptyTask> failedThreads = new LinkedList<>();
    int availableClearance = autoRunLimit;

    int successfulMaxCount = ConfigCore
            .getIntParameterOrDefaultValue(ParameterCore.TASK_MANAGER_KEEP_SUCCESSFUL);
    int failedMaxCount = ConfigCore.getIntParameterOrDefaultValue(ParameterCore.TASK_MANAGER_KEEP_FAILED);
    Duration successfulMaxAge = ConfigCore.getDurationParameter(ParameterCore.TASK_MANAGER_KEEP_SUCCESSFUL_MINS,
            TimeUnit.MINUTES);
    Duration failedMaxAge = ConfigCore.getDurationParameter(ParameterCore.TASK_MANAGER_KEEP_FAILED_MINS,
            TimeUnit.MINUTES);

    ListIterator<EmptyTask> position = taskManager.taskList.listIterator();
    EmptyTask task;
    try {
        while (position.hasNext()) {
            task = position.next();
            switch (task.getTaskState()) {
            case WORKING:
            case STOPPING:
                availableClearance = Math.max(availableClearance - 1, 0);
                break;
            case NEW:
                if (Behaviour.DELETE_IMMEDIATELY.equals(task.getBehaviour())) {
                    position.remove();
                } else {
                    launchableThreads.addLast(task);
                }
                break;
            default: // cases STOPPED, FINISHED, CRASHED
                switch (task.getBehaviour()) {
                case DELETE_IMMEDIATELY:
                    position.remove();
                    break;
                case PREPARE_FOR_RESTART:
                    EmptyTask replacement = task.replace();
                    if (Objects.nonNull(replacement)) {
                        position.set(replacement);
                        launchableThreads.addLast(replacement);
                    }
                    break;
                default: // case KEEP_FOR_A_WHILE
                    boolean taskFinishedSuccessfully = Objects.isNull(task.getException());
                    Duration durationDead = task.getDurationDead();
                    if (Objects.isNull(durationDead)) {
                        task.setTimeOfDeath();
                    } else if (durationDead
                            .isLongerThan(taskFinishedSuccessfully ? successfulMaxAge : failedMaxAge)) {
                        position.remove();
                        break;
                    }
                    if (taskFinishedSuccessfully) {
                        finishedThreads.add(task);
                    } else {
                        failedThreads.add(task);
                    }
                    break;
                }
            }
        }
    } catch (ConcurrentModificationException e) {
        return;
    }

    while (finishedThreads.size() > successfulMaxCount && (task = finishedThreads.pollFirst()) != null) {
        taskManager.taskList.remove(task);
    }

    while (failedThreads.size() > failedMaxCount && (task = failedThreads.pollFirst()) != null) {
        taskManager.taskList.remove(task);
    }

    while (launchableThreads.size() > availableClearance) {
        launchableThreads.removeLast();
    }
    while ((task = launchableThreads.pollFirst()) != null) {
        task.start();
    }
}

From source file:org.samcrow.ridgesurvey.TimerFragment.java

License:Open Source License

private void startTimer() {
    if (!mRunning) {
        showTime(Duration.ZERO);/*from ww w . j  a v  a2 s .  co  m*/
        mStartStopButton.setImageResource(ICON_STOP);
        mRunning = true;
        mTimer = new Timer();
        mNotificationManager.cancelAll();

        mCurrentDuration = Duration.ZERO;
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                final Duration newDuration = mCurrentDuration.plus(Duration.standardSeconds(1));
                mCurrentDuration = newDuration;

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showTime(newDuration);
                    }
                });

                if (newDuration.isEqual(HALF_PERIOD)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            notifyHalfPeriod();
                        }
                    });
                }

                if (newDuration.isEqual(COUNT_UP_PERIOD) || newDuration.isLongerThan(COUNT_UP_PERIOD)) {
                    mTimer.cancel();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            notifyStopped();
                            stopTimer();
                        }
                    });
                }
            }
        }, 1000, 1000);
    }
}