Here are the examples of the java api class java.util.concurrent.TimeUnit taken from open source projects.
1. Duration#convertToMostSuccinctTimeUnit()
View licensepublic 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); }
2. 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(); }
3. 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); }
4. ShortDuration#createAbbreviations()
View licenseprivate 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(); }
5. JobTest#testWaitForWithCheckingPeriod()
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); }
6. JobTest#testWaitForWithCheckingPeriod_Null()
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); }
7. OperationTest#testWaitForCheckingPeriod()
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); }
8. OperationTest#testWaitForCheckingPeriod_Null()
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); }
9. OperationTest#testWaitForWithTimeout()
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); }
10. 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); }
11. 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); }
12. 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); }
13. Janitor#start()
View licensepublic 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); }
14. 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(); }
15. Duration#valueOf()
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); }
16. 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(); }
17. TimeUtil#getTimeUnit()
View licensepublic static TimeUnit getTimeUnit(String timeUnit, TimeUnit defaultUnit) { TimeUnit timeUnit_ = TimeUnit.SECONDS; try { timeUnit_ = TimeUnit.valueOf(timeUnit); } catch (Exception e) { timeUnit_ = defaultUnit; } return timeUnit_; }
18. Processor#getDuration()
View licensepublic 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; }
19. NetworkStatsKeeper#scheduleDownloadSpeedCalculation()
View licenseprivate 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); }
20. ShortDuration#valueOf()
View licensepublic 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); }
21. ManagedShutdownStrategyTest#testManagedShutdownStrategy()
View licensepublic 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)); }
22. CamelAnnotationsHandler#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 */ 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); } }); }
23. 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); } }); }
24. FindThroughputTest#testFindPerformance1()
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(); }
25. FindThroughputTest#testFindPerformance2()
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(); }
26. Duration#parse()
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); }
27. AbstractValueHolder#accessed()
View licensepublic 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); }
28. FakeTickerTest#testAutoIncrementStep_resetToZero()
View licensepublic 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()); } }
29. DurationExpression#divide()
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); }
30. QueryListener#exitExpressionDuration()
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)); }
31. DruidSinkIT#getTrackerEvent()
View licenseprivate 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. 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); }
33. RequestTest#testSetConnectTimeout_1()
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) }
34. RequestTest#testSetReadTimeout_1()
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) }
35. 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); }
36. 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); }
37. TimeUnit8Test#testToChronoUnit()
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())); }
38. TimeUnitTest#testToMicrosSaturate()
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)); } } } }
39. TimeUnitTest#testToMillisSaturate()
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)); } } } }
40. TimeUnitTest#testToSecondsSaturate()
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)); } } } }
41. TimeUnitTest#testToMinutesSaturate()
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)); } } }
42. TimeUnitTest#testToHoursSaturate()
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)); } } }
43. ZKMetadataUtils#extractTimeUnitFromDuration()
View licenseprivate 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; }
44. EmailReportJob#calculateGraphDataStart()
View licenseprivate 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; }
45. 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"); } }
46. ExecutionEngineImpl#activate()
View licenseprotected 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); }
47. MoreCollectorsTest#testToEnumSet()
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)); }
48. SleepTimerDialog#readTimeMillis()
View licenseprivate long readTimeMillis() { TimeUnit selectedUnit = units[spTimeUnit.getSelectedItemPosition()]; long value = Long.parseLong(etxtTime.getText().toString()); return selectedUnit.toMillis(value); }
49. 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); } } }
50. JobTest#testWaitForWithTimeout()
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); }
51. 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); }
52. 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); }
53. MetricsServlet#init()
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); }
54. 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); }
55. 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); }
56. GstVideoPanel#captureFrames()
View license/** * @param file a video file from which to capture frames * @param numFrames the number of frames to capture. These frames will be * captured at successive intervals given by * durationOfVideo/numFrames. If this frame interval is * less than MIN_FRAME_INTERVAL_MILLIS, then only one frame * will be captured and returned. * * @return a List of VideoFrames representing the captured frames. */ @Override public List<VideoFrame> captureFrames(java.io.File file, int numFrames) throws Exception { List<VideoFrame> frames = new ArrayList<>(); Object lock = new Object(); FrameCaptureRGBListener rgbListener = new FrameCaptureRGBListener(lock); if (!isInited()) { return frames; } // throw exception if this file is known to be problematic if (badVideoFiles.contains(file.getName())) { throw new Exception(NbBundle.getMessage(this.getClass(), "GstVideoPanel.exception.problemFile.msg", file.getName())); } // set up a PlayBin2 object //NON-NLS RGBDataSink videoSink = new RGBDataSink("rgb", rgbListener); //NON-NLS PlayBin2 playbin = new PlayBin2("VideoFrameCapture"); playbin.setInputFile(file); playbin.setVideoSink(videoSink); // this is necessary to get a valid duration value StateChangeReturn ret = playbin.play(); if (ret == StateChangeReturn.FAILURE) { // add this file to the set of known bad ones badVideoFiles.add(file.getName()); throw new Exception(NbBundle.getMessage(this.getClass(), "GstVideoPanel.exception.problemPlay.msg")); } ret = playbin.pause(); if (ret == StateChangeReturn.FAILURE) { // add this file to the set of known bad ones badVideoFiles.add(file.getName()); throw new Exception(NbBundle.getMessage(this.getClass(), "GstVideoPanel.exception.problemPause.msg")); } playbin.getState(); // get the duration of the video TimeUnit unit = TimeUnit.MILLISECONDS; long myDurationMillis = playbin.queryDuration(unit); if (myDurationMillis <= 0) { return frames; } // calculate the number of frames to capture int numFramesToGet = numFrames; long frameInterval = myDurationMillis / numFrames; if (frameInterval < MIN_FRAME_INTERVAL_MILLIS) { numFramesToGet = 1; } // for each timeStamp, grap a frame for (int i = 0; i < numFramesToGet; ++i) { long timeStamp = i * frameInterval; ret = playbin.pause(); if (ret == StateChangeReturn.FAILURE) { // add this file to the set of known bad ones badVideoFiles.add(file.getName()); throw new Exception(NbBundle.getMessage(this.getClass(), "GstVideoPanel.exception.problemPauseCaptFrame.msg")); } playbin.getState(); if (!playbin.seek(timeStamp, unit)) { //NON-NLS logger.log(Level.INFO, "There was a problem seeking to " + timeStamp + " " + unit.name().toLowerCase()); } ret = playbin.play(); if (ret == StateChangeReturn.FAILURE) { // add this file to the set of known bad ones badVideoFiles.add(file.getName()); throw new Exception(NbBundle.getMessage(this.getClass(), "GstVideoPanel.exception.problemPlayCaptFrame.msg")); } // wait for FrameCaptureRGBListener to finish synchronized (lock) { try { lock.wait(FRAME_CAPTURE_TIMEOUT_MILLIS); } catch (InterruptedException e) { logger.log(Level.INFO, "InterruptedException occurred while waiting for frame capture.", e); } } Image image = rgbListener.getImage(); ret = playbin.stop(); if (ret == StateChangeReturn.FAILURE) { // add this file to the set of known bad ones badVideoFiles.add(file.getName()); throw new Exception(NbBundle.getMessage(this.getClass(), "GstVideoPanel.exception.problemStopCaptFrame.msg")); } if (image == null) { //NON-NLS logger.log(Level.WARNING, "There was a problem while trying to capture a frame from file " + file.getName()); badVideoFiles.add(file.getName()); break; } frames.add(new VideoFrame(image, timeStamp)); } return frames; }
57. TimeUtil#getTimeUnitByName()
View licensepublic static TimeUnit getTimeUnitByName(String timeUnit, TimeUnit defaultTimeUnit) { TimeUnit timeUnit_ = TimeUnit.SECONDS; if (timeUnit.equals("TimeUnit.SECONDS")) { timeUnit_ = TimeUnit.SECONDS; } else if (timeUnit.equals("TimeUnit.DAYS")) { try { timeUnit_ = TimeUnit.valueOf("DAYS"); } catch (Exception e) { timeUnit_ = defaultTimeUnit; } } if (timeUnit.equals("TimeUnit.HOURS")) { try { timeUnit_ = TimeUnit.valueOf("HOURS"); } catch (Exception e) { timeUnit_ = defaultTimeUnit; } // timeUnit_ = TimeUnit.HOURS; } else if (timeUnit.equals("TimeUnit.MICROSECONDS")) { timeUnit_ = TimeUnit.MICROSECONDS; } else if (timeUnit.equals("TimeUnit.MILLISECONDS")) { timeUnit_ = TimeUnit.MILLISECONDS; } else if (timeUnit.equals("TimeUnit.MINUTES")) { try { timeUnit_ = TimeUnit.valueOf("MINUTES"); } catch (Exception e) { timeUnit_ = defaultTimeUnit; } } else if (timeUnit.equals("TimeUnit.NANOSECONDS")) { timeUnit_ = TimeUnit.NANOSECONDS; } return timeUnit_; }
58. TorConfigProxy#setIntervalValue()
View licenseprivate void setIntervalValue(String varName, Object[] args) { if (!(args[0] instanceof Long && args[1] instanceof TimeUnit)) { throw new IllegalArgumentException(); } final long time = (Long) args[0]; final TimeUnit unit = (TimeUnit) args[1]; final TorConfigInterval interval = new TorConfigInterval(time, unit); configValues.put(varName, interval); }
59. ShortDuration#createUnitToPicosMap()
View licenseprivate static Map<TimeUnit, BigDecimal> createUnitToPicosMap() { Map<TimeUnit, BigDecimal> map = Maps.newEnumMap(TimeUnit.class); for (TimeUnit unit : TimeUnit.values()) { map.put(unit, new BigDecimal(picosIn(unit))); } return Collections.unmodifiableMap(map); }
60. ShortDuration#createMaxesMap()
View licenseprivate static Map<TimeUnit, Long> createMaxesMap() { Map<TimeUnit, Long> map = Maps.newEnumMap(TimeUnit.class); for (TimeUnit unit : TimeUnit.values()) { // Max is 100 days map.put(unit, unit.convert(100L * 24 * 60 * 60, TimeUnit.SECONDS)); } return Collections.unmodifiableMap(map); }
61. TimeUnitAdapter#unmarshal()
View license@Override public TimeUnit unmarshal(String v) throws Exception { TimeUnit result = null; if (v != null) { result = TimeUnit.valueOf(v.toUpperCase(Locale.ENGLISH)); } return result; }
62. ConcourseBenchmarkTest#afterEachTest()
View license@Override public void afterEachTest() { TimeUnit unit = desiredTimeUnit(); for (Map.Entry<String, Stopwatch> entry : benchmarks.entrySet()) { System.out.println("Benchmark " + entry.getKey() + " took " + entry.getValue().elapsed(unit) + " " + unit.name().toLowerCase()); } super.afterEachTest(); }
63. ConcourseBenchmarkTest#assertFasterThan()
View license/** * Assert that the {@code faster} benchmark ran in less time than the * {@code slower} benchmark. * * @param faster the name of the benchmark that is expected to be faster * @param slower the name of the benchmark that is expected to be slower */ protected void assertFasterThan(String faster, String slower) { Stopwatch f = benchmarks.get(faster); Stopwatch s = benchmarks.get(slower); TimeUnit unit = desiredTimeUnit(); Preconditions.checkArgument(f != null, "% is not a valid benchmark", faster); Preconditions.checkArgument(s != null, "% is not a valid benchmark", slower); Assert.assertTrue(f.elapsed(unit) < s.elapsed(unit)); }
64. SimpleConfig#parseDuration()
View license/** * Parses a duration string. If no units are specified in the string, it is * assumed to be in milliseconds. The returned duration is in nanoseconds. * The purpose of this function is to implement the duration-related methods * in the ConfigObject interface. * * @param input * the string to parse * @param originForException * origin of the value being parsed * @param pathForException * path to include in exceptions * @return duration in nanoseconds * @throws ConfigException * if string is invalid */ public static long parseDuration(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String originalUnitString = getUnits(s); String unitString = originalUnitString; String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); TimeUnit units = null; // is more helpful if we check it here. if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in duration value '" + input + "'"); if (unitString.length() > 2 && !unitString.endsWith("s")) unitString = unitString + "s"; // note that this is deliberately case-sensitive if (unitString.equals("") || unitString.equals("ms") || unitString.equals("millis") || unitString.equals("milliseconds")) { units = TimeUnit.MILLISECONDS; } else if (unitString.equals("us") || unitString.equals("micros") || unitString.equals("microseconds")) { units = TimeUnit.MICROSECONDS; } else if (unitString.equals("ns") || unitString.equals("nanos") || unitString.equals("nanoseconds")) { units = TimeUnit.NANOSECONDS; } else if (unitString.equals("d") || unitString.equals("days")) { units = TimeUnit.DAYS; } else if (unitString.equals("h") || unitString.equals("hours")) { units = TimeUnit.HOURS; } else if (unitString.equals("s") || unitString.equals("seconds")) { units = TimeUnit.SECONDS; } else if (unitString.equals("m") || unitString.equals("minutes")) { units = TimeUnit.MINUTES; } else { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse time unit '" + originalUnitString + "' (try ns, us, ms, s, m, h, d)"); } try { // otherwise as a double. if (numberString.matches("[+-]?[0-9]+")) { return units.toNanos(Long.parseLong(numberString)); } else { long nanosInUnit = units.toNanos(1); return (long) (Double.parseDouble(numberString) * nanosInUnit); } } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse duration number '" + numberString + "'"); } }
65. HashedWheelTimerCloseable#newInstance()
View licensepublic static HashedWheelTimerCloseable newInstance(@Nullable ThreadFactory threadFactory, @Nullable Long duration, @Nullable Integer ticksPerWheel) { TimeUnit unit = TimeUnit.MILLISECONDS; if (!nullOrNonZero(duration) && threadFactory == null && nullOrNonZero(ticksPerWheel)) { return new HashedWheelTimerCloseable(new HashedWheelTimer(duration, unit)); } if (!nullOrNonZero(duration) && threadFactory == null && !nullOrNonZero(ticksPerWheel)) { return new HashedWheelTimerCloseable(new HashedWheelTimer(duration, unit, ticksPerWheel)); } if (nullOrNonZero(duration) && threadFactory != null && nullOrNonZero(ticksPerWheel)) { return new HashedWheelTimerCloseable(new HashedWheelTimer(threadFactory)); } if (!nullOrNonZero(duration) && threadFactory != null && nullOrNonZero(ticksPerWheel)) { return new HashedWheelTimerCloseable(new HashedWheelTimer(threadFactory, duration, unit)); } if (!nullOrNonZero(duration) && threadFactory != null && !nullOrNonZero(ticksPerWheel)) { return new HashedWheelTimerCloseable(new HashedWheelTimer(threadFactory, duration, unit, ticksPerWheel)); } return new HashedWheelTimerCloseable(new HashedWheelTimer()); }
66. ConfigHelper#parseDuration()
View license/** * Parses a duration string of the format: duration_value [duration_unit]. duration_value must be * a non-negative integer. Available duration_units are: * <ul> * <li>ns|nanos|nanosecond|nanoseconds - nanoseconds * <li>us|micros|microsecond|microseconds - microseconds * <li>ms|millis|millisecond|milliseconds - milliseconds * <li>s|sec|second|seconds - seconds * <li>min|minute|minutes - minutes * <li>h|hr|hour|hours - hours * <li>d|day|days - days * </ul> * @param durationStr the string to be parsed * @param defaultUnit the unit to use if none is specified * @return the duration in defaultUnit units * @throws InvalidConfigException if the duration string does not follow the above pattern * */ public static long parseDuration(String durationStr, TimeUnit defaultUnit) throws InvalidConfigException { if (null == durationStr) return 0; TimeUnit unit = defaultUnit; Matcher m = DURATION_PATTERN.matcher(durationStr); if (!m.matches()) throw new InvalidConfigException("invalid duration string: " + durationStr); if (1 < m.groupCount() && null != m.group(2) && 0 < m.group(2).length()) { char unitChar1 = m.group(2).charAt(0); switch(unitChar1) { case 'n': case 'N': unit = TimeUnit.NANOSECONDS; break; case 'u': case 'U': unit = TimeUnit.MICROSECONDS; break; case 'm': case 'M': char unitChar3 = m.group(2).length() >= 3 ? m.group(2).charAt(2) : ' '; unit = ('n' == unitChar3 || 'N' == unitChar3) ? TimeUnit.MINUTES : TimeUnit.MILLISECONDS; break; case 's': case 'S': unit = TimeUnit.SECONDS; break; case 'h': case 'H': unit = TimeUnit.HOURS; break; case 'd': case 'D': unit = TimeUnit.DAYS; break; } } long value = Long.parseLong(m.group(1)); return defaultUnit.convert(value, unit); }
67. OSMApplyDiffOp#parseDiffFileAndInsert()
View licensepublic OSMReport parseDiffFileAndInsert() { final WorkingTree workTree = workingTree(); final int queueCapacity = 100 * 1000; final int timeout = 1; final TimeUnit timeoutUnit = TimeUnit.SECONDS; // With this iterator and the osm parsing happening on a separate thread, we follow a // producer/consumer approach so that the osm parse thread produces features into the // iterator's queue, and WorkingTree.insert consumes them on this thread QueueIterator<Feature> target = new QueueIterator<Feature>(queueCapacity, timeout, timeoutUnit); XmlChangeReader reader = new XmlChangeReader(file, true, resolveCompressionMethod(file)); ProgressListener progressListener = getProgressListener(); ConvertAndImportSink sink = new ConvertAndImportSink(target, context, workingTree(), platform(), new SubProgressListener(progressListener, 100)); reader.setChangeSink(sink); Thread readerThread = new Thread(reader, "osm-diff-reader-thread"); readerThread.start(); // used to set the task status name, but report no progress so it does not interfere // with the progress reported by the reader thread SubProgressListener noProgressReportingListener = new SubProgressListener(progressListener, 0) { @Override public void setProgress(float progress) { // no-op } }; Function<Feature, String> parentTreePathResolver = new Function<Feature, String>() { @Override public String apply(Feature input) { return input.getType().getName().getLocalPart(); } }; workTree.insert(parentTreePathResolver, target, noProgressReportingListener, null, null); OSMReport report = new OSMReport(sink.getCount(), sink.getNodeCount(), sink.getWayCount(), sink.getUnprocessedCount(), sink.getLatestChangeset(), sink.getLatestTimestamp()); return report; }
68. OSMImportOp#parseDataFileAndInsert()
View licenseprivate OSMReport parseDataFileAndInsert(@Nullable File file, final InputStream dataIn, final EntityConverter converter) { final boolean pbf; final CompressionMethod compression; if (file == null) { pbf = false; compression = CompressionMethod.None; } else { pbf = file.getName().endsWith(".pbf"); compression = resolveCompressionMethod(file); } RunnableSource reader; if (pbf) { reader = new OsmosisReader(dataIn); } else { reader = new org.locationtech.geogig.osm.internal.XmlReader(dataIn, true, compression); } final WorkingTree workTree = workingTree(); if (!add) { workTree.delete(OSMUtils.NODE_TYPE_NAME); workTree.delete(OSMUtils.WAY_TYPE_NAME); } final int queueCapacity = 100 * 1000; final int timeout = 1; final TimeUnit timeoutUnit = TimeUnit.SECONDS; // With this iterator and the osm parsing happening on a separate thread, we follow a // producer/consumer approach so that the osm parse thread produces featrures into the // iterator's queue, and WorkingTree.insert consumes them on this thread QueueIterator<Feature> iterator = new QueueIterator<Feature>(queueCapacity, timeout, timeoutUnit); ProgressListener progressListener = getProgressListener(); ConvertAndImportSink sink = new ConvertAndImportSink(converter, iterator, platform(), mapping, noRaw, new SubProgressListener(progressListener, 100)); reader.setSink(sink); Thread readerThread = new Thread(reader, "osm-import-reader-thread"); readerThread.start(); Function<Feature, String> parentTreePathResolver = new Function<Feature, String>() { @Override public String apply(Feature input) { if (input instanceof MappedFeature) { return ((MappedFeature) input).getPath(); } return input.getType().getName().getLocalPart(); } }; // used to set the task status name, but report no progress so it does not interfere // with the progress reported by the reader thread SubProgressListener noPorgressReportingListener = new SubProgressListener(progressListener, 0) { @Override public void setProgress(float progress) { // no-op } }; workTree.insert(parentTreePathResolver, iterator, noPorgressReportingListener, null, null); if (sink.getCount() == 0) { throw new EmptyOSMDownloadException(); } OSMReport report = new OSMReport(sink.getCount(), sink.getNodeCount(), sink.getWayCount(), sink.getUnprocessedCount(), sink.getLatestChangeset(), sink.getLatestTimestamp()); return report; }
69. Description#getTimeUnit()
View licensepublic static TimeUnit getTimeUnit(String unit) { if (Strings.isNullOrEmpty(unit)) { throw new IllegalArgumentException("no unit configured"); } TimeUnit u = TIME_UNITS.get(unit); if (u == null) { throw new IllegalArgumentException(String.format("unit %s not TimeUnit", unit)); } return u; }
70. ConfigUtil#getTimeUnit()
View license/** * Parse a numerical time unit, such as "1 minute", from a string. * * @param valueString the string to parse. * @param defaultValue default value to return if no value was set in the * configuration file. * @param wantUnit the units of {@code defaultValue} and the return value, as * well as the units to assume if the value does not contain an * indication of the units. * @return the setting, or {@code defaultValue} if not set, expressed in * {@code units}. */ public static long getTimeUnit(final String valueString, long defaultValue, TimeUnit wantUnit) { Matcher m = Pattern.compile("^(0|[1-9][0-9]*)\\s*(.*)$").matcher(valueString); if (!m.matches()) { return defaultValue; } String digits = m.group(1); String unitName = m.group(2).trim(); TimeUnit inputUnit; int inputMul; if ("".equals(unitName)) { inputUnit = wantUnit; inputMul = 1; } else if (match(unitName, "ms", "milliseconds")) { inputUnit = TimeUnit.MILLISECONDS; inputMul = 1; } else if (match(unitName, "s", "sec", "second", "seconds")) { inputUnit = TimeUnit.SECONDS; inputMul = 1; } else if (match(unitName, "m", "min", "minute", "minutes")) { inputUnit = TimeUnit.MINUTES; inputMul = 1; } else if (match(unitName, "h", "hr", "hour", "hours")) { inputUnit = TimeUnit.HOURS; inputMul = 1; } else if (match(unitName, "d", "day", "days")) { inputUnit = TimeUnit.DAYS; inputMul = 1; } else if (match(unitName, "w", "week", "weeks")) { inputUnit = TimeUnit.DAYS; inputMul = 7; } else if (match(unitName, "mon", "month", "months")) { inputUnit = TimeUnit.DAYS; inputMul = 30; } else if (match(unitName, "y", "year", "years")) { inputUnit = TimeUnit.DAYS; inputMul = 365; } else { throw notTimeUnit(valueString); } try { return wantUnit.convert(Long.parseLong(digits) * inputMul, inputUnit); } catch (NumberFormatException nfe) { throw notTimeUnit(valueString); } }
71. GobblinMetrics#startMetricReporting()
View license/** * Start metric reporting. * * @param properties configuration properties */ public void startMetricReporting(Properties properties) { if (this.metricsReportingStarted) { LOGGER.warn("Metric reporting has already started"); return; } TimeUnit reportTimeUnit = TimeUnit.MILLISECONDS; long reportInterval = Long.parseLong(properties.getProperty(ConfigurationKeys.METRICS_REPORT_INTERVAL_KEY, ConfigurationKeys.DEFAULT_METRICS_REPORT_INTERVAL)); ScheduledReporter.setReportingInterval(properties, reportInterval, reportTimeUnit); // Build and start the JMX reporter buildJmxMetricReporter(properties); if (this.jmxReporter.isPresent()) { LOGGER.info("Will start reporting metrics to JMX"); this.jmxReporter.get().start(); } // Build all other reporters buildFileMetricReporter(properties); buildKafkaMetricReporter(properties); buildGraphiteMetricReporter(properties); buildInfluxDBMetricReporter(properties); buildCustomMetricReporters(properties); // Start reporters that implement gobblin.metrics.report.ScheduledReporter RootMetricContext.get().startReporting(); // Start reporters that implement com.codahale.metrics.ScheduledReporter for (com.codahale.metrics.ScheduledReporter scheduledReporter : this.scheduledReporters) { scheduledReporter.start(reportInterval, reportTimeUnit); } this.metricsReportingStarted = true; }
72. Stopwatch#toString()
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 Platform.formatCompact4Digits(value) + " " + abbreviate(unit); }
73. LocalCacheTest#testSetExpireAfterWrite()
View licensepublic void testSetExpireAfterWrite() { long duration = 42; TimeUnit unit = TimeUnit.SECONDS; LocalCache<Object, Object> map = makeLocalCache(createCacheBuilder().expireAfterWrite(duration, unit)); assertEquals(unit.toNanos(duration), map.expireAfterWriteNanos); }
74. LocalCacheTest#testSetExpireAfterAccess()
View licensepublic void testSetExpireAfterAccess() { long duration = 42; TimeUnit unit = TimeUnit.SECONDS; LocalCache<Object, Object> map = makeLocalCache(createCacheBuilder().expireAfterAccess(duration, unit)); assertEquals(unit.toNanos(duration), map.expireAfterAccessNanos); }
75. LocalCacheTest#testSetRefresh()
View licensepublic void testSetRefresh() { long duration = 42; TimeUnit unit = TimeUnit.SECONDS; LocalCache<Object, Object> map = makeLocalCache(createCacheBuilder().refreshAfterWrite(duration, unit)); assertEquals(unit.toNanos(duration), map.refreshNanos); }
76. Duration#parseDuration()
View license// @formatter:on public static Duration parseDuration(final String string) { final Matcher m = PATTERN.matcher(string); if (!m.matches()) { throw new IllegalArgumentException("Invalid duration: " + string); } final long duration = Long.parseLong(m.group(1)); final String unitString = m.group(2); if (unitString.isEmpty()) { return new Duration(duration, DEFAULT_UNIT); } if ("w".equals(unitString)) { return new Duration(duration * 7, TimeUnit.DAYS); } final TimeUnit unit = units.get(unitString); if (unit == null) { throw new IllegalArgumentException("Invalid unit (" + unitString + ") in duration: " + string); } return new Duration(duration, unit); }
77. VisibilityFenceTest#testFenceTimeout()
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()); }
78. ScheduleForActorFunction#apply()
View license@Override public ScheduleForActorMethod apply(final Method m) { // Check for annotation final ScheduleForActor annonation = m.getAnnotation(ScheduleForActor.class); if (annonation == null) { return null; } // Annotation info final long initialDelay = annonation.initialDelay(); final long period = annonation.period(); final TimeUnit unit = annonation.unit(); // Check annotation info if (initialDelay < 0) { throw new IllegalArgumentException("Initial delay cannot be negative"); } else if (period < 0) { throw new IllegalArgumentException("Period cannot be negative"); } // Basic check method signature checkNoParams(m); checkNotDefault(m); // Get constructor for action Constructor<?> constructor = null; for (final Constructor<?> con : annonation.action().getConstructors()) { // Check for zero arg if (con.getParameterCount() == 0) { constructor = con; break; } } // Check constructor if (constructor == null) { throw new IllegalArgumentException(String.format("Action type %s has no public statically accessible zero argument constructor", annonation.action())); } // Check return type if (hasReturnType(m)) { // Check context if (!returnTypeIs(m, ActionContext.class)) { throw new IllegalArgumentException("Return type must be void or context"); } // Check context type final Type contextType = firstGenericTypeArg(m.getGenericReturnType()); if (!Entity.class.equals(toClass(contextType))) { throw new IllegalArgumentException("Context type must be entity"); } } // Create new schedule action method return new ScheduleForActorMethod(constructor, initialDelay, period, unit); }
79. IncrementalSimonsPurgerTest#testPeriodicalIncrementalSimonsPurge()
View license@Test(dataProvider = "managersDataProvider") public void testPeriodicalIncrementalSimonsPurge(Manager manager) { IncrementalSimonsPurger incrementalSimonsPurger = new IncrementalSimonsPurger(manager, executorService); long duration = 1; TimeUnit timeUnit = TimeUnit.SECONDS; incrementalSimonsPurger.start(duration, timeUnit); verify(executorService).scheduleWithFixedDelay(argThat(new PurgerRunnableMatcher(manager)), eq(duration), eq(duration), eq(timeUnit)); }
80. Basic#main()
View licensepublic static void main(String[] args) { long now = System.currentTimeMillis(); long tomorrowInDays = TimeUnit.DAYS.convert(now, MILLISECONDS) + 1; long yesterdayInDays = TimeUnit.DAYS.convert(now, MILLISECONDS) - 1; // equals eq(now, MILLISECONDS, now, MILLISECONDS); eq(now, MILLISECONDS, now * 1000L, MICROSECONDS); neq(now, MILLISECONDS, 0, MILLISECONDS); neq(now, MILLISECONDS, 0, MICROSECONDS); // compareTo cmp(now, MILLISECONDS, now, MILLISECONDS, 0); cmp(now, MILLISECONDS, now * 1000L, MICROSECONDS, 0); cmp(now, MILLISECONDS, now - 1234, MILLISECONDS, 1); cmp(now, MILLISECONDS, now + 1234, MILLISECONDS, -1); cmp(tomorrowInDays, DAYS, now, MILLISECONDS, 1); cmp(now, MILLISECONDS, tomorrowInDays, DAYS, -1); cmp(yesterdayInDays, DAYS, now, MILLISECONDS, -1); cmp(now, MILLISECONDS, yesterdayInDays, DAYS, 1); cmp(yesterdayInDays, DAYS, now, MILLISECONDS, -1); cmp(Long.MAX_VALUE, DAYS, Long.MAX_VALUE, NANOSECONDS, 1); cmp(Long.MAX_VALUE, DAYS, Long.MIN_VALUE, NANOSECONDS, 1); cmp(Long.MIN_VALUE, DAYS, Long.MIN_VALUE, NANOSECONDS, -1); cmp(Long.MIN_VALUE, DAYS, Long.MAX_VALUE, NANOSECONDS, -1); // to(TimeUnit) to(MILLISECONDS.convert(1, DAYS) - 1, MILLISECONDS); to(MILLISECONDS.convert(1, DAYS) + 0, MILLISECONDS); to(MILLISECONDS.convert(1, DAYS) + 1, MILLISECONDS); to(1, MILLISECONDS); to(0, MILLISECONDS); to(1, MILLISECONDS); to(MILLISECONDS.convert(-1, DAYS) - 1, MILLISECONDS); to(MILLISECONDS.convert(-1, DAYS) + 0, MILLISECONDS); to(MILLISECONDS.convert(-1, DAYS) + 1, MILLISECONDS); for (TimeUnit unit : TimeUnit.values()) { for (int i = 0; i < 100; i++) { to(rand.nextLong(), unit); } to(Long.MIN_VALUE, unit); to(Long.MAX_VALUE, unit); } // toString ts(1L, DAYS, "1970-01-02T00:00:00Z"); ts(1L, HOURS, "1970-01-01T01:00:00Z"); ts(1L, MINUTES, "1970-01-01T00:01:00Z"); ts(1L, SECONDS, "1970-01-01T00:00:01Z"); ts(1L, MILLISECONDS, "1970-01-01T00:00:00.001Z"); ts(1L, MICROSECONDS, "1970-01-01T00:00:00.000001Z"); ts(1L, NANOSECONDS, "1970-01-01T00:00:00.000000001Z"); ts(999999999L, NANOSECONDS, "1970-01-01T00:00:00.999999999Z"); ts(9999999999L, NANOSECONDS, "1970-01-01T00:00:09.999999999Z"); ts(-1L, DAYS, "1969-12-31T00:00:00Z"); ts(-1L, HOURS, "1969-12-31T23:00:00Z"); ts(-1L, MINUTES, "1969-12-31T23:59:00Z"); ts(-1L, SECONDS, "1969-12-31T23:59:59Z"); ts(-1L, MILLISECONDS, "1969-12-31T23:59:59.999Z"); ts(-1L, MICROSECONDS, "1969-12-31T23:59:59.999999Z"); ts(-1L, NANOSECONDS, "1969-12-31T23:59:59.999999999Z"); ts(-999999999L, NANOSECONDS, "1969-12-31T23:59:59.000000001Z"); ts(-9999999999L, NANOSECONDS, "1969-12-31T23:59:50.000000001Z"); ts(-62135596799999L, MILLISECONDS, "0001-01-01T00:00:00.001Z"); ts(-62135596800000L, MILLISECONDS, "0001-01-01T00:00:00Z"); ts(-62135596800001L, MILLISECONDS, "-0001-12-31T23:59:59.999Z"); ts(253402300799999L, MILLISECONDS, "9999-12-31T23:59:59.999Z"); ts(-377642044800001L, MILLISECONDS, "-9999-12-31T23:59:59.999Z"); // NTFS epoch in usec. ts(-11644473600000000L, MICROSECONDS, "1601-01-01T00:00:00Z"); // nulls try { FileTime.from(0L, null); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException npe) { } FileTime time = FileTime.fromMillis(now); if (time.equals(null)) throw new RuntimeException("should not be equal to null"); try { time.compareTo(null); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException npe) { } }
81. Basic#to()
View licensestatic 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"); } } }
82. Basic#main()
View licensepublic static void main(String[] args) { long now = System.currentTimeMillis(); long tomorrowInDays = TimeUnit.DAYS.convert(now, MILLISECONDS) + 1; long yesterdayInDays = TimeUnit.DAYS.convert(now, MILLISECONDS) - 1; // equals eq(now, MILLISECONDS, now, MILLISECONDS); eq(now, MILLISECONDS, now * 1000L, MICROSECONDS); neq(now, MILLISECONDS, 0, MILLISECONDS); neq(now, MILLISECONDS, 0, MICROSECONDS); // compareTo cmp(now, MILLISECONDS, now, MILLISECONDS, 0); cmp(now, MILLISECONDS, now * 1000L, MICROSECONDS, 0); cmp(now, MILLISECONDS, now - 1234, MILLISECONDS, 1); cmp(now, MILLISECONDS, now + 1234, MILLISECONDS, -1); cmp(tomorrowInDays, DAYS, now, MILLISECONDS, 1); cmp(now, MILLISECONDS, tomorrowInDays, DAYS, -1); cmp(yesterdayInDays, DAYS, now, MILLISECONDS, -1); cmp(now, MILLISECONDS, yesterdayInDays, DAYS, 1); cmp(yesterdayInDays, DAYS, now, MILLISECONDS, -1); cmp(Long.MAX_VALUE, DAYS, Long.MAX_VALUE, NANOSECONDS, 1); cmp(Long.MAX_VALUE, DAYS, Long.MIN_VALUE, NANOSECONDS, 1); cmp(Long.MIN_VALUE, DAYS, Long.MIN_VALUE, NANOSECONDS, -1); cmp(Long.MIN_VALUE, DAYS, Long.MAX_VALUE, NANOSECONDS, -1); // to(TimeUnit) to(MILLISECONDS.convert(1, DAYS) - 1, MILLISECONDS); to(MILLISECONDS.convert(1, DAYS) + 0, MILLISECONDS); to(MILLISECONDS.convert(1, DAYS) + 1, MILLISECONDS); to(1, MILLISECONDS); to(0, MILLISECONDS); to(1, MILLISECONDS); to(MILLISECONDS.convert(-1, DAYS) - 1, MILLISECONDS); to(MILLISECONDS.convert(-1, DAYS) + 0, MILLISECONDS); to(MILLISECONDS.convert(-1, DAYS) + 1, MILLISECONDS); for (TimeUnit unit : TimeUnit.values()) { for (int i = 0; i < 100; i++) { to(rand.nextLong(), unit); } to(Long.MIN_VALUE, unit); to(Long.MAX_VALUE, unit); } // toString ts(1L, DAYS, "1970-01-02T00:00:00Z"); ts(1L, HOURS, "1970-01-01T01:00:00Z"); ts(1L, MINUTES, "1970-01-01T00:01:00Z"); ts(1L, SECONDS, "1970-01-01T00:00:01Z"); ts(1L, MILLISECONDS, "1970-01-01T00:00:00.001Z"); ts(1L, MICROSECONDS, "1970-01-01T00:00:00.000001Z"); ts(1L, NANOSECONDS, "1970-01-01T00:00:00.000000001Z"); ts(999999999L, NANOSECONDS, "1970-01-01T00:00:00.999999999Z"); ts(9999999999L, NANOSECONDS, "1970-01-01T00:00:09.999999999Z"); ts(-1L, DAYS, "1969-12-31T00:00:00Z"); ts(-1L, HOURS, "1969-12-31T23:00:00Z"); ts(-1L, MINUTES, "1969-12-31T23:59:00Z"); ts(-1L, SECONDS, "1969-12-31T23:59:59Z"); ts(-1L, MILLISECONDS, "1969-12-31T23:59:59.999Z"); ts(-1L, MICROSECONDS, "1969-12-31T23:59:59.999999Z"); ts(-1L, NANOSECONDS, "1969-12-31T23:59:59.999999999Z"); ts(-999999999L, NANOSECONDS, "1969-12-31T23:59:59.000000001Z"); ts(-9999999999L, NANOSECONDS, "1969-12-31T23:59:50.000000001Z"); ts(-62135596799999L, MILLISECONDS, "0001-01-01T00:00:00.001Z"); ts(-62135596800000L, MILLISECONDS, "0001-01-01T00:00:00Z"); ts(-62135596800001L, MILLISECONDS, "-0001-12-31T23:59:59.999Z"); ts(253402300799999L, MILLISECONDS, "9999-12-31T23:59:59.999Z"); ts(-377642044800001L, MILLISECONDS, "-9999-12-31T23:59:59.999Z"); // NTFS epoch in usec. ts(-11644473600000000L, MICROSECONDS, "1601-01-01T00:00:00Z"); // nulls try { FileTime.from(0L, null); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException npe) { } FileTime time = FileTime.fromMillis(now); if (time.equals(null)) throw new RuntimeException("should not be equal to null"); try { time.compareTo(null); throw new RuntimeException("NullPointerException expected"); } catch (NullPointerException npe) { } }
83. Basic#to()
View licensestatic 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"); } } }
84. Basic#realMain()
View licenseprivate 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)); }
85. OkHttpAdapter#newOkHttpClient()
View licenseprivate static OkHttpClient newOkHttpClient() { TimeUnit unit = TimeUnit.SECONDS; int timeout = 10; return new OkHttpClient.Builder().connectTimeout(timeout, unit).readTimeout(timeout, unit).writeTimeout(timeout, unit).build(); }
86. TenantCacheInvalidation#start()
View licensepublic void start() { final TimeUnit pendingRateUnit = tenantConfig.getTenantBroadcastServiceRunningRate().getUnit(); final long pendingPeriod = tenantConfig.getTenantBroadcastServiceRunningRate().getPeriod(); tenantExecutor.scheduleAtFixedRate(new TenantCacheInvalidationRunnable(this, broadcastDao, tenantDao), pendingPeriod, pendingPeriod, pendingRateUnit); }
87. 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); }
88. 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()); }
89. DefaultCommandLatencyCollector#getMetric()
View licenseprivate 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; }
90. Stopwatch#toString()
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)); }
91. Stopwatch#toString()
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)); }
92. IdlePurgePolicy#createPurgePolicy()
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()); }
93. TransformerTest#testExtractEnumName()
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); } }
94. Duration#plus()
View licensepublic Duration plus(Duration o) { TimeUnit u = Timestamp.finest(getUnit(), o.getUnit()); return new Duration(convert(u) + o.convert(u), u); }
95. Duration#divideBy()
View licensepublic long divideBy(Duration o) { TimeUnit u = Timestamp.finest(getUnit(), o.getUnit()); return convert(u) / o.convert(u); }
96. Duration#isMultiple()
View licensepublic boolean isMultiple(Duration o) { TimeUnit u = Timestamp.finest(getUnit(), o.getUnit()); return this.gte(o) && ((convert(u) % o.convert(u)) == 0); }
97. Duration#compareTo()
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); }
98. Timestamp#plus()
View licensepublic Timestamp plus(long value, TimeUnit units) { TimeUnit finest = finest(m_unit, units); return new Timestamp(convert(finest) + finest.convert(value, units), finest); }
99. Timestamp#plus()
View licensepublic Timestamp plus(Duration d) { TimeUnit finest = finest(m_unit, d.getUnit()); return new Timestamp(convert(finest) + d.convert(finest), finest); }
100. Timestamp#minus()
View licensepublic Timestamp minus(long value, TimeUnit units) { TimeUnit finest = finest(m_unit, units); return new Timestamp(convert(finest) - finest.convert(value, units), finest); }