Example usage for org.joda.time Duration getMillis

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

Introduction

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

Prototype

public long getMillis() 

Source Link

Document

Gets the length of this duration in milliseconds.

Usage

From source file:com.almende.pi5.common.PowerTimeLine.java

License:Apache License

/**
 * Make this TL discrete, returning the TL;
 * As a side effect, removes values outside the start and end times.
 *
 * @param start//  w w  w. j  av  a 2s .c  om
 *            the start
 * @param end
 *            the end
 * @param stepSize
 *            the step size
 * @return this
 */
@JsonIgnore
public PowerTimeLine discrete(final DateTime start, final DateTime end, final Duration stepSize) {
    final PowerTimeLine newTL = new PowerTimeLine();
    newTL.timestamp = this.timestamp;
    final ArrayList<PowerTime> steps = new ArrayList<PowerTime>();

    long offset = new Duration(timestamp, start).getMillis();
    Interval interval = stepSize.toIntervalFrom(start);
    while (interval.getEnd().isBefore(end) || interval.getEnd().isEqual(end)) {
        steps.add(new PowerTime(offset, 0));
        offset += interval.toDurationMillis();
        interval = stepSize.toIntervalFrom(timestamp.plusMillis((int) offset));
    }
    newTL.setSeries(steps);
    this.add(newTL).zeroBefore(start).zeroFrom(end);

    final Duration diff = new Duration(start, end);
    if (series.size() > (diff.getMillis() / stepSize.getMillis())) {
        int index = 0;
        long expectedOffset = new Duration(timestamp, start).getMillis() + stepSize.getMillis();
        while (index < series.size() - 1) {
            PowerTime pt = series.get(index);
            ArrayList<PowerTime> temp = new ArrayList<PowerTime>();

            int nextIndex = index + 1;
            PowerTime next = series.get(nextIndex);
            while (next.getOffset() < expectedOffset) {
                temp.add(next);
                series.remove(nextIndex);
                if (nextIndex == series.size()) {
                    break;
                }
                next = series.get(nextIndex);
            }
            if (temp.size() > 0) {
                temp.add(0, pt);
                double integral = getIntegral(pt.getOffset(), pt.getOffset() + stepSize.getMillis(), temp);
                series.set(index, new PowerTime(pt.getOffset(), integral / stepSize.getMillis()));
            }
            index++;
            expectedOffset += stepSize.getMillis();
        }
    }

    return this;
}

From source file:com.anrisoftware.globalpom.threads.watchdog.ThreadsWatchdog.java

License:Open Source License

/**
 * @see Threads#waitForTasks(Duration)//  ww w .j a  va 2s . c  om
 */
public List<Future<?>> waitForTasks(Duration timeout) throws InterruptedException {
    while (tasks.size() > 0) {
        synchronized (this) {
            wait(timeout.getMillis());
            if (notified) {
                notified = false;
            } else {
                break;
            }
        }
    }
    return tasks;
}

From source file:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

License:Open Source License

/**
 * Sets the timeout for the process./*  ww  w.j ava 2  s  . c  o  m*/
 * 
 * @param object
 *            the {@link Duration} of the timeout; or the {@link Number}
 *            timeout in milliseconds; or an {@link Object} that is parsed
 *            as the duration.
 * 
 * @throws CommandException
 *             if any errors set the timeout watchdog.
 * 
 * @throws IllegalArgumentException
 *             if the parsed duration is not valid.
 */
public void setTimeout(Object object) throws CommandException {
    if (object instanceof Duration) {
        Duration timeout = (Duration) object;
        setWatchdog(new ExecuteWatchdog(timeout.getMillis()));
    } else if (object instanceof Number) {
        Number timeout = (Number) object;
        setWatchdog(new ExecuteWatchdog(timeout.longValue()));
    } else {
        Duration timeout = Duration.parse(object.toString());
        setWatchdog(new ExecuteWatchdog(timeout.getMillis()));
    }
}

From source file:com.anrisoftware.simplerest.core.AbstractRepeatSimpleGetWorker.java

License:Open Source License

@Override
protected T repeatRequest(CloseableHttpResponse previouslyResponse, HttpRequest previouslyRequest,
        StatusLine previouslyStatusLine) throws SimpleRestException {
    int repeateCount = requestsRepeateCount;
    int repeateMax = requestsRepeateMax;
    Duration repeateWait = requestsRepeateWait;
    if (repeateCount == repeateMax) {
        throw parseErrorMessage(previouslyRequest, previouslyResponse, previouslyStatusLine);
    }//  w w w. j a va2 s .c o  m
    try {
        log.repeatRequestsSleep(parent, repeateCount, repeateWait);
        Thread.sleep(repeateWait.getMillis());
    } catch (InterruptedException e) {
        return null;
    }
    CloseableHttpClient httpclient = createHttpClient();
    HttpGet httpget = createHttpGet();
    CloseableHttpResponse response = executeRequest(httpclient, httpget);
    StatusLine statusLine = response.getStatusLine();
    repeateCount++;
    repeateWait = repeateWait.plus(requestsRepeateWaitDuration);
    this.requestsRepeateCount = repeateCount;
    this.requestsRepeateWait = repeateWait;
    return parseResponse(response, httpget, statusLine);
}

From source file:com.anrisoftware.sscontrol.httpd.nginx.nginx.linux.SimpleDurationRenderer.java

License:Open Source License

@Override
public String toString(Object o, String formatString, Locale locale) {
    Duration duration = (Duration) o;
    if (StringUtils.equals(formatString, SIMPLE_ROUND_KEY)) {
        return DurationSimpleFormat.roundSizeUnit(duration.getMillis());
    }/*  w ww  . j  ava  2  s  . com*/
    if (startsWith(formatString, SIMPLE_KEY)) {
        return toStringSimple(formatString, duration);
    } else {
        return duration.toString();
    }
}

From source file:com.anrisoftware.sscontrol.mail.postfix.linux.DurationRenderer.java

License:Open Source License

@Override
public String toString(Object o, String format, Locale locale) {
    Duration duration = (Duration) o;
    long time = duration.getMillis() / 1000;
    if (time > 1 * WEEKS && time % WEEKS == 0) {
        return format("%dw", time / WEEKS);
    }/*from w w  w .j a v  a  2  s  .  c om*/
    if (time > 1 * DAYS && time % DAYS == 0) {
        return format("%dd", time / DAYS);
    }
    if (time > 1 * HOUR && time % HOUR == 0) {
        return format("%dh", time / HOUR);
    }
    if (time > 1 * MINUTES && time % MINUTES == 0) {
        return format("%dm", time / MINUTES);
    }
    return format("%ds", time);
}

From source file:com.arpnetworking.metrics.mad.performance.FilePerfTestBase.java

License:Apache License

/**
 * Runs a filter./* w  ww  .ja  v  a2  s . c  o m*/
 *
 * @param pipelineConfigurationFile Pipeline configuration file.
 * @param duration Timeout period.
 * @param variables Substitution key-value pairs into pipeline configuration file.
 * @throws IOException if configuration cannot be loaded.
 */
protected void benchmark(final String pipelineConfigurationFile, final Duration duration,
        final ImmutableMap<String, String> variables) throws IOException {
    // Replace any variables in the configuration file
    String configuration = Resources.toString(Resources.getResource(pipelineConfigurationFile), Charsets.UTF_8);
    for (final Map.Entry<String, String> entry : variables.entrySet()) {
        configuration = configuration.replace(entry.getKey(), entry.getValue());
    }

    // Load the specified stock configuration
    final PipelineConfiguration stockPipelineConfiguration = new StaticConfiguration.Builder()
            .addSource(new JsonNodeLiteralSource.Builder().setSource(configuration).build())
            .setObjectMapper(PipelineConfiguration.createObjectMapper(_injector)).build()
            .getRequiredAs(PipelineConfiguration.class);

    // Canary tracking
    LOGGER.info(String.format("Expected canaries; periods=%s", stockPipelineConfiguration.getPeriods()));
    final CountDownLatch latch = new CountDownLatch(stockPipelineConfiguration.getPeriods().size());
    final Set<Period> periods = Sets.newConcurrentHashSet();

    // Create custom "canary" sink
    final ListeningSink sink = new ListeningSink((periodicData) -> {
        if (periodicData != null) {
            for (final String metricName : periodicData.getData().keys()) {
                if (TestFileGenerator.CANARY.equals(metricName)) {
                    if (periods.add(periodicData.getPeriod())) {
                        LOGGER.info(String.format("Canary flew; filter=%s, period=%s", this.getClass(),
                                periodicData.getPeriod()));
                        latch.countDown();
                    }
                }
            }
        }
        return null;
    });

    // Add the custom "canary" sink
    final List<Sink> benchmarkSinks = Lists.newArrayList(stockPipelineConfiguration.getSinks());
    benchmarkSinks.add(sink);

    // Create the custom configuration
    final PipelineConfiguration benchmarkPipelineConfiguration = OvalBuilder.<PipelineConfiguration, PipelineConfiguration.Builder>clone(
            stockPipelineConfiguration).setSinks(benchmarkSinks).build();

    // Instantiate the pipeline
    final Pipeline pipeline = new Pipeline(benchmarkPipelineConfiguration);

    // Execute the pipeline until the canary flies the coop
    try {
        LOGGER.debug(String.format("Launching pipeline; configuration=%s", pipelineConfigurationFile));
        final Stopwatch timer = Stopwatch.createUnstarted();
        timer.start();
        pipeline.launch();

        if (!latch.await(duration.getMillis(), TimeUnit.MILLISECONDS)) {
            LOGGER.error("Test timed out");
            throw new RuntimeException("Test timed out");
        }

        timer.stop();
        LOGGER.info(String.format("Performance filter result; filter=%s, seconds=%s", this.getClass(),
                timer.elapsed(TimeUnit.SECONDS)));

    } catch (final InterruptedException e) {
        Thread.interrupted();
        throw new RuntimeException("Test interrupted");
    } finally {
        pipeline.shutdown();
    }
}

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

License:Apache License

/**
 * {@inheritDoc}//from  w w w  . ja  v  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.arpnetworking.tsdaggregator.perf.FilePerfTestBase.java

License:Apache License

/**
 * Runs a test.//w  w w  .jav  a  2  s . c  om
 *
 * @param pipelineConfigurationFile Pipeline configuration file.
 * @param duration Timeout period.
 */
protected void benchmark(final File pipelineConfigurationFile, final Duration duration) {
    LOGGER.debug(String.format("Launching pipeline; configuration=%s", pipelineConfigurationFile));

    // Create custom "canary" sink
    final CountDownLatch latch = new CountDownLatch(1);
    final Stopwatch timer = Stopwatch.createUnstarted();
    final ListeningSink sink = new ListeningSink(new Function<Collection<AggregatedData>, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable final Collection<AggregatedData> input) {
            if (input != null) {
                final AggregatedData datum = Iterables.getFirst(input, null);
                if (datum != null && TestFileGenerator.CANARY.equals(datum.getFQDSN().getMetric())
                        && timer.isRunning()) {
                    timer.stop();
                    latch.countDown();
                }
            }
            return null;
        }
    });

    // Load the specified stock configuration
    final PipelineConfiguration stockPipelineConfiguration = new StaticConfiguration.Builder()
            .addSource(new JsonNodeFileSource.Builder().setFile(pipelineConfigurationFile).build())
            .setObjectMapper(PipelineConfiguration.createObjectMapper(_injector)).build()
            .getRequiredAs(PipelineConfiguration.class);

    // Add the custom "canary" sink
    final List<Sink> benchmarkSinks = Lists.newArrayList(stockPipelineConfiguration.getSinks());
    benchmarkSinks.add(sink);

    // Create the custom configuration
    final PipelineConfiguration benchmarkPipelineConfiguration = OvalBuilder.<PipelineConfiguration, PipelineConfiguration.Builder>clone(
            stockPipelineConfiguration).setSinks(benchmarkSinks).build();

    // Instantiate the pipeline
    final Pipeline pipeline = new Pipeline(benchmarkPipelineConfiguration);

    // Execute the pipeline until the canary flies the coop
    try {
        timer.start();
        pipeline.launch();

        if (!latch.await(duration.getMillis(), TimeUnit.MILLISECONDS)) {
            LOGGER.error("Test timed out");
            throw new RuntimeException("Test timed out");
        }
    } catch (final InterruptedException e) {
        Thread.interrupted();
        throw new RuntimeException("Test interrupted");
    } finally {
        pipeline.shutdown();
    }
}

From source file:com.astonish.dropwizard.routing.migrations.AbstractRoutingLiquibaseCommand.java

License:Apache License

@Override
protected void run(Bootstrap<T> bootstrap, Namespace namespace, T configuration) throws Exception {
    final String routeName = (String) namespace.get("routeName");

    LOGGER.warn("routeName = {}", routeName);

    // if route is specified then only run the liquibase command against that route
    if (null != routeName) {
        final ImmutableList<DataSourceRoute> routes = strategy.getDataSourceRoutes(configuration);

        for (DataSourceRoute route : routes) {
            if (routeName.equals(route.getRouteName())) {
                LOGGER.warn("Running for route: {}", route.getRouteName());
                run(route, namespace, configuration);
            }//from   ww  w  .  j  a  v a2  s .  c o  m
        }
    } else {
        LOGGER.warn("running for all routes");
        // run against all routes
        final ExecutorService executor = Executors.newFixedThreadPool((Integer) namespace.get("threads"));

        final List<Future<?>> futures = new ArrayList<>();
        for (DataSourceRoute route : strategy.getDataSourceRoutes(configuration)) {
            try {
                LOGGER.warn("Add Future task for route: {}", route.getRouteName());
                Runnable runnable = new ThreadableCommand<T>(this, route, namespace);
                Future<?> future = executor.submit(runnable);
                futures.add(future);
            } catch (RejectedExecutionException e) {
                LOGGER.error("RejectedExecutionException while submitting runnable to executor", e);
            } catch (Exception e) {
                LOGGER.error("Who the F*$# knows what happened here...", e);
                throw e;
            }
        }

        LOGGER.warn("Shutting down executor service");
        executor.shutdown();

        final Duration timeLimit = ISOPeriodFormat.standard().parsePeriod(namespace.getString("timeLimit"))
                .toStandardDuration();

        try {
            LOGGER.warn("Start executor.awaitTermination({})", timeLimit.getMillis());
            executor.awaitTermination(timeLimit.getMillis(), TimeUnit.MILLISECONDS);
            LOGGER.warn("End executor.awaitTermination({})", timeLimit.getMillis());
        } catch (Throwable t) {
            LOGGER.error("Catching ANYTHING in executor.awaitTermination and rethrowing it!", t);
            throw t;
        }

        for (final Future<?> future : futures) {
            LOGGER.warn("Start future.get() Timestamp: {}", System.currentTimeMillis());
            try {
                future.get();
            } catch (Throwable t) {
                LOGGER.error("Catching ANYTHING in future.get() and rethrowing it!", t);
                throw t;
            }
            LOGGER.warn("End future.get() Timestamp: {}", System.currentTimeMillis());
        }
    }
}