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:be.agiv.security.AGIVSecurity.java

License:Open Source License

private boolean requireNewToken(SecurityToken securityToken) {
    if (null == securityToken) {
        return true;
    }/*from   w w w  .ja  va  2 s.c  om*/
    DateTime now = new DateTime();
    DateTime expires = new DateTime(securityToken.getExpires());
    Duration duration = new Duration(now, expires);
    LOG.debug("token validity: " + duration);
    if (duration.isLongerThan(new Duration(this.tokenRetirementDuration))) {
        LOG.debug("reusing security token: " + securityToken.getAttachedReference());
        return false;
    }
    return true;
}

From source file:ch.oakmountain.tpa.solver.TrainPathApplicationStatistics.java

License:Apache License

List<String> compileAndGetTrainPathApplicationListRow() throws IOException {
    HashMap<TrainPathSlot, Vertex> slotVertexHashMap = new HashMap<>();
    HashMap<SystemNode, Set<TrainPathSlot>> systemNodeTrainPathSlotHashMap = new HashMap<>();
    HashMap<SystemNode, Set<Pair<TrainPathSlot, TrainPathSlot>>> connectionsThroughSystemNode = new HashMap<>();
    for (Vertex vertex : dag.getVerticies()) {
        if (vertex.isLeaf() || vertex.isRoot()) {
            continue;
        }// w  w w.  j a va  2s  .co m
        TrainPathSlot trainPathSlot = dag.getSlotFromVertex(vertex.getLabel());
        slotVertexHashMap.put(trainPathSlot, vertex);
        SystemNode from = trainPathSlot.getFrom();
        SystemNode to = trainPathSlot.getTo();
        initSystemNodeInMaps(systemNodeTrainPathSlotHashMap, connectionsThroughSystemNode, to);
        initSystemNodeInMaps(systemNodeTrainPathSlotHashMap, connectionsThroughSystemNode, from);
        systemNodeTrainPathSlotHashMap.get(from).add(trainPathSlot);

        for (Vertex child : vertex.getChildren()) {
            if (vertex.isLeaf() || vertex.isRoot()) {
                continue;
            }
            TrainPathSlot childSlot = dag.getSlotFromVertex(child.getLabel());
            Pair<TrainPathSlot, TrainPathSlot> connection = new Pair<TrainPathSlot, TrainPathSlot>(
                    trainPathSlot, childSlot);

            connectionsThroughSystemNode.get(to).add(connection);
        }
    }
    int minSlotsPerSystemNode = Integer.MAX_VALUE;
    int maxSlotsPerSystemNode = Integer.MIN_VALUE;

    for (SystemNode systemNode : systemNodeTrainPathSlotHashMap.keySet()) {

        Set<TrainPathSlot> succSlots = systemNodeTrainPathSlotHashMap.get(systemNode);
        int nbSuccSlots = succSlots.size();
        maxSlotsPerSystemNode = Math.max(nbSuccSlots, maxSlotsPerSystemNode);
        minSlotsPerSystemNode = Math.min(nbSuccSlots, minSlotsPerSystemNode);

        Duration minDwellTime = new Duration(Long.MAX_VALUE);
        Duration maxDwellTime = Duration.ZERO;
        Duration totalDwellTime = Duration.ZERO;

        Set<Pair<TrainPathSlot, TrainPathSlot>> connections = connectionsThroughSystemNode.get(systemNode);
        String dwellStats = "--";
        if (!systemNode.equals(simpleTrainPathApplication.getTo())
                && !systemNode.equals(simpleTrainPathApplication.getFrom())) {
            for (Pair<TrainPathSlot, TrainPathSlot> trainPathSlotTrainPathSlotPair : connections) {
                Duration dwell = trainPathSlotTrainPathSlotPair.second.getStartTime()
                        .distanceAfter(trainPathSlotTrainPathSlotPair.first.getEndTime());
                if (dwell.isShorterThan(Duration.ZERO)) {
                    throw new IllegalStateException("");
                }
                if (dwell.isLongerThan(maxDwellTime)) {
                    maxDwellTime = dwell;
                }
                if (dwell.isShorterThan(minDwellTime)) {
                    minDwellTime = dwell;
                }
                totalDwellTime = totalDwellTime.plus(dwell);
            }
            dwellStats = PeriodicalTimeFrame.formatDuration(minDwellTime) + "/"
                    + PeriodicalTimeFrame.formatDuration(maxDwellTime) + "/"
                    + PeriodicalTimeFrame.formatDuration(
                            totalDwellTime.dividedBy(connectionsThroughSystemNode.get(systemNode).size()));
        }

        String timeWindow;
        if (systemNode.equals(simpleTrainPathApplication.getFrom())) {
            timeWindow = "[" + simpleTrainPathApplication.getParams().getDepartureLowerBound().toString() + ","
                    + simpleTrainPathApplication.getParams().getDepartureUpperBound().toString() + "]";
        } else if (systemNode.equals(simpleTrainPathApplication.getTo())) {
            timeWindow = "[" + simpleTrainPathApplication.getParams().getArrivalLowerBound().toString() + ","
                    + simpleTrainPathApplication.getParams().getArrivalUpperBound().toString() + "]";
        } else {
            timeWindow = "[arr+ "
                    + PeriodicalTimeFrame.formatDuration(simpleTrainPathApplication.getParams()
                            .getMINIMUM_DWELL_TIME())
                    + ", arr+"
                    + PeriodicalTimeFrame.formatDuration(simpleTrainPathApplication.getParams()
                            .getHARD_MINIMUM_DWELL_TIME().plus(simpleTrainPathApplication.getParams()
                                    .getMAXIMUM_ADDITIONAL_DWELL_TIME(systemNode)))
                    + "]";
        }
        table.writeRow(Arrays.asList(
                systemNode.getName(), String.valueOf(nbSuccSlots), timeWindow, "["
                        + PeriodicalTimeFrame
                                .formatDuration(simpleTrainPathApplication.getParams().getMINIMUM_DWELL_TIME())
                        + ","
                        + PeriodicalTimeFrame.formatDuration(simpleTrainPathApplication.getParams()
                                .getMAXIMUM_ADDITIONAL_DWELL_TIME(systemNode))
                        + "]",
                "Min/max/average slots", dwellStats));
    }

    List<String> data = Arrays.asList(simpleTrainPathApplication.getName(),
            simpleTrainPathApplication.getFrom().getName(), simpleTrainPathApplication.getTo().getName(),
            simpleTrainPathApplication.getStartTime().toString(),
            simpleTrainPathApplication.getEndTime().toString(),
            PeriodicalTimeFrame
                    .formatDuration(simpleTrainPathApplication.getParams().getHARD_MAXIMUM_EARLIER_DEPARTURE()),
            PeriodicalTimeFrame
                    .formatDuration(simpleTrainPathApplication.getParams().getHARD_MAXIMUM_LATER_ARRIVAL()),
            PeriodicalTimeFrame
                    .formatDuration(simpleTrainPathApplication.getParams().getHARD_MINIMUM_DWELL_TIME()),
            String.valueOf(dag.nbPaths()), String.valueOf(dag.getCyclomaticComplexity()));

    table.finishTable();
    return data;
}

From source file:com.arpnetworking.metrics.mad.PeriodWorker.java

License:Apache License

/**
 * {@inheritDoc}//  www  .j av  a 2 s  .  c o  m
 */
@Override
public void run() {
    Thread.currentThread()
            .setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error().setMessage("Unhandled exception")
                    .addData("periodWorker", PeriodWorker.this).setThrowable(throwable).log());

    while (_isRunning) {
        try {
            DateTime now = DateTime.now();
            final DateTime rotateAt = getRotateAt(now);
            Duration timeToRotate = new Duration(now, rotateAt);
            while (_isRunning && timeToRotate.isLongerThan(Duration.ZERO)) {
                // Process records or sleep
                Record recordToProcess = _recordQueue.poll();
                if (recordToProcess != null) {
                    while (recordToProcess != null) {
                        process(recordToProcess);
                        recordToProcess = _recordQueue.poll();
                    }
                } else {
                    Thread.sleep(Math.min(timeToRotate.getMillis(), 100));
                }
                // Recompute time to close
                now = DateTime.now();
                timeToRotate = new Duration(now, rotateAt);
            }
            // Drain the record queue before rotating
            final List<Record> recordsToProcess = Lists.newArrayList();
            _recordQueue.drainTo(recordsToProcess);
            for (final Record recordToProcess : recordsToProcess) {
                process(recordToProcess);
            }
            // Rotate
            rotate(now);
        } catch (final InterruptedException e) {
            Thread.interrupted();
            LOGGER.warn().setMessage("Interrupted waiting to close buckets").setThrowable(e).log();
            // CHECKSTYLE.OFF: IllegalCatch - Top level catch to prevent thread death
        } catch (final Exception e) {
            // CHECKSTYLE.ON: IllegalCatch
            LOGGER.error().setMessage("Aggregator failure").addData("periodWorker", this).setThrowable(e).log();
        }
    }
}

From source file:com.boundary.metrics.vmware.poller.VMwarePerfPoller.java

License:Apache License

/**
 * Extracts performance metrics from Managed Objects on the monitored entity
 * /*from  w  w  w  . ja  v a 2 s. c  o  m*/
 * @throws MalformedURLException Bad URL
 * @throws RemoteException Endpoint exception
 * @throws InvalidPropertyFaultMsg Bad Property
 * @throws RuntimeFaultFaultMsg Runtime error
 * @throws SOAPFaultException WebServer error
 */
public void collectPerformanceData() throws MalformedURLException, RemoteException, InvalidPropertyFaultMsg,
        RuntimeFaultFaultMsg, SOAPFaultException {

    ManagedObjectReference root = client.getServiceContent().getRootFolder();

    // 'now' according to the server
    DateTime now = TimeUtils.toDateTime(client.getVimPort().currentTime(client.getServiceInstanceReference()));
    Duration serverSkew = new Duration(now, new DateTime());
    if (serverSkew.isLongerThan(Duration.standardSeconds(1))
            && (skew == null || skew.getStandardSeconds() != serverSkew.getStandardSeconds())) {
        LOG.warn("Server {} and local time skewed by {} seconds", client.getHost(),
                serverSkew.getStandardSeconds());
        skew = serverSkew;
    }
    if (lastPoll == null) {
        lastPoll = now.minusSeconds(20);
    }

    // Holder for all our newly found measurements
    // TODO set an upper size limit on measurements list
    List<Measurement> measurements = Lists.newArrayList();

    /*
    * A {@link PerfMetricId} consistents of the performance counter and
    * the instance it applies to.
    * 
    * In our particular case we are requesting for all of the instances
    * associated with the performance counter.
    * 
    * Will this work when we have a mix of VirtualMachine, HostSystem, and DataSource
    * managed objects.
    * 
    */
    List<PerfMetricId> perfMetricIds = Lists.newArrayList();
    for (String counterName : metrics.keySet()) {
        if (this.performanceCounterMap.containsKey(counterName)) {
            PerfMetricId metricId = new PerfMetricId();
            /* Get the ID for this counter. */
            metricId.setCounterId(this.performanceCounterMap.get(counterName));
            metricId.setInstance("*");
            perfMetricIds.add(metricId);
        }
    }

    GetMOREF getMOREFs = new GetMOREF(client);
    Map<String, ManagedObjectReference> entities = getMOREFs.inFolderByType(root, "VirtualMachine");

    for (Map.Entry<String, ManagedObjectReference> entity : entities.entrySet()) {
        ManagedObjectReference mor = entity.getValue();
        String entityName = entity.getKey();

        /*
        * Create the query specification for queryPerf().
        * Specify 5 minute rollup interval and CSV output format.
        */
        PerfQuerySpec querySpec = new PerfQuerySpec();
        querySpec.setEntity(mor);
        querySpec.setIntervalId(20);
        querySpec.setFormat("normal");
        querySpec.setStartTime(TimeUtils.toXMLGregorianCalendar(lastPoll));
        querySpec.setEndTime(TimeUtils.toXMLGregorianCalendar(now));
        querySpec.getMetricId().addAll(perfMetricIds);

        LOG.info("Entity: {}, MOR: {}-{}, Interval: {}, Format: {}, MetricIds: {}, Start: {}, End: {}",
                entityName, mor.getType(), mor.getValue(), querySpec.getIntervalId(), querySpec.getFormat(),
                FluentIterable.from(perfMetricIds).transform(toStringFunction), lastPoll, now);

        List<PerfEntityMetricBase> retrievedStats = client.getVimPort()
                .queryPerf(client.getServiceContent().getPerfManager(), ImmutableList.of(querySpec));

        /*
        * Cycle through the PerfEntityMetricBase objects. Each object contains
        * a set of statistics for a single ManagedEntity.
        */
        for (PerfEntityMetricBase singleEntityPerfStats : retrievedStats) {
            if (singleEntityPerfStats instanceof PerfEntityMetric) {
                PerfEntityMetric entityStats = (PerfEntityMetric) singleEntityPerfStats;
                List<PerfMetricSeries> metricValues = entityStats.getValue();
                List<PerfSampleInfo> sampleInfos = entityStats.getSampleInfo();

                for (int x = 0; x < metricValues.size(); x++) {
                    PerfMetricIntSeries metricReading = (PerfMetricIntSeries) metricValues.get(x);
                    PerfCounterInfo metricInfo = performanceCounterInfoMap
                            .get(metricReading.getId().getCounterId());
                    String metricFullName = toFullName.apply(metricInfo);
                    if (!sampleInfos.isEmpty()) {
                        PerfSampleInfo sampleInfo = sampleInfos.get(0);
                        DateTime sampleTime = TimeUtils.toDateTime(sampleInfo.getTimestamp());
                        Number sampleValue = metricReading.getValue().iterator().next();

                        if (skew != null) {
                            sampleTime = sampleTime.plusSeconds((int) skew.getStandardSeconds());
                        }

                        if (metricReading.getValue().size() > 1) {
                            LOG.warn("Metric {} has more than one value, only using the first", metricFullName);
                        }

                        String source = client.getName() + "-" + entityName;

                        if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("kiloBytes")) {
                            sampleValue = (long) sampleValue * 1024; // Convert KB to Bytes
                        } else if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("percent")) {
                            // Convert hundredth of a percent to a decimal percent
                            sampleValue = new Long((long) sampleValue).doubleValue() / 10000.0;
                        }
                        String name = metrics.get(metricFullName).getName();
                        if (name != null) {
                            Measurement measurement = Measurement.builder().setMetric(name).setSource(source)
                                    .setTimestamp(sampleTime).setMeasurement(sampleValue).build();
                            measurements.add(measurement);

                            LOG.info("{} @ {} = {} {}", metricFullName, sampleTime, sampleValue,
                                    metricInfo.getUnitInfo().getKey());
                        } else {
                            LOG.warn("Skipping collection of metric: {}", metricFullName);
                        }
                    } else {
                        LOG.warn("Didn't receive any samples when polling for {} on {} between {} and {}",
                                metricFullName, client.getHost(), lastPoll, now);
                    }
                }
            } else {
                LOG.error("Unrecognized performance entry type received: {}, ignoring",
                        singleEntityPerfStats.getClass().getName());
            }
        }
    }

    // Send metrics
    if (!measurements.isEmpty()) {
        metricsClient.addMeasurements(measurements);
    } else {
        LOG.warn("No measurements collected in last poll for {}", client.getHost());
    }

    // Reset lastPoll time
    lastPoll = now;
}

From source file:com.facebook.stats.AbstractCompositeCounter.java

License:Apache License

/**
 * Updates the current composite counter so that it is up to date with the
 * current timestamp.//from  www  .ja v a 2  s. c  om
 * <p/>
 * This should be called by any method that needs to have the most updated
 * view of the current set of counters.
 */
protected synchronized void trimIfNeeded() {
    Duration delta = new Duration(start, new DateTime()).minus(maxLength);

    if (delta.isLongerThan(Duration.ZERO)) {
        start = start.toDateTime().plus(delta);

        if (start.isAfter(end)) {
            end = start;
        }

        Iterator<C> iter = eventCounters.iterator();

        while (iter.hasNext()) {
            EventCounterIf<C> counter = iter.next();

            // trim any counter with an end up to and including start since our composite counter is
            // [start, ... and each counter is [..., end)
            if (!start.isBefore(counter.getEnd())) {
                iter.remove();
            } else {
                break;
            }
        }
    }
}

From source file:com.facebook.stats.EventRateImpl.java

License:Apache License

private Duration getPeriodSize() {
    // normalize by the time since server start
    ReadableDateTime now = new DateTime();
    Duration periodSize = new Duration(start, now);

    if (periodSize.isLongerThan(windowSize)) {
        return windowSize;
    } else {/*  ww  w .  j a  va 2 s .c  om*/
        return periodSize;
    }
}

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 w  w w  .j  av  a2 s .  c o m*/
 * @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.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows.java

License:Apache License

private SlidingWindows(Duration period, Duration size, Duration offset) {
    if (offset.isShorterThan(Duration.ZERO) || !offset.isShorterThan(period)
            || !size.isLongerThan(Duration.ZERO)) {
        throw new IllegalArgumentException(
                "SlidingWindows WindowingStrategies must have 0 <= offset < period and 0 < size");
    }/* ww w . ja v a  2 s .  c o m*/
    this.period = period;
    this.size = size;
    this.offset = offset;
}

From source file:com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows.java

License:Apache License

static Duration getDefaultPeriod(Duration size) {
    if (size.isLongerThan(Duration.standardHours(1))) {
        return Duration.standardHours(1);
    }/*  w w w. j a v  a2 s.co m*/
    if (size.isLongerThan(Duration.standardMinutes(1))) {
        return Duration.standardMinutes(1);
    }
    if (size.isLongerThan(Duration.standardSeconds(1))) {
        return Duration.standardSeconds(1);
    }
    return Duration.millis(1);
}

From source file:com.google.cloud.dataflow.sdk.util.FluentBackoff.java

License:Apache License

/**
 * Returns a copy of this {@link FluentBackoff} that instead uses the specified initial backoff
 * duration.//  w w w .  j a va  2 s.  c o  m
 *
 * <p>Does not modify this object.
 *
 * @see FluentBackoff
 */
public FluentBackoff withInitialBackoff(Duration initialBackoff) {
    checkArgument(initialBackoff.isLongerThan(Duration.ZERO),
            "initialBackoff %s must be at least 1 millisecond", initialBackoff);
    return new FluentBackoff(exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries);
}