java.util.concurrent.TimeUnit

Here are the examples of the java api class java.util.concurrent.TimeUnit taken from open source projects.

1. NewRelicReporterFactoryBean#createInstance()

View license
@Override
protected NewRelicReporter createInstance() throws Exception {
    String prefix = this.getProperty(PREFIX, String.class, EMPTY_STRING);
    MetricFilter metricFilter = getMetricFilter();
    TimeUnit duration = this.getProperty(DURATION_UNIT, TimeUnit.class, TimeUnit.MILLISECONDS);
    TimeUnit rateUnit = this.getProperty(RATE_UNIT, TimeUnit.class, TimeUnit.SECONDS);
    String name = this.getProperty(NAME, String.class, "NewRelic reporter");
    MetricAttributeFilter attributeFilter = this.hasProperty(ATTRIBUTE_FILTER) ? this.getPropertyRef(ATTRIBUTE_FILTER, MetricAttributeFilter.class) : new AllEnabledMetricAttributeFilter();
    LOG.debug("Creating instance of NewRelicReporter with name '{}', prefix '{}', rate unit '{}', duration '{}', filter '{}' and attribute filter '{}'", name, prefix, rateUnit, duration, metricFilter, attributeFilter.getClass().getSimpleName());
    return NewRelicReporter.forRegistry(this.getMetricRegistry()).name(name).filter(metricFilter).attributeFilter(attributeFilter).rateUnit(rateUnit).durationUnit(duration).metricNamePrefix(prefix).build();
}

2. Janitor#start()

Project: killbill
Source File: Janitor.java
View license
public void start() {
    this.isStopped = false;
    janitorExecutor = paymentExecutors.getJanitorExecutorService();
    janitorQueue.startQueue();
    // Start task for completing incomplete payment attempts
    final TimeUnit attemptCompletionRateUnit = paymentConfig.getJanitorRunningRate().getUnit();
    final long attemptCompletionPeriod = paymentConfig.getJanitorRunningRate().getPeriod();
    janitorExecutor.scheduleAtFixedRate(incompletePaymentAttemptTask, attemptCompletionPeriod, attemptCompletionPeriod, attemptCompletionRateUnit);
    // Start task for completing incomplete payment attempts
    final TimeUnit erroredCompletionRateUnit = paymentConfig.getJanitorRunningRate().getUnit();
    final long erroredCompletionPeriod = paymentConfig.getJanitorRunningRate().getPeriod();
    janitorExecutor.scheduleAtFixedRate(incompletePaymentTransactionTask, erroredCompletionPeriod, erroredCompletionPeriod, erroredCompletionRateUnit);
}

3. Slf4jReporterStarter#start()

View license
@Override
public List<AutoCloseable> start(Params params) {
    Configuration config = new FluoConfiguration(params.getConfiguration()).getReporterConfiguration("slf4j");
    if (!config.getBoolean("enable", false)) {
        return Collections.emptyList();
    }
    TimeUnit rateUnit = TimeUnit.valueOf(config.getString("rateUnit", "seconds").toUpperCase());
    TimeUnit durationUnit = TimeUnit.valueOf(config.getString("durationUnit", "milliseconds").toUpperCase());
    Logger logger = LoggerFactory.getLogger(config.getString("logger", "metrics"));
    Slf4jReporter reporter = Slf4jReporter.forRegistry(params.getMetricRegistry()).convertDurationsTo(durationUnit).convertRatesTo(rateUnit).outputTo(logger).build();
    reporter.start(config.getInt("frequency", 60), TimeUnit.SECONDS);
    log.info("Reporting metrics using slf4j");
    return Collections.singletonList((AutoCloseable) reporter);
}

4. JmxReporterStarter#start()

View license
@Override
public List<AutoCloseable> start(Params params) {
    Configuration config = new FluoConfiguration(params.getConfiguration()).getReporterConfiguration("jmx");
    if (!config.getBoolean("enable", false)) {
        return Collections.emptyList();
    }
    TimeUnit rateUnit = TimeUnit.valueOf(config.getString("rateUnit", "seconds").toUpperCase());
    TimeUnit durationUnit = TimeUnit.valueOf(config.getString("durationUnit", "milliseconds").toUpperCase());
    JmxReporter reporter = JmxReporter.forRegistry(params.getMetricRegistry()).convertDurationsTo(durationUnit).convertRatesTo(rateUnit).inDomain(params.getDomain()).build();
    reporter.start();
    log.info("Reporting metrics to JMX");
    return Collections.singletonList((AutoCloseable) reporter);
}

5. CsvReporterStarter#start()

View license
@Override
public List<AutoCloseable> start(Params params) {
    Configuration config = new FluoConfiguration(params.getConfiguration()).getReporterConfiguration("csv");
    String dir = config.getString("dir", "");
    if (!config.getBoolean("enable", false) || dir.isEmpty()) {
        return Collections.emptyList();
    }
    TimeUnit rateUnit = TimeUnit.valueOf(config.getString("rateUnit", "seconds").toUpperCase());
    TimeUnit durationUnit = TimeUnit.valueOf(config.getString("durationUnit", "milliseconds").toUpperCase());
    CsvReporter reporter = CsvReporter.forRegistry(params.getMetricRegistry()).convertDurationsTo(durationUnit).convertRatesTo(rateUnit).build(new File(dir));
    reporter.start(config.getInt("frequency", 60), TimeUnit.SECONDS);
    log.info("Reporting metrics as csv to directory {}", dir);
    return Collections.singletonList((AutoCloseable) reporter);
}

6. OperationTest#testWaitForWithTimeout()

Project: gcloud-java
Source File: OperationTest.java
View license
@Test
public void testWaitForWithTimeout() throws InterruptedException, TimeoutException {
    initializeExpectedOperation(4);
    Compute.OperationOption[] expectedOptions = { Compute.OperationOption.fields(Compute.OperationField.STATUS) };
    TimeUnit timeUnit = createStrictMock(TimeUnit.class);
    timeUnit.sleep(1);
    EasyMock.expectLastCall();
    Clock clock = createStrictMock(Clock.class);
    expect(clock.millis()).andReturn(0L);
    expect(clock.millis()).andReturn(1L);
    expect(clock.millis()).andReturn(3L);
    Operation runningOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null).setStatus("RUNNING"));
    expect(compute.options()).andReturn(mockOptions);
    expect(mockOptions.clock()).andReturn(clock);
    expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation);
    expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation);
    replay(compute, timeUnit, clock, mockOptions);
    initializeOperation();
    thrown.expect(TimeoutException.class);
    operation.waitFor(WaitForOption.checkEvery(1, timeUnit), WaitForOption.timeout(3, TimeUnit.MILLISECONDS));
    verify(compute, timeUnit, clock, mockOptions);
}

7. OperationTest#testWaitForCheckingPeriod_Null()

Project: gcloud-java
Source File: OperationTest.java
View license
@Test
public void testWaitForCheckingPeriod_Null() throws InterruptedException, TimeoutException {
    initializeExpectedOperation(4);
    Compute.OperationOption[] expectedOptions = { Compute.OperationOption.fields(Compute.OperationField.STATUS) };
    TimeUnit timeUnit = createStrictMock(TimeUnit.class);
    timeUnit.sleep(42);
    EasyMock.expectLastCall();
    Operation runningOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null).setStatus("RUNNING"));
    expect(compute.options()).andReturn(mockOptions);
    expect(mockOptions.clock()).andReturn(Clock.defaultClock());
    expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation);
    expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(null);
    expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(null);
    replay(compute, timeUnit, mockOptions);
    initializeOperation();
    assertNull(operation.waitFor(WaitForOption.checkEvery(42, timeUnit)));
    verify(compute, timeUnit, mockOptions);
}

8. OperationTest#testWaitForCheckingPeriod()

Project: gcloud-java
Source File: OperationTest.java
View license
@Test
public void testWaitForCheckingPeriod() throws InterruptedException, TimeoutException {
    initializeExpectedOperation(5);
    Compute.OperationOption[] expectedOptions = { Compute.OperationOption.fields(Compute.OperationField.STATUS) };
    TimeUnit timeUnit = createStrictMock(TimeUnit.class);
    timeUnit.sleep(42);
    EasyMock.expectLastCall();
    Operation runningOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null).setStatus("RUNNING"));
    Operation completedOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null));
    expect(compute.options()).andReturn(mockOptions);
    expect(mockOptions.clock()).andReturn(Clock.defaultClock());
    expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation);
    expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(completedOperation);
    expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(completedOperation);
    replay(compute, timeUnit, mockOptions);
    initializeOperation();
    assertSame(completedOperation, operation.waitFor(WaitForOption.checkEvery(42, timeUnit)));
    verify(timeUnit, mockOptions);
}

9. JobTest#testWaitForWithCheckingPeriod_Null()

Project: gcloud-java
Source File: JobTest.java
View license
@Test
public void testWaitForWithCheckingPeriod_Null() throws InterruptedException, TimeoutException {
    initializeExpectedJob(2);
    BigQuery.JobOption[] expectedOptions = { BigQuery.JobOption.fields(BigQuery.JobField.STATUS) };
    TimeUnit timeUnit = createStrictMock(TimeUnit.class);
    timeUnit.sleep(42);
    EasyMock.expectLastCall();
    expect(bigquery.options()).andReturn(mockOptions);
    expect(mockOptions.clock()).andReturn(Clock.defaultClock());
    Job runningJob = expectedJob.toBuilder().status(new JobStatus(JobStatus.State.RUNNING)).build();
    expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob);
    expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null);
    expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(null);
    replay(bigquery, timeUnit, mockOptions);
    initializeJob();
    assertNull(job.waitFor(WaitForOption.checkEvery(42, timeUnit)));
    verify(bigquery, timeUnit, mockOptions);
}

10. JobTest#testWaitForWithCheckingPeriod()

Project: gcloud-java
Source File: JobTest.java
View license
@Test
public void testWaitForWithCheckingPeriod() throws InterruptedException, TimeoutException {
    initializeExpectedJob(3);
    BigQuery.JobOption[] expectedOptions = { BigQuery.JobOption.fields(BigQuery.JobField.STATUS) };
    TimeUnit timeUnit = createStrictMock(TimeUnit.class);
    timeUnit.sleep(42);
    EasyMock.expectLastCall();
    JobStatus status = createStrictMock(JobStatus.class);
    expect(status.state()).andReturn(JobStatus.State.RUNNING);
    expect(status.state()).andReturn(JobStatus.State.DONE);
    expect(bigquery.options()).andReturn(mockOptions);
    expect(mockOptions.clock()).andReturn(Clock.defaultClock());
    Job runningJob = expectedJob.toBuilder().status(status).build();
    Job completedJob = expectedJob.toBuilder().status(status).build();
    expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob);
    expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(completedJob);
    expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(completedJob);
    replay(status, bigquery, timeUnit, mockOptions);
    initializeJob();
    assertSame(completedJob, job.waitFor(WaitForOption.checkEvery(42, timeUnit)));
    verify(status, timeUnit, mockOptions);
}

11. ShortDuration#createAbbreviations()

Project: caliper
Source File: ShortDuration.java
View license
private static ImmutableListMultimap<TimeUnit, String> createAbbreviations() {
    ImmutableListMultimap.Builder<TimeUnit, String> builder = ImmutableListMultimap.builder();
    builder.putAll(TimeUnit.NANOSECONDS, "ns", "nanos");
    builder.putAll(TimeUnit.MICROSECONDS, "?s", /*?s*/
    "us", "micros");
    builder.putAll(TimeUnit.MILLISECONDS, "ms", "millis");
    builder.putAll(TimeUnit.SECONDS, "s", "sec");
    // Do the rest in a JDK5-safe way
    TimeUnit[] allUnits = TimeUnit.values();
    if (allUnits.length >= 7) {
        builder.putAll(allUnits[4], "m", "min");
        builder.putAll(allUnits[5], "h", "hr");
        builder.putAll(allUnits[6], "d");
    }
    for (TimeUnit unit : TimeUnit.values()) {
        builder.put(unit, Ascii.toLowerCase(unit.name()));
    }
    return builder.build();
}

12. CsvPreparableReporter#prepare()

View license
@Override
public void prepare(MetricRegistry metricsRegistry, Map stormConf) {
    LOG.debug("Preparing...");
    CsvReporter.Builder builder = CsvReporter.forRegistry(metricsRegistry);
    Locale locale = MetricsUtils.getMetricsReporterLocale(stormConf);
    if (locale != null) {
        builder.formatFor(locale);
    }
    TimeUnit rateUnit = MetricsUtils.getMetricsRateUnit(stormConf);
    if (rateUnit != null) {
        builder.convertRatesTo(rateUnit);
    }
    TimeUnit durationUnit = MetricsUtils.getMetricsDurationUnit(stormConf);
    if (durationUnit != null) {
        builder.convertDurationsTo(durationUnit);
    }
    File csvMetricsDir = MetricsUtils.getCsvLogDir(stormConf);
    reporter = builder.build(csvMetricsDir);
}

13. ConsolePreparableReporter#prepare()

View license
@Override
public void prepare(MetricRegistry metricsRegistry, Map stormConf) {
    LOG.debug("Preparing...");
    ConsoleReporter.Builder builder = ConsoleReporter.forRegistry(metricsRegistry);
    builder.outputTo(System.out);
    Locale locale = MetricsUtils.getMetricsReporterLocale(stormConf);
    if (locale != null) {
        builder.formattedFor(locale);
    }
    TimeUnit rateUnit = MetricsUtils.getMetricsRateUnit(stormConf);
    if (rateUnit != null) {
        builder.convertRatesTo(rateUnit);
    }
    TimeUnit durationUnit = MetricsUtils.getMetricsDurationUnit(stormConf);
    if (durationUnit != null) {
        builder.convertDurationsTo(durationUnit);
    }
    reporter = builder.build();
}

14. Duration#convertToMostSuccinctTimeUnit()

Project: airlift
Source File: Duration.java
View license
public Duration convertToMostSuccinctTimeUnit() {
    TimeUnit unitToUse = NANOSECONDS;
    for (TimeUnit unitToTest : TimeUnit.values()) {
        // since time units are powers of ten, we can get rounding errors here, so fuzzy match
        if (getValue(unitToTest) > 0.9999) {
            unitToUse = unitToTest;
        } else {
            break;
        }
    }
    return convertTo(unitToUse);
}

15. MoreCollectorsTest#testToEnumSet()

Project: streamex
Source File: MoreCollectorsTest.java
View license
@Test
public void testToEnumSet() {
    TimeUnit[] vals = TimeUnit.values();
    List<TimeUnit> enumValues = IntStreamEx.range(100).map( x -> x % vals.length).elements(vals).toList();
    checkShortCircuitCollector("toEnumSet", EnumSet.allOf(TimeUnit.class), vals.length, enumValues::stream, MoreCollectors.toEnumSet(TimeUnit.class));
    enumValues = IntStreamEx.range(100).map( x -> x % (vals.length - 1)).elements(vals).toList();
    EnumSet<TimeUnit> expected = EnumSet.allOf(TimeUnit.class);
    expected.remove(vals[vals.length - 1]);
    checkShortCircuitCollector("toEnumSet", expected, 100, enumValues::stream, MoreCollectors.toEnumSet(TimeUnit.class));
    checkCollectorEmpty("Empty", EnumSet.noneOf(TimeUnit.class), MoreCollectors.toEnumSet(TimeUnit.class));
}

16. ExecutionEngineImpl#activate()

Project: sling
Source File: ExecutionEngineImpl.java
View license
protected void activate(ComponentContext context) {
    corePoolSize = getIntegerProperty(context, PROP_CORE_POOL_SIZE);
    maximumPoolSize = getIntegerProperty(context, PROP_MAX_POOL_SIZE);
    keepAliveTimeSeconds = getIntegerProperty(context, PROP_KEEP_ALIVE_TIME);
    TimeUnit unit = TimeUnit.SECONDS;
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(4);
    RejectedExecutionHandler handler = new RejectedExecutionHandler() {

        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            onJobRejected(r);
        }
    };
    log.info("ThreadPoolExecutor configuration: corePoolSize = {}, maxPoolSize={}, keepAliveTimeSeconds={}", new Object[] { corePoolSize, maximumPoolSize, keepAliveTimeSeconds });
    executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeSeconds, unit, workQueue, handler);
}

17. CreateTableTest#failOnUnsupportedTimeUnits()

View license
@Test
public void failOnUnsupportedTimeUnits() throws ExecutionException, InterruptedException {
    final EnumSet<TimeUnit> supported = EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS);
    final EnumSet<TimeUnit> notSupported = EnumSet.complementOf(supported);
    for (TimeUnit tu : notSupported) {
        try {
            verifyTableCreation(tableDefinition, 10, tu, "");
        } catch (IllegalArgumentException ex) {
            assertTrue(ex.getMessage().startsWith("Unsupported quantum unit"));
            continue;
        }
        fail("In case of using unsupported time unit IllegalArgumentException must be thrown");
    }
}

18. EmailReportJob#calculateGraphDataStart()

Project: pinot
Source File: EmailReportJob.java
View license
private DateTime calculateGraphDataStart(DateTime start, DateTime end, TimeGranularity bucketGranularity) {
    TimeUnit unit = bucketGranularity.getUnit();
    long minUnits;
    if (TimeUnit.DAYS.equals(unit)) {
        minUnits = MINIMUM_GRAPH_WINDOW_DAYS;
    } else if (TimeUnit.HOURS.equals(unit)) {
        minUnits = MINIMUM_GRAPH_WINDOW_HOURS;
    } else {
        // no need to do calculation, return input start;
        return start;
    }
    long currentUnits = unit.convert(end.getMillis() - start.getMillis(), TimeUnit.MILLISECONDS);
    if (currentUnits < minUnits) {
        LOG.info("Overriding config window size {} {} with minimum default of {}", currentUnits, unit, minUnits);
        start = end.minus(unit.toMillis(minUnits));
    }
    return start;
}

19. ZKMetadataUtils#extractTimeUnitFromDuration()

Project: pinot
Source File: ZKMetadataUtils.java
View license
private static TimeUnit extractTimeUnitFromDuration(Duration timeGranularity) {
    if (timeGranularity == null) {
        return null;
    }
    long timeUnitInMills = timeGranularity.getMillis();
    for (TimeUnit timeUnit : TimeUnit.values()) {
        if (timeUnit.toMillis(1) == timeUnitInMills) {
            return timeUnit;
        }
    }
    return null;
}

20. TimeUnitTest#testToHoursSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * toHours saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testToHoursSaturate() {
    for (TimeUnit x : TimeUnit.values()) {
        long ratio = x.toNanos(1) / HOURS.toNanos(1);
        if (ratio >= 1) {
            long max = Long.MAX_VALUE / ratio;
            for (long z : new long[] { 0, 1, -1, max, -max }) assertEquals(z * ratio, x.toHours(z));
            if (max < Long.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toHours(max + 1));
                assertEquals(Long.MIN_VALUE, x.toHours(-max - 1));
                assertEquals(Long.MIN_VALUE, x.toHours(Long.MIN_VALUE + 1));
            }
            assertEquals(Long.MAX_VALUE, x.toHours(Long.MAX_VALUE));
            assertEquals(Long.MIN_VALUE, x.toHours(Long.MIN_VALUE));
        }
    }
}

21. TimeUnitTest#testToMinutesSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * toMinutes saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testToMinutesSaturate() {
    for (TimeUnit x : TimeUnit.values()) {
        long ratio = x.toNanos(1) / MINUTES.toNanos(1);
        if (ratio > 1) {
            long max = Long.MAX_VALUE / ratio;
            for (long z : new long[] { 0, 1, -1, max, -max }) assertEquals(z * ratio, x.toMinutes(z));
            assertEquals(Long.MAX_VALUE, x.toMinutes(max + 1));
            assertEquals(Long.MIN_VALUE, x.toMinutes(-max - 1));
            assertEquals(Long.MAX_VALUE, x.toMinutes(Long.MAX_VALUE));
            assertEquals(Long.MIN_VALUE, x.toMinutes(Long.MIN_VALUE));
            assertEquals(Long.MIN_VALUE, x.toMinutes(Long.MIN_VALUE + 1));
        }
    }
}

22. TimeUnitTest#testToSecondsSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * toSeconds saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testToSecondsSaturate() {
    for (TimeUnit x : TimeUnit.values()) {
        long ratio = x.toNanos(1) / SECONDS.toNanos(1);
        if (ratio >= 1) {
            long max = Long.MAX_VALUE / ratio;
            for (long z : new long[] { 0, 1, -1, max, -max }) assertEquals(z * ratio, x.toSeconds(z));
            if (max < Long.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toSeconds(max + 1));
                assertEquals(Long.MIN_VALUE, x.toSeconds(-max - 1));
                assertEquals(Long.MIN_VALUE, x.toSeconds(Long.MIN_VALUE + 1));
            }
            assertEquals(Long.MAX_VALUE, x.toSeconds(Long.MAX_VALUE));
            assertEquals(Long.MIN_VALUE, x.toSeconds(Long.MIN_VALUE));
            if (max < Integer.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toSeconds(Integer.MAX_VALUE));
                assertEquals(Long.MIN_VALUE, x.toSeconds(Integer.MIN_VALUE));
            }
        }
    }
}

23. TimeUnitTest#testToMillisSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * toMillis saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testToMillisSaturate() {
    for (TimeUnit x : TimeUnit.values()) {
        long ratio = x.toNanos(1) / MILLISECONDS.toNanos(1);
        if (ratio >= 1) {
            long max = Long.MAX_VALUE / ratio;
            for (long z : new long[] { 0, 1, -1, max, -max }) assertEquals(z * ratio, x.toMillis(z));
            if (max < Long.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toMillis(max + 1));
                assertEquals(Long.MIN_VALUE, x.toMillis(-max - 1));
                assertEquals(Long.MIN_VALUE, x.toMillis(Long.MIN_VALUE + 1));
            }
            assertEquals(Long.MAX_VALUE, x.toMillis(Long.MAX_VALUE));
            assertEquals(Long.MIN_VALUE, x.toMillis(Long.MIN_VALUE));
            if (max < Integer.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toMillis(Integer.MAX_VALUE));
                assertEquals(Long.MIN_VALUE, x.toMillis(Integer.MIN_VALUE));
            }
        }
    }
}

24. TimeUnitTest#testToMicrosSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * toMicros saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testToMicrosSaturate() {
    for (TimeUnit x : TimeUnit.values()) {
        long ratio = x.toNanos(1) / MICROSECONDS.toNanos(1);
        if (ratio >= 1) {
            long max = Long.MAX_VALUE / ratio;
            for (long z : new long[] { 0, 1, -1, max, -max }) assertEquals(z * ratio, x.toMicros(z));
            if (max < Long.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toMicros(max + 1));
                assertEquals(Long.MIN_VALUE, x.toMicros(-max - 1));
                assertEquals(Long.MIN_VALUE, x.toMicros(Long.MIN_VALUE + 1));
            }
            assertEquals(Long.MAX_VALUE, x.toMicros(Long.MAX_VALUE));
            assertEquals(Long.MIN_VALUE, x.toMicros(Long.MIN_VALUE));
            if (max < Integer.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toMicros(Integer.MAX_VALUE));
                assertEquals(Long.MIN_VALUE, x.toMicros(Integer.MIN_VALUE));
            }
        }
    }
}

25. TimeUnit8Test#testToChronoUnit()

Project: openjdk
Source File: TimeUnit8Test.java
View license
/**
     * tests for toChronoUnit.
     */
public void testToChronoUnit() throws Exception {
    assertSame(ChronoUnit.NANOS, NANOSECONDS.toChronoUnit());
    assertSame(ChronoUnit.MICROS, MICROSECONDS.toChronoUnit());
    assertSame(ChronoUnit.MILLIS, MILLISECONDS.toChronoUnit());
    assertSame(ChronoUnit.SECONDS, SECONDS.toChronoUnit());
    assertSame(ChronoUnit.MINUTES, MINUTES.toChronoUnit());
    assertSame(ChronoUnit.HOURS, HOURS.toChronoUnit());
    assertSame(ChronoUnit.DAYS, DAYS.toChronoUnit());
    // Every TimeUnit has a defined ChronoUnit equivalent
    for (TimeUnit x : TimeUnit.values()) assertSame(x, TimeUnit.of(x.toChronoUnit()));
}

26. TopologyEventsMetricsCommand#printEventMetric()

View license
/**
     * Prints an Event Metric.
     *
     * @param operationStr the string with the intent operation to print
     * @param eventMetric the Event Metric to print
     */
private void printEventMetric(String operationStr, EventMetric eventMetric) {
    Gauge<Long> gauge = eventMetric.lastEventTimestampGauge();
    Meter meter = eventMetric.eventRateMeter();
    TimeUnit rateUnit = TimeUnit.SECONDS;
    double rateFactor = rateUnit.toSeconds(1);
    // Print the Gauge
    print(FORMAT_GAUGE, operationStr, gauge.getValue());
    // Print the Meter
    print(FORMAT_METER, operationStr, meter.getCount(), meter.getMeanRate() * rateFactor, meter.getOneMinuteRate() * rateFactor, meter.getFiveMinuteRate() * rateFactor, meter.getFifteenMinuteRate() * rateFactor);
}

27. IntentEventsMetricsCommand#printEventMetric()

View license
/**
     * Prints an Event Metric.
     *
     * @param operationStr the string with the intent operation to print
     * @param eventMetric the Event Metric to print
     */
private void printEventMetric(String operationStr, EventMetric eventMetric) {
    Gauge<Long> gauge = eventMetric.lastEventTimestampGauge();
    Meter meter = eventMetric.eventRateMeter();
    TimeUnit rateUnit = TimeUnit.SECONDS;
    double rateFactor = rateUnit.toSeconds(1);
    // Print the Gauge
    print(FORMAT_GAUGE, operationStr, gauge.getValue());
    // Print the Meter
    print(FORMAT_METER, operationStr, meter.getCount(), meter.getMeanRate() * rateFactor, meter.getOneMinuteRate() * rateFactor, meter.getFiveMinuteRate() * rateFactor, meter.getFifteenMinuteRate() * rateFactor);
}

28. RequestTest#testSetReadTimeout_1()

Project: jInstagram
Source File: RequestTest.java
View license
/**
	 * Run the void setReadTimeout(int,TimeUnit) method test.
	 *
	 * @throws Exception
	 *
	 * 
	 */
@Test
public void testSetReadTimeout_1() throws Exception {
    Request fixture = new Request(Verbs.DELETE, "");
    fixture.setConnectionKeepAlive(true);
    fixture.setCharset("UTF-8");
    fixture.addPayload("Dummy payload");
    fixture.setConnection(mockHttpConnection);
    fixture.setProxy(proxy);
    int duration = 1;
    TimeUnit unit = TimeUnit.DAYS;
    fixture.setReadTimeout(duration, unit);
// add additional test code here
// An unexpected exception was thrown in user code while executing this
// test:
// java.lang.IllegalArgumentException: type DIRECT is not compatible
// with address 0.0.0.0/0.0.0.0:1
// at java.net.Proxy.<init>(Proxy.java:95)
}

29. RequestTest#testSetConnectTimeout_1()

Project: jInstagram
Source File: RequestTest.java
View license
/**
	 * Run the void setConnectTimeout(int,TimeUnit) method test.
	 *
	 * @throws Exception
	 *
	 * 
	 */
@Test
public void testSetConnectTimeout_1() throws Exception {
    Request fixture = new Request(Verbs.DELETE, "");
    fixture.setConnectionKeepAlive(true);
    fixture.setCharset("UTF-8");
    fixture.addPayload("Dummy payload");
    fixture.setConnection(mockHttpConnection);
    fixture.setProxy(proxy);
    int duration = 1;
    TimeUnit unit = TimeUnit.DAYS;
    fixture.setConnectTimeout(duration, unit);
// add additional test code here
// An unexpected exception was thrown in user code while executing this
// test:
// java.lang.IllegalArgumentException: type DIRECT is not compatible
// with address 0.0.0.0/0.0.0.0:1
// at java.net.Proxy.<init>(Proxy.java:95)
}

30. IncrementalSimonsPurgerTest#testCancel()

View license
@Test
public void testCancel() {
    EnabledManager manager = new EnabledManager();
    IncrementalSimonsPurger incrementalSimonsPurger = new IncrementalSimonsPurger(manager, executorService);
    long duration = 1;
    TimeUnit timeUnit = TimeUnit.SECONDS;
    incrementalSimonsPurger.start(duration, timeUnit);
    incrementalSimonsPurger.cancel();
    verify(scheduledFuture).cancel(false);
}

31. DruidSinkIT#getTrackerEvent()

Project: Ingestion
Source File: DruidSinkIT.java
View license
private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "[email protected]", "[email protected]", "[email protected]", "[email protected]" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp", String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random.nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);
    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}

32. QueryListener#exitExpressionDuration()

Project: heroic
Source File: QueryListener.java
View license
@Override
public void exitExpressionDuration(ExpressionDurationContext ctx) {
    final String text = ctx.getText();
    final int value;
    final TimeUnit unit;
    final Context c = context(ctx);
    if (text.length() > 2 && "ms".equals(text.substring(text.length() - 2, text.length()))) {
        unit = TimeUnit.MILLISECONDS;
        value = Integer.parseInt(text.substring(0, text.length() - 2));
    } else {
        unit = extractUnit(c, text.substring(text.length() - 1, text.length()));
        value = Integer.parseInt(text.substring(0, text.length() - 1));
    }
    push(new DurationExpression(c, unit, value));
}

33. DurationExpression#divide()

Project: heroic
Source File: DurationExpression.java
View license
@Override
public DurationExpression divide(final Expression other) {
    final long den = other.cast(IntegerExpression.class).getValue();
    long value = this.value;
    TimeUnit unit = this.unit;
    outer: while (value % den != 0) {
        if (unit == TimeUnit.MILLISECONDS) {
            break;
        }
        final TimeUnit next = nextSmallerUnit(unit);
        value = next.convert(value, unit);
        unit = next;
    }
    return new DurationExpression(context, unit, value / den);
}

34. FakeTickerTest#testAutoIncrementStep_resetToZero()

Project: guava
Source File: FakeTickerTest.java
View license
public void testAutoIncrementStep_resetToZero() {
    FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS);
    assertEquals(0, ticker.read());
    assertEquals(10, ticker.read());
    assertEquals(20, ticker.read());
    for (TimeUnit timeUnit : EnumSet.allOf(TimeUnit.class)) {
        ticker.setAutoIncrementStep(0, timeUnit);
        assertEquals("Expected no auto-increment when setting autoIncrementStep to 0 " + timeUnit, 30, ticker.read());
    }
}

35. AbstractValueHolder#accessed()

Project: ehcache3
Source File: AbstractValueHolder.java
View license
public void accessed(long now, Duration expiration) {
    final TimeUnit timeUnit = nativeTimeUnit();
    if (expiration != null) {
        if (expiration.isInfinite()) {
            setExpirationTime(Store.ValueHolder.NO_EXPIRE, null);
        } else {
            long millis = timeUnit.convert(expiration.getLength(), expiration.getTimeUnit());
            long newExpirationTime;
            if (millis == Long.MAX_VALUE) {
                newExpirationTime = Long.MAX_VALUE;
            } else {
                newExpirationTime = now + millis;
                if (newExpirationTime < 0) {
                    newExpirationTime = Long.MAX_VALUE;
                }
            }
            setExpirationTime(newExpirationTime, timeUnit);
        }
    }
    setLastAccessTime(now, timeUnit);
    HITS_UPDATER.getAndIncrement(this);
}

36. Duration#parse()

Project: dropwizard
Source File: Duration.java
View license
@JsonCreator
public static Duration parse(String duration) {
    final Matcher matcher = DURATION_PATTERN.matcher(duration);
    checkArgument(matcher.matches(), "Invalid duration: " + duration);
    final long count = Long.parseLong(matcher.group(1));
    final TimeUnit unit = SUFFIXES.get(matcher.group(2));
    if (unit == null) {
        throw new IllegalArgumentException("Invalid duration: " + duration + ". Wrong time unit");
    }
    return new Duration(count, unit);
}

37. FindThroughputTest#testFindPerformance2()

Project: concourse
Source File: FindThroughputTest.java
View license
@Test
public void testFindPerformance2() {
    System.out.println("Doing the testFindPerformance2 test");
    int count = 500;
    for (int i = 0; i < count; i++) {
        for (int j = 0; j <= i; j++) {
            client.add("foo", j, i);
        }
    }
    Stopwatch watch = Stopwatch.createStarted();
    client.find("foo", Operator.BETWEEN, 5, 100);
    watch.stop();
    TimeUnit unit = TimeUnit.MILLISECONDS;
    System.out.println(watch.elapsed(unit) + " " + unit);
    System.gc();
}

38. FindThroughputTest#testFindPerformance1()

Project: concourse
Source File: FindThroughputTest.java
View license
@Test
public void testFindPerformance1() {
    System.out.println("Doing the testFindPerformance1 test");
    int count = 20000;
    for (int i = 0; i < count; i++) {
        client.add("foo", i, i);
    }
    Stopwatch watch = Stopwatch.createStarted();
    client.find("foo", Operator.GREATER_THAN_OR_EQUALS, 0);
    watch.stop();
    TimeUnit unit = TimeUnit.MILLISECONDS;
    System.out.println(watch.elapsed(unit) + " " + unit);
    System.gc();
}

39. CamelSpringTestContextLoader#handleShutdownTimeout()

View license
/**
     * Handles updating shutdown timeouts on Camel contexts based on {@link ShutdownTimeout}.
     *
     * @param context the initialized Spring context
     * @param testClass the test class being executed
     */
protected void handleShutdownTimeout(GenericApplicationContext context, Class<?> testClass) throws Exception {
    final int shutdownTimeout;
    final TimeUnit shutdownTimeUnit;
    if (testClass.isAnnotationPresent(ShutdownTimeout.class)) {
        shutdownTimeout = testClass.getAnnotation(ShutdownTimeout.class).value();
        shutdownTimeUnit = testClass.getAnnotation(ShutdownTimeout.class).timeUnit();
    } else {
        shutdownTimeout = 10;
        shutdownTimeUnit = TimeUnit.SECONDS;
    }
    CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() {

        @Override
        public void execute(String contextName, SpringCamelContext camelContext) throws Exception {
            LOG.info("Setting shutdown timeout to [{} {}] on CamelContext with name [{}].", new Object[] { shutdownTimeout, shutdownTimeUnit, contextName });
            camelContext.getShutdownStrategy().setTimeout(shutdownTimeout);
            camelContext.getShutdownStrategy().setTimeUnit(shutdownTimeUnit);
        }
    });
}

40. CamelAnnotationsHandler#handleShutdownTimeout()

Project: camel
Source File: CamelAnnotationsHandler.java
View license
/**
     * Handles updating shutdown timeouts on Camel contexts based on {@link ShutdownTimeout}.
     *
     * @param context the initialized Spring context
     * @param testClass the test class being executed
     */
public static void handleShutdownTimeout(ConfigurableApplicationContext context, Class<?> testClass) throws Exception {
    final int shutdownTimeout;
    final TimeUnit shutdownTimeUnit;
    if (testClass.isAnnotationPresent(ShutdownTimeout.class)) {
        shutdownTimeout = testClass.getAnnotation(ShutdownTimeout.class).value();
        shutdownTimeUnit = testClass.getAnnotation(ShutdownTimeout.class).timeUnit();
    } else {
        shutdownTimeout = 10;
        shutdownTimeUnit = TimeUnit.SECONDS;
    }
    CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() {

        public void execute(String contextName, SpringCamelContext camelContext) throws Exception {
            LOGGER.info("Setting shutdown timeout to [{} {}] on CamelContext with name [{}].", new Object[] { shutdownTimeout, shutdownTimeUnit, contextName });
            camelContext.getShutdownStrategy().setTimeout(shutdownTimeout);
            camelContext.getShutdownStrategy().setTimeUnit(shutdownTimeUnit);
        }
    });
}

41. ManagedShutdownStrategyTest#testManagedShutdownStrategy()

View license
public void testManagedShutdownStrategy() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
        return;
    }
    // set timeout to 300
    context.getShutdownStrategy().setTimeout(300);
    MBeanServer mbeanServer = getMBeanServer();
    ObjectName on = ObjectName.getInstance("org.apache.camel:context=camel-1,type=context,name=\"camel-1\"");
    Long timeout = (Long) mbeanServer.getAttribute(on, "Timeout");
    assertEquals(300, timeout.longValue());
    TimeUnit unit = (TimeUnit) mbeanServer.getAttribute(on, "TimeUnit");
    assertEquals("seconds", unit.toString().toLowerCase(Locale.ENGLISH));
}

42. ShortDuration#valueOf()

Project: caliper
Source File: ShortDuration.java
View license
public static ShortDuration valueOf(String s) {
    if ("0".equals(s)) {
        return ZERO;
    }
    Matcher matcher = PATTERN.matcher(s);
    checkArgument(matcher.matches(), "Invalid ShortDuration: %s", s);
    BigDecimal value = new BigDecimal(matcher.group(1));
    String abbrev = matcher.group(2);
    TimeUnit unit = ABBREV_TO_UNIT.get(abbrev);
    checkArgument(unit != null, "Unrecognized time unit: %s", abbrev);
    return of(value, unit);
}

43. NetworkStatsKeeper#scheduleDownloadSpeedCalculation()

Project: buck
Source File: NetworkStatsKeeper.java
View license
private void scheduleDownloadSpeedCalculation() {
    long calculationInterval = DOWNLOAD_SPEED_CALCULATION_INTERVAL.getDuration();
    TimeUnit timeUnit = DOWNLOAD_SPEED_CALCULATION_INTERVAL.getUnit();
    scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            calculateDownloadSpeedInLastInterval();
        }
    }, /* initialDelay */
    calculationInterval, /* period */
    calculationInterval, timeUnit);
}

44. Processor#getDuration()

Project: bnd
Source File: Processor.java
View license
public static long getDuration(String tm, long dflt) {
    if (tm == null)
        return dflt;
    tm = tm.toUpperCase();
    TimeUnit unit = TimeUnit.MILLISECONDS;
    Matcher m = Pattern.compile("\\s*(\\d+)\\s*(NANOSECONDS|MICROSECONDS|MILLISECONDS|SECONDS|MINUTES|HOURS|DAYS)?").matcher(tm);
    if (m.matches()) {
        long duration = Long.parseLong(tm);
        String u = m.group(2);
        if (u != null)
            unit = TimeUnit.valueOf(u);
        duration = TimeUnit.MILLISECONDS.convert(duration, unit);
        return duration;
    }
    return dflt;
}

45. TimeUtil#getTimeUnit()

Project: bboss
Source File: TimeUtil.java
View license
public static TimeUnit getTimeUnit(String timeUnit, TimeUnit defaultUnit) {
    TimeUnit timeUnit_ = TimeUnit.SECONDS;
    try {
        timeUnit_ = TimeUnit.valueOf(timeUnit);
    } catch (Exception e) {
        timeUnit_ = defaultUnit;
    }
    return timeUnit_;
}

46. JmxPreparableReporter#prepare()

View license
@Override
public void prepare(MetricRegistry metricsRegistry, Map stormConf) {
    LOG.info("Preparing...");
    JmxReporter.Builder builder = JmxReporter.forRegistry(metricsRegistry);
    String domain = Utils.getString(stormConf.get(Config.STORM_DAEMON_METRICS_REPORTER_PLUGIN_DOMAIN), null);
    if (domain != null) {
        builder.inDomain(domain);
    }
    TimeUnit rateUnit = MetricsUtils.getMetricsRateUnit(stormConf);
    if (rateUnit != null) {
        builder.convertRatesTo(rateUnit);
    }
    reporter = builder.build();
}

47. Duration#valueOf()

Project: airlift
Source File: Duration.java
View license
@JsonCreator
public static Duration valueOf(String duration) throws IllegalArgumentException {
    Preconditions.checkNotNull(duration, "duration is null");
    Preconditions.checkArgument(!duration.isEmpty(), "duration is empty");
    Matcher matcher = PATTERN.matcher(duration);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("duration is not a valid data duration string: " + duration);
    }
    double value = Double.parseDouble(matcher.group(1));
    String unitString = matcher.group(2);
    TimeUnit timeUnit = valueOfTimeUnit(unitString);
    return new Duration(value, timeUnit);
}

48. FakeReporterFactoryBean#createInstance()

View license
@Override
protected FakeReporter createInstance() {
    TimeUnit durationUnit = getProperty(DURATION_UNIT, TimeUnit.class);
    TimeUnit rateUnit = getProperty(RATE_UNIT, TimeUnit.class);
    return new FakeReporter(getMetricRegistry(), getMetricFilter(), rateUnit, durationUnit);
}

49. AbstractScheduledReporterFactoryBean#convertDurationString()

View license
/**
	 * Parses and converts to nanoseconds a string representing
	 * a duration, ie: 500ms, 30s, 5m, 1h, etc
	 * @param duration a string representing a duration
	 * @return the duration in nanoseconds
	 */
protected long convertDurationString(String duration) {
    final Matcher m = DURATION_STRING_PATTERN.matcher(duration);
    if (!m.matches()) {
        throw new IllegalArgumentException("Invalid duration string format");
    }
    final long sourceDuration = Long.parseLong(m.group(1));
    final String sourceUnitString = m.group(2);
    final TimeUnit sourceUnit;
    if ("ns".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.NANOSECONDS;
    } else if ("us".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MICROSECONDS;
    } else if ("ms".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MILLISECONDS;
    } else if ("s".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.SECONDS;
    } else if ("m".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MINUTES;
    } else if ("h".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.HOURS;
    } else if ("d".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.DAYS;
    } else {
        sourceUnit = TimeUnit.MILLISECONDS;
    }
    return sourceUnit.toNanos(sourceDuration);
}

50. MetricsServlet#init()

Project: metrics
Source File: MetricsServlet.java
View license
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    final ServletContext context = config.getServletContext();
    if (null == registry) {
        final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
        if (registryAttr instanceof MetricRegistry) {
            this.registry = (MetricRegistry) registryAttr;
        } else {
            throw new ServletException("Couldn't find a MetricRegistry instance.");
        }
    }
    final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS);
    final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS);
    final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES));
    MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER);
    if (filter == null) {
        filter = MetricFilter.ALL;
    }
    this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter));
    this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN);
    this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM);
}

51. GraphiteReporterStarter#start()

View license
@Override
public List<AutoCloseable> start(Params params) {
    Configuration config = new FluoConfiguration(params.getConfiguration()).getReporterConfiguration("graphite");
    if (!config.getBoolean("enable", false)) {
        return Collections.emptyList();
    }
    String host = config.getString("host");
    String prefix = config.getString("prefix", "");
    int port = config.getInt("port", 8080);
    TimeUnit rateUnit = TimeUnit.valueOf(config.getString("rateUnit", "seconds").toUpperCase());
    TimeUnit durationUnit = TimeUnit.valueOf(config.getString("durationUnit", "milliseconds").toUpperCase());
    Graphite graphite = new Graphite(host, port);
    GraphiteReporter reporter = GraphiteReporter.forRegistry(params.getMetricRegistry()).convertDurationsTo(durationUnit).convertRatesTo(rateUnit).prefixedWith(prefix).build(graphite);
    reporter.start(config.getInt("frequency", 60), TimeUnit.SECONDS);
    log.info("Reporting metrics to graphite server {}:{}", host, port);
    return Collections.singletonList((AutoCloseable) reporter);
}

52. ConsoleReporterStarter#start()

View license
@Override
public List<AutoCloseable> start(Params params) {
    Configuration config = new FluoConfiguration(params.getConfiguration()).getReporterConfiguration("console");
    if (!config.getBoolean("enable", false)) {
        return Collections.emptyList();
    }
    TimeUnit rateUnit = TimeUnit.valueOf(config.getString("rateUnit", "seconds").toUpperCase());
    TimeUnit durationUnit = TimeUnit.valueOf(config.getString("durationUnit", "milliseconds").toUpperCase());
    PrintStream out = System.out;
    if (config.getString("target", "stdout").equals("stderr")) {
        out = System.err;
    }
    ConsoleReporter reporter = ConsoleReporter.forRegistry(params.getMetricRegistry()).convertDurationsTo(durationUnit).convertRatesTo(rateUnit).outputTo(out).build();
    reporter.start(config.getInt("frequency", 60), TimeUnit.SECONDS);
    log.info("Reporting metrics to console");
    return Collections.singletonList((AutoCloseable) reporter);
}

53. JobTest#testWaitForWithTimeout()

Project: gcloud-java
Source File: JobTest.java
View license
@Test
public void testWaitForWithTimeout() throws InterruptedException, TimeoutException {
    initializeExpectedJob(2);
    BigQuery.JobOption[] expectedOptions = { BigQuery.JobOption.fields(BigQuery.JobField.STATUS) };
    TimeUnit timeUnit = createStrictMock(TimeUnit.class);
    timeUnit.sleep(1);
    EasyMock.expectLastCall();
    Clock clock = createStrictMock(Clock.class);
    expect(clock.millis()).andReturn(0L);
    expect(clock.millis()).andReturn(1L);
    expect(clock.millis()).andReturn(3L);
    JobStatus status = createStrictMock(JobStatus.class);
    expect(status.state()).andReturn(JobStatus.State.RUNNING);
    expect(status.state()).andReturn(JobStatus.State.RUNNING);
    expect(bigquery.options()).andReturn(mockOptions);
    expect(mockOptions.clock()).andReturn(clock);
    Job runningJob = expectedJob.toBuilder().status(status).build();
    expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob);
    expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob);
    replay(status, bigquery, timeUnit, clock, mockOptions);
    initializeJob();
    thrown.expect(TimeoutException.class);
    job.waitFor(WaitForOption.checkEvery(1, timeUnit), WaitForOption.timeout(3, TimeUnit.MILLISECONDS));
    verify(status, timeUnit, clock, mockOptions);
}

54. ChronicleMapSanityCheckTest#testSanity1()

View license
@Test
public void testSanity1() throws IOException, InterruptedException {
    String tmp = System.getProperty("java.io.tmpdir");
    String pathname = tmp + "/testSanity1-" + UUID.randomUUID().toString() + ".dat";
    File file = new File(pathname);
    System.out.println("Starting sanity test 1. Chronicle file :" + file.getAbsolutePath().toString());
    ScheduledExecutorService producerExecutor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() - 1);
    ScheduledExecutorService consumerExecutor = Executors.newSingleThreadScheduledExecutor();
    int N = 1000;
    int producerPeriod = 100;
    TimeUnit producerTimeUnit = TimeUnit.MILLISECONDS;
    int consumerPeriod = 100;
    TimeUnit consumerTimeUnit = TimeUnit.MILLISECONDS;
    int totalTestTimeMS = (consumerPeriod + producerPeriod) * 20;
    try (ChronicleMap<String, DummyValue> map = ChronicleMapBuilder.of(String.class, DummyValue.class).averageKey("" + N).averageValue(DummyValue.DUMMY_VALUE).entries(N).createPersistedTo(file)) {
        map.clear();
        producerExecutor.scheduleAtFixedRate(() -> {
            Thread.currentThread().setName("Producer " + Thread.currentThread().getId());
            Random r = new Random();
            System.out.println("Before PRODUCING size is " + map.size());
            for (int i = 0; i < N; i++) {
                LockSupport.parkNanos(r.nextInt(5));
                map.put(String.valueOf(i), DummyValue.DUMMY_VALUE);
            }
            System.out.println("After PRODUCING size is " + map.size());
        }, 0, producerPeriod, producerTimeUnit);
        consumerExecutor.scheduleAtFixedRate(() -> {
            Thread.currentThread().setName("Consumer");
            Set<String> keys = map.keySet();
            Random r = new Random();
            System.out.println("Before CONSUMING size is " + map.size());
            System.out.println();
            for (String key : keys) {
                if (r.nextBoolean()) {
                    map.remove(key);
                }
            }
            System.out.println("After CONSUMING size is " + map.size());
        }, 0, consumerPeriod, consumerTimeUnit);
        Jvm.pause(totalTestTimeMS);
        consumerExecutor.shutdown();
        try {
            consumerExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        producerExecutor.shutdown();
        try {
            producerExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

55. SleepTimerDialog#readTimeMillis()

Project: AntennaPod
Source File: SleepTimerDialog.java
View license
private long readTimeMillis() {
    TimeUnit selectedUnit = units[spTimeUnit.getSelectedItemPosition()];
    long value = Long.parseLong(etxtTime.getText().toString());
    return selectedUnit.toMillis(value);
}

56. HasEmailRule#emailsArrivedWithinTimeout()

Project: zanata-server
Source File: HasEmailRule.java
View license
/**
     * Email may arrive a little bit late therefore this method can be used to
     * poll and wait until timeout.
     *
     * @param expectedEmailNum
     *            expected arriving email numbers
     * @param timeoutDuration
     *            timeout duration
     * @param timeoutUnit
     *            timeout time unit
     * @return true if the expected number of emails has arrived or false if it
     *         fails within the timeout period
     */
public boolean emailsArrivedWithinTimeout(final int expectedEmailNum, final long timeoutDuration, final TimeUnit timeoutUnit) {
    log.info("waiting for email count to be {}", expectedEmailNum);
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    // poll every half second
    final int sleepFor = 500;
    final TimeUnit sleepUnit = TimeUnit.MILLISECONDS;
    final long sleepTime = sleepUnit.convert(sleepFor, sleepUnit);
    final long timeoutTime = sleepUnit.convert(timeoutDuration, timeoutUnit);
    Runnable runnable = () -> {
        long slept = 0;
        while (wiser.getMessages().size() < expectedEmailNum && slept < timeoutTime) {
            log.info("Number of arrived emails: {}", wiser.getMessages().size());
            Uninterruptibles.sleepUninterruptibly(sleepFor, sleepUnit);
            slept += sleepTime;
        }
        countDownLatch.countDown();
    };
    Executors.newFixedThreadPool(1).submit(runnable);
    try {
        return countDownLatch.await(timeoutDuration, timeoutUnit);
    } catch (InterruptedException e) {
        log.warn("interrupted", e);
        return wiser.getMessages().size() == expectedEmailNum;
    }
}

57. Stopwatch#toString()

Project: voltdb
Source File: Stopwatch.java
View license
/**
   * Returns a string representation of the current elapsed time.
   */
@GwtIncompatible("String.format()")
@Override
public String toString() {
    long nanos = elapsedNanos();
    TimeUnit unit = chooseUnit(nanos);
    double value = (double) nanos / NANOSECONDS.convert(1, unit);
    // Too bad this functionality is not exposed as a regular method call
    return String.format(Locale.ROOT, "%.4g %s", value, abbreviate(unit));
}

58. BaseStreamingClient#initStreamingSessions()

Project: voldemort
Source File: BaseStreamingClient.java
View license
/**
     ** 
     * @param stores - the list of name of the stores to be streamed to
     * 
     * 
     * @param checkpointCallback - the callback that allows for the user to
     *        record the progress, up to the last event delivered. This callable
     *        would be invoked every so often internally.
     * 
     * @param recoveryCallback - the callback that allows the user to rewind the
     *        upstream to the position recorded by the last complete call on
     *        checkpointCallback whenever an exception occurs during the
     *        streaming session.
     * 
     * @param allowMerge - whether to allow for the streaming event to be merged
     *        with online writes. If not, all online writes since the completion
     *        of the last streaming session will be lost at the end of the
     *        current streaming session.
     * 
     * @param blackListedNodes - the list of Nodes not to stream to; we can
     *        probably recover them later from the replicas
     **/
@SuppressWarnings({ "unchecked", "rawtypes" })
public synchronized void initStreamingSessions(List<String> stores, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge, List<Integer> blackListedNodes) {
    logger.info("Initializing a streaming session");
    this.checkpointCallback = checkpointCallback;
    this.recoveryCallback = recoveryCallback;
    this.allowMerge = allowMerge;
    streamingresults = Executors.newFixedThreadPool(3);
    entriesProcessed = 0;
    newBatch = true;
    isMultiSession = true;
    this.throttler = new EventThrottler(THROTTLE_QPS);
    TimeUnit unit = TimeUnit.SECONDS;
    Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();
    if (blackListedNodes != null && blackListedNodes.size() > 0) {
        this.blackListedNodes = blackListedNodes;
    }
    for (Node node : nodesInCluster) {
        if (blackListedNodes != null && blackListedNodes.size() > 0) {
            if (!blackListedNodes.contains(node.getId())) {
                nodesToStream.add(node);
            }
        } else
            nodesToStream.add(node);
    }
    // socket pool
    streamingSocketPool = new SocketPool(adminClient.getAdminClientCluster().getNumberOfNodes() * MAX_STORES_PER_SESSION, (int) unit.toMillis(adminClientConfig.getAdminConnectionTimeoutSec()), (int) unit.toMillis(adminClientConfig.getAdminSocketTimeoutSec()), adminClientConfig.getAdminSocketBufferSize(), adminClientConfig.getAdminSocketKeepAlive());
    nodeIdStoreToSocketRequest = new HashMap();
    nodeIdStoreToOutputStreamRequest = new HashMap();
    nodeIdStoreToInputStreamRequest = new HashMap();
    nodeIdStoreInitialized = new HashMap();
    storeToRoutingStrategy = new HashMap();
    nodeIdStoreToSocketAndStreams = new HashMap();
    for (String store : stores) {
        addStoreToSession(store);
    }
}

59. Stopwatch#toString()

Project: titan
Source File: Stopwatch.java
View license
/**
     * Returns a string representation of the current elapsed time.
     */
@GwtIncompatible("String.format()")
@Override
public String toString() {
    long nanos = elapsedNanos();
    TimeUnit unit = chooseUnit(nanos);
    double value = (double) nanos / NANOSECONDS.convert(1, unit);
    // Too bad this functionality is not exposed as a regular method call
    return String.format("%.4g %s", value, abbreviate(unit));
}

60. VisibilityFenceTest#testFenceTimeout()

Project: tephra
Source File: VisibilityFenceTest.java
View license
@Test
public void testFenceTimeout() throws Exception {
    byte[] fenceId = "test_table".getBytes(Charsets.UTF_8);
    final TransactionContext fence1 = new TransactionContext(new InMemoryTxSystemClient(txManager), VisibilityFence.create(fenceId));
    fence1.start();
    final long timeout = 100;
    final TimeUnit timeUnit = TimeUnit.MILLISECONDS;
    final AtomicInteger attempts = new AtomicInteger();
    TransactionSystemClient customTxClient = new InMemoryTxSystemClient(txManager) {

        @Override
        public Transaction startShort() {
            Transaction transaction = super.startShort();
            try {
                switch(attempts.getAndIncrement()) {
                    case 0:
                        fence1.finish();
                        break;
                }
                timeUnit.sleep(timeout + 1);
            } catch (InterruptedExceptionTransactionFailureException |  e) {
                Throwables.propagate(e);
            }
            return transaction;
        }
    };
    try {
        FenceWait fenceWait = VisibilityFence.prepareWait(fenceId, customTxClient);
        fenceWait.await(timeout, timeUnit);
        Assert.fail("Expected await to fail");
    } catch (TimeoutException e) {
    }
    Assert.assertEquals(1, attempts.get());
    FenceWait fenceWait = VisibilityFence.prepareWait(fenceId, customTxClient);
    fenceWait.await(timeout, timeUnit);
    Assert.assertEquals(2, attempts.get());
}

61. StopwatchImpl#toString()

Project: speedment
Source File: StopwatchImpl.java
View license
@Override
public String toString() {
    final long nanos = elapsedNanos();
    final TimeUnit unit = timeUnitFor(nanos);
    final double value = (double) nanos / NANOSECONDS.convert(1, unit);
    return String.format("%,.2f %s", value, unitShortText(unit));
}

62. DefaultClientConfigImpl#putDefaultTimeUnitProperty()

Project: ribbon
Source File: DefaultClientConfigImpl.java
View license
protected void putDefaultTimeUnitProperty(IClientConfigKey propName, TimeUnit defaultValue) {
    TimeUnit value = defaultValue;
    String propValue = ConfigurationManager.getConfigInstance().getString(getDefaultPropName(propName));
    if (propValue != null && propValue.length() > 0) {
        value = TimeUnit.valueOf(propValue);
    }
    setPropertyInternal(propName, value);
}

63. AnomalyResource#updateEmailConfigs()

Project: pinot
Source File: AnomalyResource.java
View license
// Update email function
@POST
@UnitOfWork
@Path("/email-config/update")
public Response updateEmailConfigs(@NotNull @QueryParam("id") Long id, @NotNull @QueryParam("dataset") String dataset, @NotNull @QueryParam("metric") String metric, @NotNull @QueryParam("fromAddress") String fromAddress, @NotNull @QueryParam("toAddresses") String toAddresses, @QueryParam("repeatEvery") String repeatEvery, @QueryParam("scheduleMinute") String scheduleMinute, @QueryParam("scheduleHour") String scheduleHour, @NotNull @QueryParam("windowSize") String windowSize, @NotNull @QueryParam("windowUnit") String windowUnit, @QueryParam("windowDelay") String windowDelay, @QueryParam("windowDelayUnit") String windowDelayUnit, @QueryParam("filters") String filters, @QueryParam("isActive") boolean isActive, @QueryParam("sendZeroAnomalyEmail") boolean sendZeroAnomalyEmail, @QueryParam("functionIds") String functionIds) throws ClientProtocolException, IOException {
    if (id == null || StringUtils.isEmpty(dataset) || StringUtils.isEmpty(functionIds) || StringUtils.isEmpty(metric) || StringUtils.isEmpty(windowSize) || StringUtils.isEmpty(windowUnit) || StringUtils.isEmpty(fromAddress) || StringUtils.isEmpty(toAddresses)) {
        throw new UnsupportedOperationException("Received null for one of the mandatory params: " + "dataset " + dataset + ", functionIds " + functionIds + ", metric " + metric + ", windowSize " + windowSize + ", windowUnit " + windowUnit + ", fromAddress" + fromAddress + ", toAddresses " + toAddresses);
    }
    // stop email report if active
    EmailConfiguration emailConfiguration = emailConfigurationDAO.findById(id);
    if (emailConfiguration == null) {
        throw new IllegalStateException("No email configuration for id " + id);
    }
    if (emailConfiguration.getIsActive()) {
        detectorHttpUtils.disableEmailConfiguration(String.valueOf(id));
    }
    emailConfiguration.setIsActive(false);
    emailConfiguration.setId(id);
    emailConfiguration.setCollection(dataset);
    emailConfiguration.setMetric(metric);
    emailConfiguration.setFromAddress(fromAddress);
    emailConfiguration.setToAddresses(toAddresses);
    String cron = DEFAULT_CRON;
    if (StringUtils.isNotEmpty(repeatEvery)) {
        cron = ThirdEyeUtils.constructCron(scheduleMinute, scheduleHour, TimeUnit.valueOf(repeatEvery));
    }
    emailConfiguration.setCron(cron);
    emailConfiguration.setSmtpHost(dashboardConfiguration.getSmtpHost());
    emailConfiguration.setSmtpPort(dashboardConfiguration.getSmtpPort());
    emailConfiguration.setWindowSize(Integer.valueOf(windowSize));
    emailConfiguration.setWindowUnit(TimeUnit.valueOf(windowUnit));
    TimeUnit windowDelayTimeUnit = TimeUnit.valueOf(windowUnit);
    if (StringUtils.isNotEmpty(windowDelayUnit)) {
        windowDelayTimeUnit = TimeUnit.valueOf(windowDelayUnit);
    }
    int windowDelayTime = 0;
    if (StringUtils.isNotEmpty(windowDelay)) {
        windowDelayTime = Integer.valueOf(windowDelay);
    }
    emailConfiguration.setWindowDelayUnit(windowDelayTimeUnit);
    emailConfiguration.setWindowDelay(windowDelayTime);
    emailConfiguration.setSendZeroAnomalyEmail(sendZeroAnomalyEmail);
    emailConfiguration.setFilters(filters);
    List<AnomalyFunctionSpec> anomalyFunctionSpecs = new ArrayList<>();
    for (String functionIdString : functionIds.split(",")) {
        AnomalyFunctionSpec anomalyFunctionSpec = anomalyFunctionSpecDAO.findById(Long.valueOf(functionIdString));
        anomalyFunctionSpecs.add(anomalyFunctionSpec);
    }
    emailConfiguration.setFunctions(anomalyFunctionSpecs);
    Long responseId = emailConfigurationDAO.createOrUpdate(emailConfiguration);
    // call endpoint to start, if active
    if (isActive) {
        detectorHttpUtils.enableEmailConfiguration(String.valueOf(id));
    }
    return Response.ok(responseId).build();
}

64. AnomalyResource#createEmailConfigs()

Project: pinot
Source File: AnomalyResource.java
View license
// Add email function
@POST
@UnitOfWork
@Path("/email-config/create")
public Response createEmailConfigs(@NotNull @QueryParam("dataset") String dataset, @NotNull @QueryParam("metric") String metric, @NotNull @QueryParam("fromAddress") String fromAddress, @NotNull @QueryParam("toAddresses") String toAddresses, @QueryParam("repeatEvery") String repeatEvery, @QueryParam("scheduleMinute") String scheduleMinute, @QueryParam("scheduleHour") String scheduleHour, @NotNull @QueryParam("windowSize") String windowSize, @NotNull @QueryParam("windowUnit") String windowUnit, @QueryParam("windowDelay") String windowDelay, @QueryParam("windowDelayUnit") String windowDelayUnit, @QueryParam("filters") String filters, @QueryParam("isActive") boolean isActive, @QueryParam("sendZeroAnomalyEmail") boolean sendZeroAnomalyEmail, @QueryParam("functionIds") String functionIds) throws ClientProtocolException, IOException {
    if (StringUtils.isEmpty(dataset) || StringUtils.isEmpty(functionIds) || StringUtils.isEmpty(metric) || StringUtils.isEmpty(windowSize) || StringUtils.isEmpty(windowUnit) || StringUtils.isEmpty(fromAddress) || StringUtils.isEmpty(toAddresses)) {
        throw new UnsupportedOperationException("Received null for one of the mandatory params: " + "dataset " + dataset + ", functionIds " + functionIds + ", metric " + metric + ", windowSize " + windowSize + ", windowUnit " + windowUnit + ", fromAddress" + fromAddress + ", toAddresses " + toAddresses);
    }
    EmailConfiguration emailConfiguration = new EmailConfiguration();
    emailConfiguration.setIsActive(false);
    emailConfiguration.setCollection(dataset);
    emailConfiguration.setMetric(metric);
    emailConfiguration.setFromAddress(fromAddress);
    emailConfiguration.setToAddresses(toAddresses);
    String cron = DEFAULT_CRON;
    if (StringUtils.isNotEmpty(repeatEvery)) {
        cron = ThirdEyeUtils.constructCron(scheduleMinute, scheduleHour, TimeUnit.valueOf(repeatEvery));
    }
    emailConfiguration.setCron(cron);
    emailConfiguration.setSmtpHost(dashboardConfiguration.getSmtpHost());
    emailConfiguration.setSmtpPort(dashboardConfiguration.getSmtpPort());
    emailConfiguration.setWindowSize(Integer.valueOf(windowSize));
    emailConfiguration.setWindowUnit(TimeUnit.valueOf(windowUnit));
    TimeUnit windowDelayTimeUnit = TimeUnit.valueOf(windowUnit);
    if (StringUtils.isNotEmpty(windowDelayUnit)) {
        windowDelayTimeUnit = TimeUnit.valueOf(windowDelayUnit);
    }
    int windowDelayTime = 0;
    if (StringUtils.isNotEmpty(windowDelay)) {
        windowDelayTime = Integer.valueOf(windowDelay);
    }
    emailConfiguration.setWindowDelayUnit(windowDelayTimeUnit);
    emailConfiguration.setWindowDelay(windowDelayTime);
    emailConfiguration.setSendZeroAnomalyEmail(sendZeroAnomalyEmail);
    emailConfiguration.setFilters(filters);
    List<AnomalyFunctionSpec> anomalyFunctionSpecs = new ArrayList<>();
    for (String functionIdString : functionIds.split(",")) {
        AnomalyFunctionSpec anomalyFunctionSpec = anomalyFunctionSpecDAO.findById(Long.valueOf(functionIdString));
        anomalyFunctionSpecs.add(anomalyFunctionSpec);
    }
    emailConfiguration.setFunctions(anomalyFunctionSpecs);
    Long id = emailConfigurationDAO.createOrUpdate(emailConfiguration);
    // enable id isActive
    if (isActive) {
        detectorHttpUtils.enableEmailConfiguration(String.valueOf(id));
    }
    return Response.ok(id).build();
}

65. AnomalyResource#createAnomalyFunction()

Project: pinot
Source File: AnomalyResource.java
View license
// Add anomaly function
@POST
@UnitOfWork
@Path("/anomaly-function/create")
public Response createAnomalyFunction(@NotNull @QueryParam("dataset") String dataset, @NotNull @QueryParam("functionName") String functionName, @NotNull @QueryParam("metric") String metric, @QueryParam("type") String type, @NotNull @QueryParam("windowSize") String windowSize, @NotNull @QueryParam("windowUnit") String windowUnit, @QueryParam("windowDelay") String windowDelay, @QueryParam("windowDelayUnit") String windowDelayUnit, @QueryParam("scheduleMinute") String scheduleMinute, @QueryParam("scheduleHour") String scheduleHour, @QueryParam("repeatEvery") String repeatEvery, @QueryParam("exploreDimension") String exploreDimensions, @QueryParam("filters") String filters, @NotNull @QueryParam("properties") String properties, @QueryParam("isActive") boolean isActive) throws Exception {
    if (StringUtils.isEmpty(dataset) || StringUtils.isEmpty(functionName) || StringUtils.isEmpty(metric) || StringUtils.isEmpty(windowSize) || StringUtils.isEmpty(windowUnit) || StringUtils.isEmpty(properties)) {
        throw new UnsupportedOperationException("Received null for one of the mandatory params: " + "dataset " + dataset + ", functionName " + functionName + ", metric " + metric + ", windowSize " + windowSize + ", windowUnit " + windowUnit + ", properties" + properties);
    }
    CollectionSchema schema = CACHE_REGISTRY_INSTANCE.getCollectionSchemaCache().get(dataset);
    TimeGranularity dataGranularity = schema.getTime().getDataGranularity();
    AnomalyFunctionSpec anomalyFunctionSpec = new AnomalyFunctionSpec();
    anomalyFunctionSpec.setIsActive(false);
    anomalyFunctionSpec.setCollection(dataset);
    anomalyFunctionSpec.setFunctionName(functionName);
    anomalyFunctionSpec.setMetric(metric);
    if (StringUtils.isEmpty(type)) {
        type = DEFAULT_FUNCTION_TYPE;
    }
    anomalyFunctionSpec.setType(type);
    anomalyFunctionSpec.setWindowSize(Integer.valueOf(windowSize));
    anomalyFunctionSpec.setWindowUnit(TimeUnit.valueOf(windowUnit));
    TimeUnit windowDelayTimeUnit = TimeUnit.valueOf(windowUnit);
    if (StringUtils.isNotEmpty(windowDelayUnit)) {
        windowDelayTimeUnit = TimeUnit.valueOf(windowDelayUnit);
    }
    int windowDelayTime;
    if (StringUtils.isNotEmpty(windowDelay)) {
        windowDelayTime = Integer.valueOf(windowDelay);
    } else {
        Long maxDateTime = CACHE_REGISTRY_INSTANCE.getCollectionMaxDataTimeCache().get(dataset);
        windowDelayTime = (int) windowDelayTimeUnit.convert(System.currentTimeMillis() - maxDateTime, TimeUnit.MILLISECONDS);
    }
    anomalyFunctionSpec.setWindowDelayUnit(windowDelayTimeUnit);
    anomalyFunctionSpec.setWindowDelay(windowDelayTime);
    // bucket size and unit are defaulted to the collection granularity
    anomalyFunctionSpec.setBucketSize(dataGranularity.getSize());
    anomalyFunctionSpec.setBucketUnit(dataGranularity.getUnit());
    anomalyFunctionSpec.setExploreDimensions(exploreDimensions);
    anomalyFunctionSpec.setFilters(filters);
    anomalyFunctionSpec.setProperties(properties);
    String cron = DEFAULT_CRON;
    if (StringUtils.isNotEmpty(repeatEvery)) {
        cron = ThirdEyeUtils.constructCron(scheduleMinute, scheduleHour, TimeUnit.valueOf(repeatEvery));
    }
    anomalyFunctionSpec.setCron(cron);
    Long id = anomalyFunctionSpecDAO.createOrUpdate(anomalyFunctionSpec);
    if (isActive) {
        // this call will set isActive and schedule it
        detectorHttpUtils.enableAnomalyFunction(String.valueOf(id));
    }
    return Response.ok(id).build();
}

66. PinotThirdEyeClient#parseResultSetGroup()

Project: pinot
Source File: PinotThirdEyeClient.java
View license
private List<String[]> parseResultSetGroup(ThirdEyeRequest request, ResultSetGroup result, List<MetricFunction> metricFunctions, CollectionSchema collectionSchema, List<String> dimensionNames) {
    int numGroupByKeys = 0;
    boolean hasGroupBy = false;
    if (request.getGroupByTimeGranularity() != null) {
        numGroupByKeys += 1;
    }
    if (request.getGroupBy() != null) {
        numGroupByKeys += request.getGroupBy().size();
    }
    if (numGroupByKeys > 0) {
        hasGroupBy = true;
    }
    int numMetrics = request.getMetricFunctions().size();
    int numCols = numGroupByKeys + numMetrics;
    boolean hasGroupByTime = false;
    TimeUnit dataTimeUnit = null;
    long startTime = request.getStartTimeInclusive().getMillis();
    long interval = -1;
    dataTimeUnit = collectionSchema.getTime().getDataGranularity().getUnit();
    boolean isISOFormat = false;
    DateTimeFormatter dateTimeFormatter = null;
    String timeFormat = collectionSchema.getTime().getFormat();
    if (timeFormat != null && !timeFormat.equals(TimeSpec.SINCE_EPOCH_FORMAT)) {
        isISOFormat = true;
        dateTimeFormatter = DateTimeFormat.forPattern(timeFormat).withZoneUTC();
    }
    if (request.getGroupByTimeGranularity() != null) {
        hasGroupByTime = true;
        interval = request.getGroupByTimeGranularity().toMillis();
    }
    LinkedHashMap<String, String[]> dataMap = new LinkedHashMap<>();
    for (int i = 0; i < result.getResultSetCount(); i++) {
        ResultSet resultSet = result.getResultSet(i);
        int numRows = resultSet.getRowCount();
        for (int r = 0; r < numRows; r++) {
            boolean skipRowDueToError = false;
            String[] groupKeys;
            if (hasGroupBy) {
                groupKeys = new String[resultSet.getGroupKeyLength()];
                for (int grpKeyIdx = 0; grpKeyIdx < resultSet.getGroupKeyLength(); grpKeyIdx++) {
                    String groupKeyVal = resultSet.getGroupKeyString(r, grpKeyIdx);
                    if (hasGroupByTime && grpKeyIdx == 0) {
                        int timeBucket;
                        long millis;
                        if (!isISOFormat) {
                            millis = dataTimeUnit.toMillis(Long.parseLong(groupKeyVal));
                        } else {
                            millis = DateTime.parse(groupKeyVal, dateTimeFormatter).getMillis();
                        }
                        if (millis < startTime) {
                            LOG.error("Data point earlier than requested start time {}: {}", startTime, millis);
                            skipRowDueToError = true;
                            break;
                        }
                        timeBucket = (int) ((millis - startTime) / interval);
                        groupKeyVal = String.valueOf(timeBucket);
                    }
                    groupKeys[grpKeyIdx] = groupKeyVal;
                }
                if (skipRowDueToError) {
                    continue;
                }
            } else {
                groupKeys = new String[] {};
            }
            StringBuilder groupKeyBuilder = new StringBuilder("");
            for (String grpKey : groupKeys) {
                groupKeyBuilder.append(grpKey).append("|");
            }
            String compositeGroupKey = groupKeyBuilder.toString();
            String[] rowValues = dataMap.get(compositeGroupKey);
            if (rowValues == null) {
                rowValues = new String[numCols];
                Arrays.fill(rowValues, "0");
                System.arraycopy(groupKeys, 0, rowValues, 0, groupKeys.length);
                dataMap.put(compositeGroupKey, rowValues);
            }
            rowValues[groupKeys.length + i] = String.valueOf(Double.parseDouble(rowValues[groupKeys.length + i]) + Double.parseDouble(resultSet.getString(r, 0)));
        }
    }
    List<String[]> rows = new ArrayList<>();
    rows.addAll(dataMap.values());
    return rows;
}

67. HelixExternalViewBasedTimeBoundaryService#getTimeUnitFromString()

View license
private TimeUnit getTimeUnitFromString(String timeTypeString) {
    // If input data does not have a time column, no need to fire an exception.
    if ((timeTypeString == null) || timeTypeString.isEmpty()) {
        return null;
    }
    TimeUnit timeUnit = TimeUtils.timeUnitFromString(timeTypeString);
    // Check legacy time formats
    if (timeUnit == null) {
        if (timeTypeString.equalsIgnoreCase(DAYS_SINCE_EPOCH)) {
            timeUnit = TimeUnit.DAYS;
        }
        if (timeTypeString.equalsIgnoreCase(HOURS_SINCE_EPOCH)) {
            timeUnit = TimeUnit.HOURS;
        }
        if (timeTypeString.equalsIgnoreCase(MINUTES_SINCE_EPOCH)) {
            timeUnit = TimeUnit.MINUTES;
        }
        if (timeTypeString.equalsIgnoreCase(SECONDS_SINCE_EPOCH)) {
            timeUnit = TimeUnit.SECONDS;
        }
    }
    if (timeUnit == null) {
        throw new RuntimeException("Not supported time type for: " + timeTypeString);
    }
    return timeUnit;
}

68. HelixExternalViewBasedTimeBoundaryService#updateTimeBoundaryService()

View license
public synchronized void updateTimeBoundaryService(ExternalView externalView) {
    if (_propertyStore == null) {
        return;
    }
    String tableName = externalView.getResourceName();
    // Do nothing for realtime table.
    if (TableNameBuilder.getTableTypeFromTableName(tableName) == TableType.REALTIME) {
        return;
    }
    Set<String> offlineSegmentsServing = externalView.getPartitionSet();
    if (offlineSegmentsServing.isEmpty()) {
        LOGGER.info("Skipping updating time boundary service for table '{}' with no offline segments.", tableName);
        return;
    }
    AbstractTableConfig offlineTableConfig = ZKMetadataProvider.getOfflineTableConfig(_propertyStore, tableName);
    String timeType = offlineTableConfig.getValidationConfig().getTimeType();
    TimeUnit tableTimeUnit = getTimeUnitFromString(timeType);
    if (tableTimeUnit == null) {
        LOGGER.info("Skipping updating time boundary service for table '{}' with null timeUnit, config time type: {}.", tableName, timeType);
        return;
    }
    // Bulk reading all segment zk-metadata at once is more efficient than reading one at a time.
    List<OfflineSegmentZKMetadata> segmentZKMetadataList = ZKMetadataProvider.getOfflineSegmentZKMetadataListForTable(_propertyStore, tableName);
    long maxTimeValue = computeMaxSegmentEndTimeForTable(segmentZKMetadataList, tableTimeUnit);
    TimeBoundaryInfo timeBoundaryInfo = new TimeBoundaryInfo();
    timeBoundaryInfo.setTimeColumn(offlineTableConfig.getValidationConfig().getTimeColumnName());
    timeBoundaryInfo.setTimeValue(Long.toString(maxTimeValue));
    _timeBoundaryInfoMap.put(tableName, timeBoundaryInfo);
    LOGGER.info("Updated time boundary service for table '{}', maxTime: {}", tableName, maxTimeValue);
}

69. ColumnMetadata#fromPropertiesConfiguration()

Project: pinot
Source File: ColumnMetadata.java
View license
public static ColumnMetadata fromPropertiesConfiguration(String column, PropertiesConfiguration config) {
    Builder builder = new Builder();
    builder.setColumnName(column);
    int cardinality = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.CARDINALITY));
    builder.setCardinality(cardinality);
    int totalDocs = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.TOTAL_DOCS));
    builder.setTotalDocs(totalDocs);
    final int totalRawDocs = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.TOTAL_RAW_DOCS), totalDocs);
    builder.setTotalRawDocs(totalRawDocs);
    final int totalAggDocs = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.TOTAL_AGG_DOCS), 0);
    builder.setTotalAggDocs(totalAggDocs);
    final DataType dataType = DataType.valueOf(config.getString(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.DATA_TYPE)));
    builder.setDataType(dataType);
    final int bitsPerElement = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.BITS_PER_ELEMENT));
    builder.setBitsPerElement(bitsPerElement);
    final int stringColumnMaxLength = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.DICTIONARY_ELEMENT_SIZE));
    builder.setStringColumnMaxLength(stringColumnMaxLength);
    final FieldType fieldType = FieldType.valueOf(config.getString(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.COLUMN_TYPE)).toUpperCase());
    builder.setFieldType(fieldType);
    final boolean isSorted = config.getBoolean(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.IS_SORTED));
    builder.setIsSorted(isSorted);
    final boolean hasInvertedIndex = config.getBoolean(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.HAS_INVERTED_INDEX));
    builder.setHasInvertedIndex(hasInvertedIndex);
    final boolean isSingleValue = config.getBoolean(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.IS_SINGLE_VALUED));
    builder.setInSingleValue(isSingleValue);
    final int maxNumberOfMultiValues = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.MAX_MULTI_VALUE_ELEMTS));
    builder.setMaxNumberOfMultiValues(maxNumberOfMultiValues);
    final boolean hasNulls = config.getBoolean(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.HAS_NULL_VALUE));
    builder.setContainsNulls(hasNulls);
    TimeUnit segmentTimeUnit = TimeUnit.DAYS;
    if (config.containsKey(V1Constants.MetadataKeys.Segment.TIME_UNIT)) {
        segmentTimeUnit = TimeUtils.timeUnitFromString(config.getString(TIME_UNIT));
    }
    builder.setTimeunit(segmentTimeUnit);
    final boolean hasDictionary = config.getBoolean(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.HAS_DICTIONARY), true);
    builder.setHasDictionary(hasDictionary);
    final int totalNumberOfEntries = config.getInt(V1Constants.MetadataKeys.Column.getKeyFor(column, V1Constants.MetadataKeys.Column.TOTAL_NUMBER_OF_ENTRIES));
    builder.setTotalNumberOfEntries(totalNumberOfEntries);
    return builder.build();
}

70. TimeUtils#toMillis()

Project: pinot
Source File: TimeUtils.java
View license
/**
   * Converts timeValue in timeUnitString to milliseconds
   * @param timeUnitString the time unit string to convert, such as DAYS or SECONDS
   * @param timeValue the time value to convert to milliseconds
   * @return corresponding value in milliseconds or LONG.MIN_VALUE if timeUnitString is invalid
   *         Returning LONG.MIN_VALUE gives consistent beahvior with the java library
   */
public static long toMillis(String timeUnitString, String timeValue) {
    TimeUnit timeUnit = timeUnitFromString(timeUnitString);
    return (timeUnit == null) ? Long.MIN_VALUE : timeUnit.toMillis(Long.parseLong(timeValue));
}

71. LabelTimeComposite#getTimeUnits()

View license
private String[] getTimeUnits() {
    ArrayList<String> timeUnits = new ArrayList<String>();
    for (TimeUnit timeUnit : TimeUnit.values()) {
        timeUnits.add(timeUnit.toString());
    }
    return timeUnits.toArray(new String[timeUnits.size()]);
}

72. Basic#realMain()

Project: openjdk
Source File: Basic.java
View license
private static void realMain(String[] args) throws Throwable {
    for (TimeUnit u : TimeUnit.values()) {
        System.out.println(u);
        check(u instanceof TimeUnit);
        equal(42L, u.convert(42, u));
        for (TimeUnit v : TimeUnit.values()) if (u.convert(42, v) >= 42)
            equal(42L, v.convert(u.convert(42, v), u));
        check(readObject(serializedForm(u)) == u);
    }
    equal(24L, HOURS.convert(1, DAYS));
    equal(60L, MINUTES.convert(1, HOURS));
    equal(60L, SECONDS.convert(1, MINUTES));
    equal(1000L, MILLISECONDS.convert(1, SECONDS));
    equal(1000L, MICROSECONDS.convert(1, MILLISECONDS));
    equal(1000L, NANOSECONDS.convert(1, MICROSECONDS));
    equal(24L, DAYS.toHours(1));
    equal(60L, HOURS.toMinutes(1));
    equal(60L, MINUTES.toSeconds(1));
    equal(1000L, SECONDS.toMillis(1));
    equal(1000L, MILLISECONDS.toMicros(1));
    equal(1000L, MICROSECONDS.toNanos(1));
    long t0 = System.nanoTime();
    MILLISECONDS.sleep(3);
    /* See windows bug 6313903, might not sleep */
    long elapsedMillis = (System.nanoTime() - t0) / (1000L * 1000L);
    System.out.printf("elapsed=%d%n", elapsedMillis);
    check(elapsedMillis >= 0);
    /* Might not sleep on windows: check(elapsedMillis >= 3); */
    check(elapsedMillis < 1000);
    //----------------------------------------------------------------
    // Tests for serialized form compatibility with previous release
    //----------------------------------------------------------------
    byte[] serializedForm = /* Generated using tiger */
    { -84, -19, 0, 5, '~', 'r', 0, 29, 'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l', '.', 'c', 'o', 'n', 'c', 'u', 'r', 'r', 'e', 'n', 't', '.', 'T', 'i', 'm', 'e', 'U', 'n', 'i', 't', 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 'x', 'r', 0, 14, 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'E', 'n', 'u', 'm', 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 'x', 'p', 't', 0, 7, 'S', 'E', 'C', 'O', 'N', 'D', 'S' };
    check(Arrays.equals(serializedForm(SECONDS), serializedForm));
}

73. TimeUnitTest#testSerialization()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * a deserialized serialized unit is the same instance
     */
public void testSerialization() throws Exception {
    for (TimeUnit x : TimeUnit.values()) assertSame(x, serialClone(x));
}

74. TimeUnitTest#testToNanosSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * toNanos saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testToNanosSaturate() {
    assertEquals(Long.MAX_VALUE, MILLISECONDS.toNanos(Long.MAX_VALUE / 2));
    assertEquals(Long.MIN_VALUE, MILLISECONDS.toNanos(-Long.MAX_VALUE / 3));
    for (TimeUnit x : TimeUnit.values()) {
        long ratio = x.toNanos(1) / NANOSECONDS.toNanos(1);
        if (ratio >= 1) {
            long max = Long.MAX_VALUE / ratio;
            for (long z : new long[] { 0, 1, -1, max, -max }) assertEquals(z * ratio, x.toNanos(z));
            if (max < Long.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toNanos(max + 1));
                assertEquals(Long.MIN_VALUE, x.toNanos(-max - 1));
                assertEquals(Long.MIN_VALUE, x.toNanos(Long.MIN_VALUE + 1));
            }
            assertEquals(Long.MAX_VALUE, x.toNanos(Long.MAX_VALUE));
            assertEquals(Long.MIN_VALUE, x.toNanos(Long.MIN_VALUE));
            if (max < Integer.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, x.toNanos(Integer.MAX_VALUE));
                assertEquals(Long.MIN_VALUE, x.toNanos(Integer.MIN_VALUE));
            }
        }
    }
}

75. TimeUnitTest#testConvertSaturate()

Project: openjdk
Source File: TimeUnitTest.java
View license
/**
     * convert saturates positive too-large values to Long.MAX_VALUE
     * and negative to LONG.MIN_VALUE
     */
public void testConvertSaturate() {
    assertEquals(Long.MAX_VALUE, NANOSECONDS.convert(Long.MAX_VALUE / 2, SECONDS));
    assertEquals(Long.MIN_VALUE, NANOSECONDS.convert(-Long.MAX_VALUE / 4, SECONDS));
    assertEquals(Long.MAX_VALUE, NANOSECONDS.convert(Long.MAX_VALUE / 2, MINUTES));
    assertEquals(Long.MIN_VALUE, NANOSECONDS.convert(-Long.MAX_VALUE / 4, MINUTES));
    assertEquals(Long.MAX_VALUE, NANOSECONDS.convert(Long.MAX_VALUE / 2, HOURS));
    assertEquals(Long.MIN_VALUE, NANOSECONDS.convert(-Long.MAX_VALUE / 4, HOURS));
    assertEquals(Long.MAX_VALUE, NANOSECONDS.convert(Long.MAX_VALUE / 2, DAYS));
    assertEquals(Long.MIN_VALUE, NANOSECONDS.convert(-Long.MAX_VALUE / 4, DAYS));
    for (TimeUnit x : TimeUnit.values()) for (TimeUnit y : TimeUnit.values()) {
        long ratio = x.toNanos(1) / y.toNanos(1);
        if (ratio >= 1) {
            assertEquals(ratio, y.convert(1, x));
            assertEquals(1, x.convert(ratio, y));
            long max = Long.MAX_VALUE / ratio;
            assertEquals(max * ratio, y.convert(max, x));
            assertEquals(-max * ratio, y.convert(-max, x));
            assertEquals(max, x.convert(max * ratio, y));
            assertEquals(-max, x.convert(-max * ratio, y));
            if (max < Long.MAX_VALUE) {
                assertEquals(Long.MAX_VALUE, y.convert(max + 1, x));
                assertEquals(Long.MIN_VALUE, y.convert(-max - 1, x));
                assertEquals(Long.MIN_VALUE, y.convert(Long.MIN_VALUE + 1, x));
            }
            assertEquals(Long.MAX_VALUE, y.convert(Long.MAX_VALUE, x));
            assertEquals(Long.MIN_VALUE, y.convert(Long.MIN_VALUE, x));
        }
    }
}

76. TimeUnitTest#testConvert()

Project: openjdk
Source File: TimeUnitTest.java
View license
// (loops to 88888 check increments at all time divisions.)
/**
     * convert correctly converts sample values across the units
     */
public void testConvert() {
    for (long t = 0; t < 88888; ++t) {
        assertEquals(t * 60 * 60 * 24, SECONDS.convert(t, DAYS));
        assertEquals(t * 60 * 60, SECONDS.convert(t, HOURS));
        assertEquals(t * 60, SECONDS.convert(t, MINUTES));
        assertEquals(t, SECONDS.convert(t, SECONDS));
        assertEquals(t, SECONDS.convert(1000L * t, MILLISECONDS));
        assertEquals(t, SECONDS.convert(1000000L * t, MICROSECONDS));
        assertEquals(t, SECONDS.convert(1000000000L * t, NANOSECONDS));
        assertEquals(1000L * t * 60 * 60 * 24, MILLISECONDS.convert(t, DAYS));
        assertEquals(1000L * t * 60 * 60, MILLISECONDS.convert(t, HOURS));
        assertEquals(1000L * t * 60, MILLISECONDS.convert(t, MINUTES));
        assertEquals(1000L * t, MILLISECONDS.convert(t, SECONDS));
        assertEquals(t, MILLISECONDS.convert(t, MILLISECONDS));
        assertEquals(t, MILLISECONDS.convert(1000L * t, MICROSECONDS));
        assertEquals(t, MILLISECONDS.convert(1000000L * t, NANOSECONDS));
        assertEquals(1000000L * t * 60 * 60 * 24, MICROSECONDS.convert(t, DAYS));
        assertEquals(1000000L * t * 60 * 60, MICROSECONDS.convert(t, HOURS));
        assertEquals(1000000L * t * 60, MICROSECONDS.convert(t, MINUTES));
        assertEquals(1000000L * t, MICROSECONDS.convert(t, SECONDS));
        assertEquals(1000L * t, MICROSECONDS.convert(t, MILLISECONDS));
        assertEquals(t, MICROSECONDS.convert(t, MICROSECONDS));
        assertEquals(t, MICROSECONDS.convert(1000L * t, NANOSECONDS));
        assertEquals(1000000000L * t * 60 * 60 * 24, NANOSECONDS.convert(t, DAYS));
        assertEquals(1000000000L * t * 60 * 60, NANOSECONDS.convert(t, HOURS));
        assertEquals(1000000000L * t * 60, NANOSECONDS.convert(t, MINUTES));
        assertEquals(1000000000L * t, NANOSECONDS.convert(t, SECONDS));
        assertEquals(1000000L * t, NANOSECONDS.convert(t, MILLISECONDS));
        assertEquals(1000L * t, NANOSECONDS.convert(t, MICROSECONDS));
        assertEquals(t, NANOSECONDS.convert(t, NANOSECONDS));
    }
    for (TimeUnit x : TimeUnit.values()) {
        long[] zs = { 0, 1, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE };
        for (long z : zs) assertEquals(z, x.convert(z, x));
    }
}

77. Basic#to()

Project: openjdk
Source File: Basic.java
View license
static void to(long v, TimeUnit unit) {
    FileTime t = FileTime.from(v, unit);
    for (TimeUnit u : TimeUnit.values()) {
        long result = t.to(u);
        long expected = u.convert(v, unit);
        if (result != expected) {
            throw new RuntimeException("unexpected result");
        }
    }
}

78. Basic#to()

Project: openjdk
Source File: Basic.java
View license
static void to(long v, TimeUnit unit) {
    FileTime t = FileTime.from(v, unit);
    for (TimeUnit u : TimeUnit.values()) {
        long result = t.to(u);
        long expected = u.convert(v, unit);
        if (result != expected) {
            throw new RuntimeException("unexpected result");
        }
    }
}

79. Scheduler#schedule()

Project: ninja
Source File: Scheduler.java
View license
private void schedule(final Object target, final Method method, Schedule schedule) {
    long delay = schedule.delay();
    if (!schedule.delayProperty().equals(Schedule.NO_PROPERTY)) {
        String delayString = getProperty(schedule.delayProperty());
        if (delayString != null) {
            delay = Long.parseLong(delayString);
        } else if (delay < 0) {
            throw new IllegalArgumentException("No delay property found: " + schedule.delayProperty() + " and no default delay set");
        }
    }
    if (delay < 0) {
        throw new IllegalArgumentException("No delay or delay property specified");
    }
    TimeUnit timeUnit = schedule.timeUnit();
    if (!schedule.timeUnitProperty().equals(Schedule.NO_PROPERTY)) {
        String timeUnitString = getProperty(schedule.timeUnitProperty());
        if (timeUnitString != null) {
            timeUnit = TimeUnit.valueOf(timeUnitString);
        }
    }
    long initialDelay = schedule.initialDelay();
    if (!schedule.initialDelayProperty().equals(Schedule.NO_PROPERTY)) {
        String initialDelayString = getProperty(schedule.initialDelayProperty());
        if (initialDelayString != null) {
            initialDelay = Long.parseLong(initialDelayString);
        }
    }
    if (initialDelay < 0) {
        initialDelay = delay;
    }
    log.info("Scheduling method " + method.getName() + " on " + target + " to be run every " + delay + " " + timeUnit + " after " + initialDelay + " " + timeUnit);
    executor.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                log.debug("Running scheduled method {} on {}", method.getName(), target);
                method.invoke(target);
            } catch (Exception e) {
                log.error("Error invoking scheduled run of method " + method.getName() + " on " + target, e);
            }
        }
    }, initialDelay, delay, timeUnit);
}

80. Timestamp#compareTo()

Project: newts
Source File: Timestamp.java
View license
@Override
public int compareTo(Timestamp o) {
    TimeUnit unit = finest(getUnit(), o.getUnit());
    return convert(unit) < o.convert(unit) ? -1 : (convert(unit) > o.convert(unit) ? 1 : 0);
}

81. Timestamp#minus()

Project: newts
Source File: Timestamp.java
View license
public Duration minus(Timestamp t) {
    if (t.gt(this))
        throw new IllegalArgumentException("you can only subtract an earlier date from a later one... negative durations don't make sense");
    TimeUnit finest = finest(m_unit, t.getUnit());
    return new Duration(convert(finest) - t.convert(finest), finest);
}

82. Timestamp#minus()

Project: newts
Source File: Timestamp.java
View license
public Timestamp minus(Duration d) {
    TimeUnit finest = finest(m_unit, d.getUnit());
    return new Timestamp(convert(finest) - d.convert(finest), finest);
}

83. Timestamp#minus()

Project: newts
Source File: Timestamp.java
View license
public Timestamp minus(long value, TimeUnit units) {
    TimeUnit finest = finest(m_unit, units);
    return new Timestamp(convert(finest) - finest.convert(value, units), finest);
}

84. Timestamp#plus()

Project: newts
Source File: Timestamp.java
View license
public Timestamp plus(Duration d) {
    TimeUnit finest = finest(m_unit, d.getUnit());
    return new Timestamp(convert(finest) + d.convert(finest), finest);
}

85. Timestamp#plus()

Project: newts
Source File: Timestamp.java
View license
public Timestamp plus(long value, TimeUnit units) {
    TimeUnit finest = finest(m_unit, units);
    return new Timestamp(convert(finest) + finest.convert(value, units), finest);
}

86. Duration#compareTo()

Project: newts
Source File: Duration.java
View license
@Override
public int compareTo(Duration o) {
    TimeUnit unit = Timestamp.finest(getUnit(), o.getUnit());
    return convert(unit) < o.convert(unit) ? -1 : (convert(unit) > o.convert(unit) ? 1 : 0);
}

87. Duration#isMultiple()

Project: newts
Source File: Duration.java
View license
public boolean isMultiple(Duration o) {
    TimeUnit u = Timestamp.finest(getUnit(), o.getUnit());
    return this.gte(o) && ((convert(u) % o.convert(u)) == 0);
}

88. Duration#divideBy()

Project: newts
Source File: Duration.java
View license
public long divideBy(Duration o) {
    TimeUnit u = Timestamp.finest(getUnit(), o.getUnit());
    return convert(u) / o.convert(u);
}

89. Duration#plus()

Project: newts
Source File: Duration.java
View license
public Duration plus(Duration o) {
    TimeUnit u = Timestamp.finest(getUnit(), o.getUnit());
    return new Duration(convert(u) + o.convert(u), u);
}

90. TransformerTest#testExtractEnumName()

Project: mina-sshd
Source File: TransformerTest.java
View license
@Test
public void testExtractEnumName() {
    assertNull("Invalid null result", Transformer.ENUM_NAME_EXTRACTOR.transform(null));
    for (TimeUnit u : TimeUnit.values()) {
        String expected = u.name();
        String actual = Transformer.ENUM_NAME_EXTRACTOR.transform(u);
        assertEquals("Mismatched name", expected, actual);
    }
}

91. IdlePurgePolicy#createPurgePolicy()

Project: logging-log4j2
Source File: IdlePurgePolicy.java
View license
/**
     * Create the PurgePolicy
     *
     * @param timeToLive the number of increments of timeUnit before the Appender should be purged.
     * @param timeUnit   the unit of time the timeToLive is expressed in.
     * @return The Routes container.
     */
@PluginFactory
public static PurgePolicy createPurgePolicy(@PluginAttribute("timeToLive") final String timeToLive, @PluginAttribute("timeUnit") final String timeUnit, @PluginConfiguration final Configuration configuration) {
    if (timeToLive == null) {
        LOGGER.error("A timeToLive  value is required");
        return null;
    }
    TimeUnit units;
    if (timeUnit == null) {
        units = TimeUnit.MINUTES;
    } else {
        try {
            units = TimeUnit.valueOf(timeUnit.toUpperCase());
        } catch (final Exception ex) {
            LOGGER.error("Invalid time unit {}", timeUnit);
            units = TimeUnit.MINUTES;
        }
    }
    final long ttl = units.toMillis(Long.parseLong(timeToLive));
    return new IdlePurgePolicy(ttl, configuration.getScheduler());
}

92. Stopwatch#toString()

Project: light-task-scheduler
Source File: Stopwatch.java
View license
/**
     * Returns a string representation of the current elapsed time.
     */
@Override
public String toString() {
    long nanos = elapsedNanos();
    TimeUnit unit = chooseUnit(nanos);
    double value = (double) nanos / NANOSECONDS.convert(1, unit);
    // Too bad this functionality is not exposed as a regular method call
    return String.format(Locale.ROOT, "%.4g %s", value, abbreviate(unit));
}

93. Stopwatch#toString()

Project: light-task-scheduler
Source File: Stopwatch.java
View license
/**
     * Returns a string representation of the current elapsed time.
     */
@Override
public String toString() {
    long nanos = elapsedNanos();
    TimeUnit unit = chooseUnit(nanos);
    double value = (double) nanos / NANOSECONDS.convert(1, unit);
    // Too bad this functionality is not exposed as a regular method call
    return String.format(Locale.ROOT, "%.4g %s", value, abbreviate(unit));
}

94. DefaultCommandLatencyCollector#getMetric()

View license
private CommandLatency getMetric(Histogram histogram) {
    Map<Double, Long> percentiles = getPercentiles(histogram);
    TimeUnit timeUnit = options.targetUnit();
    CommandLatency metric = new CommandLatency(timeUnit.convert(histogram.getMinValue(), TimeUnit.NANOSECONDS), timeUnit.convert(histogram.getMaxValue(), TimeUnit.NANOSECONDS), percentiles);
    return metric;
}

95. OracleNoSQLPropertySetterTest#testProperties()

View license
@Test
public void testProperties() {
    // Get properties from client
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    OracleNoSQLClient client = (OracleNoSQLClient) clients.get(PU);
    // Check default values
    Durability du = client.getDurability();
    Consistency consist = client.getConsistency();
    TimeUnit tu = client.getTimeUnit();
    Assert.assertNotNull(du);
    Assert.assertNotNull(consist);
    Assert.assertNotNull(tu);
    Assert.assertTrue(du instanceof Durability);
    // Set parameters into EM
    em.setProperty("write.timeout", 5);
    em.setProperty("durability", Durability.COMMIT_NO_SYNC);
    em.setProperty("time.unit", TimeUnit.HOURS);
    em.setProperty("consistency", Consistency.ABSOLUTE);
    em.setProperty(PersistenceProperties.KUNDERA_BATCH_SIZE, 5);
    Assert.assertEquals(5, client.getBatchSize());
    Assert.assertEquals(5, client.getTimeout());
    Assert.assertEquals(TimeUnit.HOURS, client.getTimeUnit());
    Assert.assertEquals(Consistency.ABSOLUTE, client.getConsistency());
    Assert.assertEquals(Durability.COMMIT_NO_SYNC, client.getDurability());
    em.clear();
    // Set parameters into EMas string
    em.setProperty("write.timeout", "10");
    em.setProperty(PersistenceProperties.KUNDERA_BATCH_SIZE, "10");
    em.setProperty("time.unit", "" + TimeUnit.HOURS);
    Assert.assertEquals(10, client.getTimeout());
    Assert.assertEquals(TimeUnit.HOURS, client.getTimeUnit());
    Assert.assertEquals(10, client.getBatchSize());
}

96. DefaultBroadcastService#start()

View license
@LifecycleHandlerType(LifecycleHandlerType.LifecycleLevel.START_SERVICE)
public void start() {
    final TimeUnit pendingRateUnit = broadcastConfig.getBroadcastServiceRunningRate().getUnit();
    final long pendingPeriod = broadcastConfig.getBroadcastServiceRunningRate().getPeriod();
    broadcastExecutor.scheduleAtFixedRate(new BroadcastServiceRunnable(this, broadcastDao, eventBus), pendingPeriod, pendingPeriod, pendingRateUnit);
}

97. TenantCacheInvalidation#start()

View license
public void start() {
    final TimeUnit pendingRateUnit = tenantConfig.getTenantBroadcastServiceRunningRate().getUnit();
    final long pendingPeriod = tenantConfig.getTenantBroadcastServiceRunningRate().getPeriod();
    tenantExecutor.scheduleAtFixedRate(new TenantCacheInvalidationRunnable(this, broadcastDao, tenantDao), pendingPeriod, pendingPeriod, pendingRateUnit);
}

98. OkHttpAdapter#newOkHttpClient()

Project: JRAW
Source File: OkHttpAdapter.java
View license
private static OkHttpClient newOkHttpClient() {
    TimeUnit unit = TimeUnit.SECONDS;
    int timeout = 10;
    return new OkHttpClient.Builder().connectTimeout(timeout, unit).readTimeout(timeout, unit).writeTimeout(timeout, unit).build();
}

99. Basic#realMain()

Project: jdk7u-jdk
Source File: Basic.java
View license
private static void realMain(String[] args) throws Throwable {
    for (TimeUnit u : TimeUnit.values()) {
        System.out.println(u);
        check(u instanceof TimeUnit);
        equal(42L, u.convert(42, u));
        for (TimeUnit v : TimeUnit.values()) if (u.convert(42, v) >= 42)
            equal(42L, v.convert(u.convert(42, v), u));
        check(readObject(serializedForm(u)) == u);
    }
    equal(24L, HOURS.convert(1, DAYS));
    equal(60L, MINUTES.convert(1, HOURS));
    equal(60L, SECONDS.convert(1, MINUTES));
    equal(1000L, MILLISECONDS.convert(1, SECONDS));
    equal(1000L, MICROSECONDS.convert(1, MILLISECONDS));
    equal(1000L, NANOSECONDS.convert(1, MICROSECONDS));
    equal(24L, DAYS.toHours(1));
    equal(60L, HOURS.toMinutes(1));
    equal(60L, MINUTES.toSeconds(1));
    equal(1000L, SECONDS.toMillis(1));
    equal(1000L, MILLISECONDS.toMicros(1));
    equal(1000L, MICROSECONDS.toNanos(1));
    long t0 = System.nanoTime();
    MILLISECONDS.sleep(3);
    /* See windows bug 6313903, might not sleep */
    long elapsedMillis = (System.nanoTime() - t0) / (1000L * 1000L);
    System.out.printf("elapsed=%d%n", elapsedMillis);
    check(elapsedMillis >= 0);
    /* Might not sleep on windows: check(elapsedMillis >= 3); */
    check(elapsedMillis < 1000);
    //----------------------------------------------------------------
    // Tests for serialized form compatibility with previous release
    //----------------------------------------------------------------
    byte[] serializedForm = /* Generated using tiger */
    { -84, -19, 0, 5, '~', 'r', 0, 29, 'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l', '.', 'c', 'o', 'n', 'c', 'u', 'r', 'r', 'e', 'n', 't', '.', 'T', 'i', 'm', 'e', 'U', 'n', 'i', 't', 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 'x', 'r', 0, 14, 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'E', 'n', 'u', 'm', 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 'x', 'p', 't', 0, 7, 'S', 'E', 'C', 'O', 'N', 'D', 'S' };
    check(Arrays.equals(serializedForm(SECONDS), serializedForm));
}

100. Basic#to()

Project: jdk7u-jdk
Source File: Basic.java
View license
static void to(long v, TimeUnit unit) {
    FileTime t = FileTime.from(v, unit);
    for (TimeUnit u : TimeUnit.values()) {
        long result = t.to(u);
        long expected = u.convert(v, unit);
        if (result != expected) {
            throw new RuntimeException("unexpected result");
        }
    }
}