Java Examples for java.time.Duration
The following java examples will help you to understand the usage of java.time.Duration. These source code samples are taken from different open source projects.
Example 1
| Project: bearchoke-master File: DurationReadConverter.java View source code |
@Override public Duration convert(String value) { Duration result = null; try { if (log.isTraceEnabled()) { log.trace("Converting String {} to Duration", value); } result = Duration.parse(value); } catch (DateTimeParseException e) { log.error("{} could not be converted to java.time.Duration", value); } return result; }
Example 2
| Project: cmn-project-master File: CreateSubnetTask.java View source code |
@Override
public void execute(Context context) throws Exception {
List<String> zones = AWS.ec2.availabilityZones();
List<String> subnetIds = new ArrayList<>();
for (int i = 0; i < resource.cidrs.size(); i++) {
String cidr = resource.cidrs.get(i);
com.amazonaws.services.ec2.model.Subnet subnet = AWS.vpc.createSubnet(new CreateSubnetRequest(resource.vpc.remoteVPC.getVpcId(), cidr).withAvailabilityZone(zones.get(i)));
subnetIds.add(subnet.getSubnetId());
}
while (true) {
logger.info("wait until all subnets are available");
Threads.sleepRoughly(Duration.ofSeconds(10));
List<com.amazonaws.services.ec2.model.Subnet> subnets = AWS.vpc.describeSubnets(subnetIds);
boolean allOK = subnets.stream().allMatch( subnet -> {
logger.info("subnet {} => {}", subnet.getSubnetId(), subnet.getState());
return "available".equals(subnet.getState());
});
if (allOK) {
resource.remoteSubnets.addAll(subnets);
break;
}
}
if (resource.type == SubnetType.PUBLIC) {
for (String subnetId : subnetIds) {
AWS.vpc.ec2.modifySubnetAttribute(new ModifySubnetAttributeRequest().withSubnetId(subnetId).withMapPublicIpOnLaunch(true));
}
}
EC2TagHelper tagHelper = new EC2TagHelper(context.env);
AWS.ec2.createTags(new CreateTagsRequest().withResources(subnetIds).withTags(tagHelper.env(), tagHelper.resourceId(resource.id), tagHelper.name(resource.id)));
logger.info("associate route table, subnet={}, routeTable={}", resource.id, resource.routeTable.id);
for (com.amazonaws.services.ec2.model.Subnet remoteSubnet : resource.remoteSubnets) {
AWS.vpc.ec2.associateRouteTable(new AssociateRouteTableRequest().withRouteTableId(resource.routeTable.remoteRouteTable.getRouteTableId()).withSubnetId(remoteSubnet.getSubnetId()));
}
}Example 3
| Project: core-ng-project-master File: CacheImplTest.java View source code |
@Test
public void getAll() {
Map<String, byte[]> values = Maps.newHashMap();
values.put("name:key1", Strings.bytes("1"));
values.put("name:key3", Strings.bytes("3"));
when(cacheStore.getAll(new String[] { "name:key1", "name:key2", "name:key3" })).thenReturn(values);
Map<String, Integer> results = cache.getAll(Arrays.asList("key1", "key2", "key3"), key -> 2);
assertEquals(3, results.size());
assertEquals(1, results.get("key1").intValue());
assertEquals(2, results.get("key2").intValue());
assertEquals(3, results.get("key3").intValue());
verify(cacheStore).putAll(argThat( argument -> argument.size() == 1 && Arrays.equals(argument.get("name:key2"), Strings.bytes("2"))), eq(Duration.ofHours(1)));
}Example 4
| Project: ecdr-master File: DateTest.java View source code |
public static void main(String args[]) {
Date startDate = new Date();
startDate = DateUtils.addDays(startDate, -20);
if (startDate != null) {
System.out.println(startDate);
LocalDateTime start = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault());
System.out.println(start);
Duration duration = Duration.between(start, LocalDateTime.now());
System.out.println(4 / duration.toHours());
System.out.println((13 * 7) / duration.toDays());
}
}Example 5
| Project: btpka3.github.com-master File: DurationTest.java View source code |
public static void main(String[] args) throws InterruptedException {
// æ ¼å¼?化时间
LocalDateTime date = LocalDateTime.now();
String text = date.format(DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime parsedDate = LocalDateTime.parse(text, DateTimeFormatter.ISO_DATE_TIME);
System.out.println("1.1 - " + date);
System.out.println("1.2 - " + text);
System.out.println("1.3 - " + parsedDate);
// 打�时间段
long start = System.currentTimeMillis();
Duration duration = Duration.ZERO.plusMillis(start);
System.out.println("2.1 - " + duration);
}Example 6
| Project: ethernet-ip-master File: LargeForwardOpenResponse.java View source code |
public static LargeForwardOpenResponse decode(ByteBuf buffer) {
int o2tConnectionId = buffer.readInt();
int t2oConnectionId = buffer.readInt();
int connectionSerialNumber = buffer.readUnsignedShort();
int originatorVendorId = buffer.readUnsignedShort();
long originatorSerialNumber = buffer.readUnsignedInt();
long o2tActualPacketInterval = TimeUnit.MICROSECONDS.convert(buffer.readUnsignedInt(), TimeUnit.MILLISECONDS);
long t2oActualPacketInterval = TimeUnit.MICROSECONDS.convert(buffer.readUnsignedInt(), TimeUnit.MILLISECONDS);
int applicationReplySize = buffer.readUnsignedByte();
// reserved
buffer.skipBytes(1);
ByteBuf applicationReply = applicationReplySize > 0 ? buffer.readSlice(applicationReplySize).copy() : Unpooled.EMPTY_BUFFER;
return new LargeForwardOpenResponse(o2tConnectionId, t2oConnectionId, connectionSerialNumber, originatorVendorId, originatorSerialNumber, Duration.ofMillis(o2tActualPacketInterval), Duration.ofMillis(t2oActualPacketInterval), applicationReplySize, applicationReply);
}Example 7
| Project: hprose-java-master File: DurationUnserializer.java View source code |
@Override public Duration unserialize(Reader reader, int tag, Type type) throws IOException { switch(tag) { case TagEmpty: return null; case TagString: return Duration.parse(ReferenceReader.readString(reader)); case TagInteger: case TagLong: return Duration.ofNanos(ValueReader.readLong(reader)); case TagDouble: return Duration.ofNanos((long) ValueReader.readDouble(reader)); } if (tag >= '0' && tag <= '9') return Duration.ofNanos(tag - '0'); return super.unserialize(reader, tag, type); }
Example 8
| Project: javalab-master File: AsyncInterceptor.java View source code |
private void traceTotalTime(InvocationContext ctx, Instant start) {
Instant end = Instant.now();
tracer.info(() -> {
Long duration = Duration.between(start, end).toMillis();
return new StringJoiner("").add("ASYNC Total Duration of method ").add(ctx.getMethod().getName()).add(" on class ").add(ctx.getMethod().getDeclaringClass().getSimpleName()).add(" : ").add(duration.toString()).add(" milliseconds").toString();
});
}Example 9
| Project: jfxtras-master File: TriggerTest.java View source code |
@Test
public void canBuildTrigger1() {
Trigger<Duration> madeProperty = new Trigger<Duration>(Duration.ofMinutes(5)).withAlarmTrigger(new AlarmTriggerRelationship(AlarmTriggerRelationshipType.END));
String expectedContent = "TRIGGER;RELATED=END:PT5M";
assertEquals(expectedContent, madeProperty.toString());
assertEquals(Duration.ofMinutes(5), madeProperty.getValue());
assertEquals(AlarmTriggerRelationshipType.END, madeProperty.getAlarmTrigger().getValue());
}Example 10
| Project: ProjectAres-master File: BlockingScheduledQueue.java View source code |
public T get(Duration timeout) throws InterruptedException {
final long limit = Instant.now().plus(timeout).toEpochMilli();
for (; ; ) {
synchronized (this) {
final long now = Instant.now().toEpochMilli();
final Entry<T> entry = queue.peek();
long wait = limit - now;
if (entry != null) {
final long untilNext = entry.time - now;
if (untilNext <= 0)
return queue.remove().element;
wait = Math.min(wait, untilNext);
}
if (wait <= 0)
throw new InterruptedException();
wait(wait);
}
}
}Example 11
| Project: datanucleus-core-master File: DurationTest.java View source code |
public void testConversionToDouble() {
DurationDoubleConverter conv = new DurationDoubleConverter();
// Conversion from Duration to Double
Duration d1 = Duration.ofNanos(5000005000l);
Double d1Double = conv.toDatastoreType(d1);
assertEquals(5, d1Double.longValue());
assertEquals(5000l, (long) ((d1Double.doubleValue() * 1E9) - (d1Double.longValue() * 1E9)));
Duration d2 = Duration.ofNanos(7999999999l);
Double d2Double = conv.toDatastoreType(d2);
assertEquals(7, d2Double.longValue());
assertEquals(999999999l, (long) ((d2Double.doubleValue() * 1E9) - (d2Double.longValue() * 1E9)));
// Conversion of Double to Duration
Double dbl1 = new Double(8.000600010);
Duration dbl1Dur = conv.toMemberType(dbl1);
assertEquals(8, dbl1Dur.getSeconds());
assertEquals(600010, dbl1Dur.getNano(), 1);
Double dbl2 = new Double(5.070000099);
Duration dbl2Dur = conv.toMemberType(dbl2);
assertEquals(5, dbl2Dur.getSeconds());
assertEquals(70000099, dbl2Dur.getNano(), 1);
}Example 12
| Project: extract-master File: HumanDuration.java View source code |
/**
* Creates a new {@link Duration} by parsing the given string.
*
* @param duration the duration - for example {@literal 500ms} or {@literal 1h}
*/
public static Duration parse(final String duration) {
final Matcher matcher = pattern.matcher(duration);
final long value;
if (!matcher.find()) {
throw new DateTimeParseException("Invalid time duration string.", duration, 0);
}
value = Long.parseLong(matcher.group(1));
if (null == matcher.group(2)) {
return Duration.ofMillis(value);
}
switch(matcher.group(2).toLowerCase()) {
case "d":
return Duration.ofDays(value);
case "h":
return Duration.ofHours(value);
case "m":
return Duration.ofMinutes(value);
case "s":
return Duration.ofSeconds(value);
default:
return Duration.ofMillis(value);
}
}Example 13
| Project: levelup-java-examples-master File: SecondsBetweenDates.java View source code |
@Test
public void seconds_between_two_dates_in_java_with_java8() {
LocalDateTime startDate = LocalDateTime.now().minusDays(1);
LocalDateTime endDate = LocalDateTime.now();
long secondsInDay = Duration.between(startDate, endDate).toMinutes();
assertEquals(1440, secondsInDay);
// or
long secondsInDay2 = ChronoUnit.SECONDS.between(startDate, endDate);
assertEquals(86400, secondsInDay2);
}Example 14
| Project: bootique-master File: DefaultShutdownManagerIT.java View source code |
@Test
public void testShutdown() throws Exception {
Duration timeout = Duration.ofMillis(10000l);
DefaultShutdownManager shutdownManager = new DefaultShutdownManager(timeout);
shutdownManager.addShutdownHook(mockCloseable1);
shutdownManager.addShutdownHook(mockCloseable2);
shutdownManager.shutdown();
verify(mockCloseable1).close();
verify(mockCloseable2).close();
}Example 15
| Project: camelinaction2-master File: NumbersTest.java View source code |
@Test
public void testNumbers() throws Exception {
LOG.info("Starting Reactive-Core Flux numbers");
// use stream engine to subscribe from a timer interval that runs a continued
// stream with data once per second
Flux.interval(Duration.ofSeconds(1)).map(// map the message to a random number between 0..9
i -> new Random().nextInt(10)).filter(// filter out to only include big numbers, eg 6..9
n -> n > 5).doOnNext(// log the big number
c -> LOG.info("Streaming big number {}", c)).subscribe();
// let it run for 10 seconds
Thread.sleep(10000);
}Example 16
| Project: cas-master File: CasConfigurationEmbeddedValueResolver.java View source code |
private String convertValueToDurationIfPossible(final String value) {
try {
final ConversionService service = applicationContext.getEnvironment().getConversionService();
final Duration dur = service.convert(value, Duration.class);
if (dur != null) {
return String.valueOf(dur.toMillis());
}
} catch (final ConversionFailedException e) {
LOGGER.trace(e.getMessage());
}
return null;
}Example 17
| Project: catalyst-master File: Durations.java View source code |
/** * Returns a Duration from the parsed {@code duration}. Example: * * <pre> * 5 * 5 s * 5 seconds * 10m * 10 minutes * </pre> * * <p> * If a unit is not given, the default unit will be milliseconds. */ public static Duration of(String duration) { Matcher matcher = PATTERN.matcher(duration); Assert.arg(matcher.matches(), "Invalid duration: %s", duration); if (matcher.group(1) != null) { return Duration.ofSeconds(Long.MAX_VALUE); } else { String unit = matcher.group(4); String value = matcher.group(3); return Duration.ofNanos(TimeUnit.NANOSECONDS.convert(Long.parseLong(value), unit == null ? TimeUnit.MILLISECONDS : SUFFIXES.get(unit))); } }
Example 18
| Project: cdi-master File: NotificationOptionsTest.java View source code |
@Test
public void testBuilder() {
Duration timeout = Duration.ofDays(1);
NotificationOptions options = NotificationOptions.of("timeout", timeout);
assertEquals(timeout, options.get("timeout"));
assertNull(options.getExecutor());
assertNull(options.get("alpha"));
options = NotificationOptions.builder().set("foo", "bar").setExecutor(new Executor() {
@Override
public void execute(Runnable command) {
}
}).build();
assertEquals("bar", options.get("foo"));
assertNotNull(options.getExecutor());
options = NotificationOptions.ofExecutor(new Executor() {
@Override
public void execute(Runnable command) {
}
});
Executor executor = options.getExecutor();
assertNotNull(executor);
assertNull(options.get("timeout"));
}Example 19
| Project: diirt-master File: IntegrateFormulaFunction.java View source code |
static double integrate(Instant start, Instant end, VNumber value, VNumber nextValue) {
Instant actualStart = Collections.max(Arrays.asList(start, value.getTimestamp()));
Instant actualEnd = end;
if (nextValue != null) {
actualEnd = Collections.min(Arrays.asList(end, nextValue.getTimestamp()));
}
Duration duration = Duration.between(actualStart, actualEnd);
if (!duration.isNegative() && !duration.isZero()) {
return TimeDuration.toSecondsDouble(duration.multipliedBy(value.getValue().longValue()));
} else {
return 0;
}
}Example 20
| Project: hawkular-metrics-master File: CompressData.java View source code |
@Override
public Completable call(JobDetails jobDetails) {
Duration runtimeBlockSize = blockSize;
DateTime timeSliceInclusive;
Trigger trigger = jobDetails.getTrigger();
if (trigger instanceof RepeatingTrigger) {
if (!enabled) {
return Completable.complete();
}
timeSliceInclusive = new DateTime(trigger.getTriggerTime(), DateTimeZone.UTC).minus(runtimeBlockSize);
} else {
if (jobDetails.getParameters().containsKey(TARGET_TIME)) {
// DateTime parsing fails without casting to Long first
Long parsedMillis = Long.valueOf(jobDetails.getParameters().get(TARGET_TIME));
timeSliceInclusive = new DateTime(parsedMillis, DateTimeZone.UTC);
} else {
logger.error("Missing " + TARGET_TIME + " parameter from manual execution of " + JOB_NAME + " job");
return Completable.complete();
}
if (jobDetails.getParameters().containsKey(BLOCK_SIZE)) {
java.time.Duration parsedDuration = java.time.Duration.parse(jobDetails.getParameters().get(BLOCK_SIZE));
runtimeBlockSize = Duration.millis(parsedDuration.toMillis());
}
}
// Rewind to previous timeslice
DateTime timeSliceStart = DateTimeService.getTimeSlice(timeSliceInclusive, runtimeBlockSize);
long startOfSlice = timeSliceStart.getMillis();
long endOfSlice = timeSliceStart.plus(runtimeBlockSize).getMillis() - 1;
Stopwatch stopwatch = Stopwatch.createStarted();
logger.info("Starting compression of timestamps (UTC) between " + startOfSlice + " - " + endOfSlice);
Observable<? extends MetricId<?>> metricIds = metricsService.findAllMetrics().map(Metric::getMetricId).filter( m -> (m.getType() == GAUGE || m.getType() == COUNTER || m.getType() == AVAILABILITY));
PublishSubject<Metric<?>> subject = PublishSubject.create();
subject.subscribe( metric -> {
try {
this.metricsService.updateMetricExpiration(metric);
} catch (Exception e) {
logger.error("Could not update the metric expiration index for metric " + metric.getId() + " of tenant " + metric.getTenantId());
}
});
// TODO Optimization - new worker per token - use parallelism in Cassandra (with configured parallelism)
return metricsService.compressBlock(metricIds, startOfSlice, endOfSlice, pageSize, subject).doOnError( t -> {
subject.onCompleted();
logger.warn("Failed to compress data", t);
}).doOnCompleted(() -> {
subject.onCompleted();
stopwatch.stop();
logger.info("Finished compressing data in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
});
}Example 21
| Project: hello-world-master File: TcMonitorFilter.java View source code |
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
LocalDateTime now = LocalDateTime.now();
filterChain.doFilter(request, response);
long nanos = Duration.between(now, LocalDateTime.now()).get(ChronoUnit.NANOS);
if (maxThan(nanos, errorTimeout)) {
log.warn("request [{}] process take time [{}]", request.getRequestURI(), nanos / NANO_2_MS);
} else if (maxThan(nanos, warnTimeout)) {
log.error("request [{}] process take time [{}]", request.getRequestURI(), nanos / NANO_2_MS);
}
}Example 22
| Project: hibernate-validator-master File: DurationMinValidator.java View source code |
@Override
public void initialize(DurationMin constraintAnnotation) {
this.minDuration = Duration.ofNanos(constraintAnnotation.nanos()).plusMillis(constraintAnnotation.millis()).plusSeconds(constraintAnnotation.seconds()).plusMinutes(constraintAnnotation.minutes()).plusHours(constraintAnnotation.hours()).plusDays(constraintAnnotation.days());
this.inclusive = constraintAnnotation.inclusive();
}Example 23
| Project: java-core-learning-example-master File: PlayDuration.java View source code |
public static void main(String[] args) throws InterruptedException {
Instant start = Instant.now();
TimeUnit.SECONDS.sleep(3);
Instant end = Instant.now();
// 获å?–æŒ?ç»æ—¶é—´
Duration timeElapsed = Duration.between(start, end);
// 毫秒
System.out.println(timeElapsed.toMillis());
// 纳
System.out.println(// 纳
timeElapsed.toNanos());
Instant start1 = Instant.now();
TimeUnit.SECONDS.sleep(2);
Instant end1 = Instant.now();
// 获å?–æŒ?ç»æ—¶é—´
Duration timeElapsed1 = Duration.between(start1, end1);
// æ·»åŠ æ“?作
Duration all = timeElapsed.plus(timeElapsed1);
// 毫秒
System.out.println(all.toMillis());
}Example 24
| Project: MasteringTables-master File: GameView.java View source code |
public void startTimer() {
this.begin = Instant.now();
this.tl = new Timeline();
this.tl.setCycleCount(Animation.INDEFINITE);
this.tl.getKeyFrames().add(new KeyFrame(Duration.millis(200), new EventHandler<ActionEvent>() {
@Override
public void handle(final ActionEvent arg0) {
final java.time.Duration d = java.time.Duration.between(GameView.this.begin, Instant.now());
GameView.this.timer.setText(numberFormat.format(d.getSeconds() / 60) + ":" + numberFormat.format(d.getSeconds() % 60));
}
}));
this.tl.play();
}Example 25
| Project: owner-master File: DurationConverter.java View source code |
@Override public Duration convert(Method method, String input) { // If it looks like a string that Duration.parse can handle, let's try that. if (input.startsWith("P") || input.startsWith("-P") || input.startsWith("+P")) { return Duration.parse(input); } // ...otherwise we'll perform our own parsing return parseDuration(input); }
Example 26
| Project: rakam-master File: EventExplorerListener.java View source code |
public void createTable(String project, String collection) {
String query = format("select date_trunc('hour', %s) as _time, count(*) as total from %s group by 1", checkTableColumn(projectConfig.getTimeColumn()), checkCollection(collection));
MaterializedView report = new MaterializedView("_event_explorer_metrics - " + collection, format("Event explorer metrics for %s collection", collection), query, Duration.ofHours(1), true, true, ImmutableMap.of());
materializedViewService.create(project, report).join();
}Example 27
| Project: SupaCommons-master File: DurationUtilsTest.java View source code |
@Test
public void testToString() throws Exception {
Assert.assertEquals("1h", DurationUtils.toString(Duration.ofSeconds(3600), true));
Assert.assertEquals("1 hour", DurationUtils.toString(Duration.ofSeconds(3600), false));
Assert.assertEquals("-1h", DurationUtils.toString(Duration.ofSeconds(-3600), true));
Assert.assertEquals("-1 hour", DurationUtils.toString(Duration.ofSeconds(-3600), false));
}Example 28
| Project: webflux-streaming-showcase-master File: QuoteGenerator.java View source code |
public Flux<Quote> fetchQuoteStream(Duration period) {
return Flux.generate(() -> 0, (BiFunction<Integer, SynchronousSink<Quote>, Integer>) ( index, sink) -> {
Quote updatedQuote = updateQuote(prices.get(index));
sink.next(updatedQuote);
return ++index % prices.size();
}).zipWith(Flux.interval(period)).map( t -> t.getT1()).map( quote -> {
quote.setInstant(Instant.now());
return quote;
}).share().log();
}Example 29
| Project: Time4J-master File: TemporalType.java View source code |
@Override public java.time.Duration from(Duration<ClockUnit> time4j) { java.time.Duration threetenDuration = java.time.Duration.ZERO; for (ClockUnit unit : ClockUnit.values()) { long amount = time4j.getPartialAmount(unit); TemporalUnit threetenUnit; switch(unit) { case HOURS: threetenUnit = ChronoUnit.HOURS; break; case MINUTES: threetenUnit = ChronoUnit.MINUTES; break; case SECONDS: threetenUnit = ChronoUnit.SECONDS; break; case MILLIS: threetenUnit = ChronoUnit.MILLIS; break; case MICROS: threetenUnit = ChronoUnit.MICROS; break; case NANOS: threetenUnit = ChronoUnit.NANOS; break; default: throw new UnsupportedOperationException(unit.name()); } threetenDuration = threetenDuration.plus(amount, threetenUnit); } if (time4j.isNegative()) { threetenDuration = threetenDuration.negated(); } return threetenDuration; }
Example 30
| Project: cf-java-client-master File: RouterGroupsTest.java View source code |
@Test
public void list() throws TimeoutException, InterruptedException {
this.routingClient.routerGroups().list(ListRouterGroupsRequest.builder().build()).flatMapIterable(ListRouterGroupsResponse::getRouterGroups).map(RouterGroup::getName).filter(DEFAULT_ROUTER_GROUP::equals).as(StepVerifier::create).expectNext(DEFAULT_ROUTER_GROUP).expectComplete().verify(Duration.ofMinutes(5));
}Example 31
| Project: circuitbreaker-master File: RetryRegistryTest.java View source code |
@Test
public void canBuildRetryRegistryWithConfig() {
RetryConfig config = RetryConfig.custom().maxAttempts(1000).waitDuration(Duration.ofSeconds(300)).build();
retryRegistry = RetryRegistry.of(config);
Retry retry = retryRegistry.retry("testName", () -> config);
Assertions.assertThat(retry).isNotNull();
Assertions.assertThat(retryRegistry.getAllRetries()).hasSize(1);
}Example 32
| Project: corgi-master File: RequestInterceptor.java View source code |
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
LocalDateTime startTime = LocalDateTime.parse(request.getAttribute(STARTTIME).toString());
long seconds = Duration.between(startTime, LocalDateTime.now()).getSeconds();
if (seconds >= ACTIONE_SECONDS) {
LOGGER.info(request.getRequestURI() + " 处�时间为 => " + seconds + "s");
}
super.afterCompletion(request, response, handler, ex);
}Example 33
| Project: downlords-faf-client-master File: TimeServiceImpl.java View source code |
@Override
public String timeAgo(Instant instant) {
if (instant == null) {
return "";
}
Duration ago = Duration.between(instant, Instant.now());
if (Duration.ofMinutes(1).compareTo(ago) > 0) {
return i18n.get("secondsAgo", ago.getSeconds());
}
if (Duration.ofHours(1).compareTo(ago) > 0) {
return i18n.get("minutesAgo", ago.toMinutes());
}
if (Duration.ofDays(1).compareTo(ago) > 0) {
return i18n.get("hoursAgo", ago.toHours());
}
if (Duration.ofDays(30).compareTo(ago) > 0) {
return i18n.get("daysAgo", ago.toDays());
}
if (Duration.ofDays(365).compareTo(ago) > 0) {
return i18n.get("monthsAgo", ago.toDays() / 30);
}
return i18n.get("yearsAgo", ago.toDays() / 365);
}Example 34
| Project: ebean-master File: ScalarTypeDurationWithNanosTest.java View source code |
@Test
public void testReadData() throws Exception {
Duration duration = Duration.ofSeconds(323, 1500000);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os);
type.writeData(out, duration);
type.writeData(out, null);
out.flush();
out.close();
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
ObjectInputStream in = new ObjectInputStream(is);
Duration val1 = type.readData(in);
Duration val2 = type.readData(in);
assertEquals(duration, val1);
assertNull(val2);
}Example 35
| Project: euphoria-master File: SumByKeyTest.java View source code |
@Test
public void testTwoPartitions() {
execute(new AbstractTestCase<Integer, Pair<Integer, Long>>() {
@Override
protected Dataset<Pair<Integer, Long>> getOutput(Dataset<Integer> input) {
return SumByKey.of(input).keyBy( e -> e % 2).valueBy( e -> (long) e).setPartitioner( e -> e % 2).windowBy(Time.of(Duration.ofSeconds(1))).output();
}
@Override
protected Partitions<Integer> getInput() {
return Partitions.add(1, 2, 3, 4, 5).add(6, 7, 8, 9).build();
}
@Override
public int getNumOutputPartitions() {
return 2;
}
@Override
public void validate(Partitions<Pair<Integer, Long>> partitions) {
assertEquals(2, partitions.size());
assertEquals(1, partitions.get(0).size());
assertEquals(Pair.of(0, 20L), partitions.get(0).get(0));
assertEquals(1, partitions.get(1).size());
assertEquals(Pair.of(1, 25L), partitions.get(1).get(0));
}
});
}Example 36
| Project: fungsi-master File: PromiseTest.java View source code |
@Test
public void testGetTimeoutSuccess() throws Exception {
Worker w = Workers.wrap(Executors.newCachedThreadPool());
Future<Unit> f = w.cast(() -> Thread.sleep(1000));
Future<Unit> ff = f.flatMap( u -> w.cast(() -> Thread.sleep(1000)));
long start = System.currentTimeMillis();
ff.get(Duration.ofMillis(3000));
long elapsed = System.currentTimeMillis() - start;
assertTrue(2000 - elapsed < 50);
}Example 37
| Project: future-master File: SatisfiedFutureTest.java View source code |
/*** delayed ***/
@Test
public void delayed() throws CheckedFutureException {
Future<Integer> future = Future.value(1);
long delay = 10;
long start = System.currentTimeMillis();
int result = future.delayed(Duration.ofMillis(delay), scheduler).get(Duration.ofMillis(200));
assertTrue(System.currentTimeMillis() - start >= delay);
assertEquals(1, result);
}Example 38
| Project: genie-master File: TimeUtilsUnitTests.java View source code |
/**
* Can get the duration for various cases.
*/
@Test
public void canGetDuration() {
final Date epoch = new Date(0);
final long durationMillis = 50823L;
final Duration duration = Duration.ofMillis(durationMillis);
final Date started = new Date();
final Date finished = new Date(started.getTime() + durationMillis);
Assert.assertThat(TimeUtils.getDuration(null, finished), Matchers.is(Duration.ZERO));
Assert.assertThat(TimeUtils.getDuration(epoch, finished), Matchers.is(Duration.ZERO));
Assert.assertNotNull(TimeUtils.getDuration(started, null));
Assert.assertNotNull(TimeUtils.getDuration(started, epoch));
Assert.assertThat(TimeUtils.getDuration(started, finished), Matchers.is(duration));
}Example 39
| Project: gridrouter-master File: WaitAvailableBrowsersChecker.java View source code |
@Override
public void ensureFreeBrowsersAvailable(String user, String remoteHost, String browser, Version version) {
int waitAttempt = 0;
final String requestId = randomUUID().toString();
final Temporal waitingStarted = now();
final Duration maxWait = Duration.ofSeconds(queueTimeout);
while (maxWait.compareTo(Duration.between(waitingStarted, now())) > 0 && (countSessions(user, browser, version)) >= version.getPermittedCount()) {
try {
onWait(user, browser, version, requestId, waitAttempt);
Thread.sleep(SECONDS.toMillis(queueWaitInterval));
} catch (InterruptedException e) {
LOGGER.error("Failed to sleep thread", e);
}
if (maxWait.compareTo(Duration.between(waitingStarted, now())) < 0) {
onWaitTimeout(user, browser, version, requestId, waitAttempt);
}
}
onWaitFinished(user, browser, version, requestId, waitAttempt);
}Example 40
| Project: heron-master File: GlobalMetricsTest.java View source code |
@Test
public void testGlobalMetrics() {
MetricsCollector fakeCollector = new MetricsCollector(new FakeWakeableLooper(), null);
TopologyContext fakeContext = new TopologyContextImpl(new HashMap<String, Object>(), TopologyAPI.Topology.getDefaultInstance(), new HashMap<Integer, String>(), 0, fakeCollector);
GlobalMetrics.init(fakeContext, Duration.ofSeconds(5));
GlobalMetrics.incr("mycounter");
Map<String, Long> metricsContent = GlobalMetrics.getUnderlyingCounter().getValueAndReset();
assertTrue(metricsContent.containsKey("mycounter"));
assertEquals(1, metricsContent.size());
assertEquals(new Long(1), metricsContent.get("mycounter"));
// Increment two different counters
GlobalMetrics.incr("mycounter1");
GlobalMetrics.incr("mycounter2");
GlobalMetrics.incr("mycounter1");
metricsContent = GlobalMetrics.getUnderlyingCounter().getValueAndReset();
assertTrue(metricsContent.containsKey("mycounter"));
assertTrue(metricsContent.containsKey("mycounter1"));
assertTrue(metricsContent.containsKey("mycounter2"));
assertEquals(3L, metricsContent.size());
assertEquals(new Long(0), metricsContent.get("mycounter"));
assertEquals(new Long(1), metricsContent.get("mycounter2"));
assertEquals(new Long(2), metricsContent.get("mycounter1"));
}Example 41
| Project: hibernate-orm-master File: DurationJavaDescriptor.java View source code |
@Override
@SuppressWarnings("unchecked")
public <X> X unwrap(Duration duration, Class<X> type, WrapperOptions options) {
if (duration == null) {
return null;
}
if (Duration.class.isAssignableFrom(type)) {
return (X) duration;
}
if (String.class.isAssignableFrom(type)) {
return (X) duration.toString();
}
if (Long.class.isAssignableFrom(type)) {
return (X) Long.valueOf(duration.toNanos());
}
throw unknownUnwrap(type);
}Example 42
| Project: hibernate-search-master File: NumericFieldUtils.java View source code |
public static Query createNumericRangeQuery(String fieldName, Object from, Object to, boolean includeLower, boolean includeUpper) {
Class<?> numericClass;
if (from != null) {
numericClass = from.getClass();
} else if (to != null) {
numericClass = to.getClass();
} else {
throw log.rangeQueryWithNullToAndFromValue(fieldName);
}
if (Double.class.isAssignableFrom(numericClass)) {
return NumericRangeQuery.newDoubleRange(fieldName, (Double) from, (Double) to, includeLower, includeUpper);
}
if (Byte.class.isAssignableFrom(numericClass)) {
return NumericRangeQuery.newIntRange(fieldName, ((Byte) from).intValue(), ((Byte) to).intValue(), includeLower, includeUpper);
}
if (Short.class.isAssignableFrom(numericClass)) {
return NumericRangeQuery.newIntRange(fieldName, ((Short) from).intValue(), ((Short) to).intValue(), includeLower, includeUpper);
}
if (Long.class.isAssignableFrom(numericClass)) {
return NumericRangeQuery.newLongRange(fieldName, (Long) from, (Long) to, includeLower, includeUpper);
}
if (Integer.class.isAssignableFrom(numericClass)) {
return NumericRangeQuery.newIntRange(fieldName, (Integer) from, (Integer) to, includeLower, includeUpper);
}
if (Float.class.isAssignableFrom(numericClass)) {
return NumericRangeQuery.newFloatRange(fieldName, (Float) from, (Float) to, includeLower, includeUpper);
}
if (Date.class.isAssignableFrom(numericClass)) {
Long fromValue = from != null ? ((Date) from).getTime() : null;
Long toValue = to != null ? ((Date) to).getTime() : null;
return NumericRangeQuery.newLongRange(fieldName, fromValue, toValue, includeLower, includeUpper);
}
if (Calendar.class.isAssignableFrom(numericClass)) {
Long fromValue = from != null ? ((Calendar) from).getTime().getTime() : null;
Long toValue = to != null ? ((Calendar) to).getTime().getTime() : null;
return NumericRangeQuery.newLongRange(fieldName, fromValue, toValue, includeLower, includeUpper);
}
if (java.time.Duration.class.isAssignableFrom(numericClass)) {
Long fromValue = from != null ? ((java.time.Duration) from).toNanos() : null;
Long toValue = to != null ? ((java.time.Duration) to).toNanos() : null;
return NumericRangeQuery.newLongRange(fieldName, fromValue, toValue, includeLower, includeUpper);
}
if (java.time.Year.class.isAssignableFrom(numericClass)) {
Integer fromValue = from != null ? ((java.time.Year) from).getValue() : null;
Integer toValue = to != null ? ((java.time.Year) to).getValue() : null;
return NumericRangeQuery.newIntRange(fieldName, fromValue, toValue, includeLower, includeUpper);
}
if (java.time.Instant.class.isAssignableFrom(numericClass)) {
Long fromValue = from != null ? ((java.time.Instant) from).toEpochMilli() : null;
Long toValue = to != null ? ((java.time.Instant) to).toEpochMilli() : null;
return NumericRangeQuery.newLongRange(fieldName, fromValue, toValue, includeLower, includeUpper);
}
throw log.numericRangeQueryWithNonNumericToAndFromValues(fieldName);
}Example 43
| Project: Hindsight-master File: CountdownTimer.java View source code |
public static void printAndReset(String name) {
List<Instant> start = started.get(name);
List<Instant> stop = stopped.get(name);
Duration total = Duration.ZERO;
if (start != null && stop != null) {
for (int i = 0; i < start.size(); i++) {
total = total.plus(Duration.between(start.get(i), stop.get(i)));
}
System.out.println(name + " " + total.toString().replaceFirst("PT", "").replaceFirst("M", " min ").replaceFirst("S", " s"));
started.remove(name);
stopped.remove(name);
}
}Example 44
| Project: idnadrev-master File: OverviewActivityTest.java View source code |
@Override
protected void createTestData(EntityManager em) {
new OverviewDSTest().createTestData(em);
Context context = new Context("context");
em.persist(context);
em.persist(new Task("task1").setContext(context).setEstimatedTime(Duration.ofMinutes(42)));
em.persist(new Task("task2").setContext(context).setEstimatedTime(Duration.ofMinutes(12)));
}Example 45
| Project: jadira-master File: BigDecimalColumnDurationMapper.java View source code |
@Override public Duration fromNonNullValue(BigDecimal value) { StringBuilder durationPattern = new StringBuilder(); if (value.compareTo(BigDecimal.ZERO) < 0) { durationPattern.append('-'); } durationPattern.append("PT"); durationPattern.append(value.abs().toPlainString()); durationPattern.append("S"); return Duration.parse(durationPattern.toString()); }
Example 46
| Project: janus-master File: CommonConfigTest.java View source code |
@Test
public void testDateParsing() {
BaseConfiguration base = new BaseConfiguration();
CommonsConfiguration config = new CommonsConfiguration(base);
for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS, ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
base.setProperty("test", "100 " + unit.toString());
Duration d = config.get("test", Duration.class);
assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
}
Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
base.setProperty("test", "100 " + entry.getValue());
Duration d = config.get("test", Duration.class);
assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
}
}Example 47
| Project: janusgraph-master File: CommonConfigTest.java View source code |
@Test
public void testDateParsing() {
BaseConfiguration base = new BaseConfiguration();
CommonsConfiguration config = new CommonsConfiguration(base);
for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS, ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
base.setProperty("test", "100 " + unit.toString());
Duration d = config.get("test", Duration.class);
assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
}
Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
base.setProperty("test", "100 " + entry.getValue());
Duration d = config.get("test", Duration.class);
assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
}
}Example 48
| Project: java-buildpack-system-test-master File: ServiceBindingTestExecutionListener.java View source code |
@Override
public void afterTestClass(TestContext testContext) {
getServiceType(testContext).ifPresent( serviceType -> {
Collection<Application> applications = getApplications(testContext);
ServiceInstance serviceInstance = getServiceInstance(testContext, serviceType);
Flux.fromIterable(applications).flatMap(( application) -> serviceInstance.unbind(application).doOnError( t -> this.logger.warn("Error while unbinding: {}", t.getMessage())).retryWhen(DelayUtils.exponentialBackOffError(Duration.ofSeconds(1), Duration.ofSeconds(10), Duration.ofMinutes(1)))).then().block(Duration.ofMinutes(1));
});
}Example 49
| Project: javacuriosities-master File: Lesson07PeriodAndDuration.java View source code |
public static void main(String[] args) throws Exception {
// Duration
Instant start = Instant.now();
Instant end = Instant.now();
long nanoseconds = Duration.between(start, end).toNanos();
System.out.println("Start: " + start);
System.out.println("End: " + end);
System.out.println("Diff: " + nanoseconds);
Duration gap = Duration.ofSeconds(10);
Instant later = start.plus(gap);
System.out.println("Start + 10s : " + later);
// Period
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1985, Month.MAY, 6);
Period period = Period.between(birthday, today);
long chronoUnit = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + period.getYears() + " years, " + period.getMonths() + " months, and " + period.getDays() + " days old. (" + chronoUnit + " days total)");
}Example 50
| Project: javaone2015-cloudone-master File: DurationMessageBodyWriter.java View source code |
@Override
public void writeTo(Duration duration, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
if (duration == null) {
entityStream.write("00:00:00,000".getBytes());
return;
}
StringBuilder result = new StringBuilder(20);
long dur = duration.toMillis();
//Days
long l = dur / ChronoUnit.DAYS.getDuration().toMillis();
if (l > 0) {
result.append(l).append("D ");
dur -= l * ChronoUnit.DAYS.getDuration().toMillis();
}
//Hours
l = dur / ChronoUnit.HOURS.getDuration().toMillis();
if (l < 10) {
result.append('0');
}
result.append(l).append(':');
dur -= l * ChronoUnit.HOURS.getDuration().toMillis();
//Minutes
l = dur / ChronoUnit.MINUTES.getDuration().toMillis();
if (l < 10) {
result.append('0');
}
result.append(l).append(':');
dur -= l * ChronoUnit.MINUTES.getDuration().toMillis();
//Seconds
l = dur / ChronoUnit.SECONDS.getDuration().toMillis();
if (l < 10) {
result.append('0');
}
result.append(l).append(',');
dur -= l * ChronoUnit.SECONDS.getDuration().toMillis();
//Millis
if (dur < 100) {
result.append('0');
if (dur < 10) {
result.append('0');
}
}
result.append(dur);
//WRITE IT
entityStream.write(result.toString().getBytes());
}Example 51
| Project: jenetics-master File: ExecutionTimeLimitTest.java View source code |
@Test(dataProvider = "durations")
public void test(final Integer millis) {
final CountClock clock = new CountClock();
final Duration duration = Duration.ofMillis(millis);
final AtomicInteger count = new AtomicInteger();
stream().limit(limit.byExecutionTime(duration, clock)).forEach( s -> count.incrementAndGet());
Assert.assertEquals(count.get(), Math.max(millis.intValue(), 1));
Assert.assertEquals(clock.count, count.get() + 1);
}Example 52
| Project: kaif-master File: GrantCodeTest.java View source code |
@Test
public void codec() throws Exception {
GrantCode code = new GrantCode(UUID.randomUUID(), "cli-id", "sec", "foo://bar", EnumSet.of(ClientAppScope.FEED, ClientAppScope.PUBLIC));
String token = code.encode(Instant.now().plus(Duration.ofHours(1)), secret);
assertTrue(token.length() > 100);
GrantCode decoded = GrantCode.tryDecode(token, secret).get();
assertEquals(code, decoded);
assertFalse(GrantCode.tryDecode("bad", secret).isPresent());
}Example 53
| Project: keywhiz-master File: StatusResourceTest.java View source code |
@Before
public void setUp() throws Exception {
this.registry = mock(HealthCheckRegistry.class);
this.environment = mock(Environment.class);
this.keywhizConfig = mock(KeywhizConfig.class);
when(environment.healthChecks()).thenReturn(registry);
when(keywhizConfig.getStatusCacheExpiry()).thenReturn(Duration.ofSeconds(1));
this.status = new StatusResource(keywhizConfig, environment);
}Example 54
| Project: kume-master File: ClusterTest.java View source code |
@Test
public void testSendAllMembers() throws InterruptedException {
Member member0 = new Member("", 0);
Member member1 = new Member("", 1);
Member member2 = new Member("", 2);
CountDownLatch latch = new CountDownLatch(2);
List<NoNetworkTransport> buses = of(new NoNetworkTransport(member0), new NoNetworkTransport(member1), new NoNetworkTransport(member2));
buses.stream().forEach( bus -> buses.stream().filter( other -> !other.equals(bus)).forEach(bus::addMember));
ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder().add("test", ( bus) -> new PingService(bus, latch)).build();
Cluster cluster0 = new ClusterBuilder().joinStrategy(new DelayedJoinerService(of(member1, member2), Duration.ofSeconds(1))).transport(buses.get(0)::setContext).services(services).serverAddress(member0.getAddress()).start();
Cluster cluster1 = new ClusterBuilder().joinStrategy(new DelayedJoinerService(of(member0, member2), Duration.ofSeconds(1))).transport(buses.get(1)::setContext).services(services).serverAddress(member1.getAddress()).start();
Cluster cluster2 = new ClusterBuilder().joinStrategy(new DelayedJoinerService(of(member0, member1), Duration.ofSeconds(1))).transport(buses.get(2)::setContext).services(services).serverAddress(member2.getAddress()).start();
waitForDiscovery(cluster0, 2);
PingService service = cluster0.getService("test");
service.pingAll();
latch.await();
}Example 55
| Project: microservices-sample-master File: HazelcastApp.java View source code |
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
HazelcastApp app = new HazelcastApp("App", new Random().nextInt(10));
app.doSomeWork();
app.waitFor(20, TimeUnit.SECONDS);
app.shutdown();
System.out.println("total time:" + Duration.ofMillis(System.currentTimeMillis() - start));
}Example 56
| Project: mldht-master File: GetPeers.java View source code |
@Override
protected void process() {
boolean fast = ParseArgs.extractBool(arguments, "-fast");
boolean nocache = ParseArgs.extractBool(arguments, "-nocache");
List<Key> hashes = arguments.stream().filter(Key.STRING_PATTERN.asPredicate()).map( st -> new Key(st)).collect(Collectors.toCollection(ArrayList::new));
if (hashes.isEmpty())
hashes.add(Key.createRandomKey());
AtomicInteger counter = new AtomicInteger();
Instant start = Instant.now();
hashes.forEach( h -> {
dhts.stream().filter(DHT::isRunning).map(DHT::getServerManager).map( m -> m.getRandomActiveServer(false)).filter(Objects::nonNull).forEach( d -> {
DHT dht = d.getDHT();
PeerLookupTask t = new PeerLookupTask(d, dht.getNode(), h);
t.setNoAnnounce(true);
t.setFastTerminate(fast);
t.useCache(!nocache);
counter.incrementAndGet();
t.addListener( unused -> {
if (counter.decrementAndGet() == 0)
exit(0);
});
t.setResultHandler(( source, item) -> {
Formatter f = new Formatter();
Duration elapsed = Duration.between(start, Instant.now());
f.format("%-5dms %s %s from: %s", elapsed.toMillis(), h.toString(), item.toString(), source);
println(f.toString());
});
dht.getTaskManager().addTask(t);
});
});
}Example 57
| Project: MountainRangePvP-master File: GameScreen.java View source code |
public void render(float delta, Duration pingTime) {
Gdx.gl.glClearColor(SKY_COLOUR.r, SKY_COLOUR.g, SKY_COLOUR.b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Vector2 scroll = session.getCameraCentre().cpy();
scroll.x = scroll.x - width / 2;
scroll.y = scroll.y - height / 2;
renderer.render(scroll, pingTime);
}Example 58
| Project: OpenLegislation-master File: SpotcheckTests.java View source code |
@Test
public void openObsGetTest() {
// LocalTime start = LocalTime.now();
// logger.info("start {}", start);
// BaseResponse response =
// spotCheckCtrl.getOpenMismatches("scraped-bill", null, "CONTENT_KEY", null, false, false, false, false, true,
// new ServletWebRequest(new MockHttpServletRequest()));
// LocalTime end = LocalTime.now();
// logger.info("done {}", end);
// logger.info("took {}", Duration.between(start, end));
}Example 59
| Project: qbit-master File: Bug746.java View source code |
//Works
@Test
public void testWithServiceQueue() {
final ServiceQueue serviceQueue = ServiceBuilder.serviceBuilder().setServiceObject(new FeedServiceImpl()).buildAndStartAll();
final FeedService feedService = serviceQueue.createProxyWithAutoFlush(FeedService.class, Duration.ofMillis(100));
final List<FeedMeta> feedMetas = feedService.listFeeds().blockingGet(Duration.ofSeconds(30));
assertNotNull(feedMetas);
assertEquals(1, feedMetas.size());
assertEquals("Hello", feedMetas.get(0).name);
serviceQueue.stop();
}Example 60
| Project: reactor-core-master File: FluxWithProcessorVerification.java View source code |
@Override
public Processor<Integer, Integer> createProcessor(int bufferSize) {
Flux<String> otherStream = Flux.just("test", "test2", "test3");
System.out.println("Providing new downstream");
FluxProcessor<Integer, Integer> p = WorkQueueProcessor.create("fluxion-raw-fork", bufferSize);
cumulated.set(0);
cumulatedJoin.set(0);
BiFunction<Integer, String, Integer> combinator = ( t1, t2) -> t1;
return FluxProcessor.wrap(p, p.groupBy( k -> k % 2 == 0).flatMap( stream -> stream.scan(( prev, next) -> next).map( integer -> -integer).filter( integer -> integer <= 0).map( integer -> -integer).bufferTimeout(batch, Duration.ofMillis(50)).flatMap(Flux::fromIterable).doOnNext( array -> cumulated.getAndIncrement()).flatMap( i -> Flux.zip(Flux.just(i), otherStream, combinator)).doOnNext(this::monitorThreadUse)).doOnNext( array -> cumulatedJoin.getAndIncrement()).subscribeWith(TopicProcessor.create("fluxion-raw-join", bufferSize)).doOnError(Throwable::printStackTrace).awaitOnSubscribe());
}Example 61
| Project: reactor-master File: RouterGroupsTest.java View source code |
@Test
public void list() throws TimeoutException, InterruptedException {
this.routingClient.routerGroups().list(ListRouterGroupsRequest.builder().build()).flatMapIterable(ListRouterGroupsResponse::getRouterGroups).map(RouterGroup::getName).filter(DEFAULT_ROUTER_GROUP::equals).as(StepVerifier::create).expectNext(DEFAULT_ROUTER_GROUP).expectComplete().verify(Duration.ofMinutes(5));
}Example 62
| Project: sandbox-master File: PingService.java View source code |
/**
* @return the ping time in milliseconds
*/
@Override
public Long call() throws IOException {
Instant start = Instant.now();
try (Socket sock = new Socket()) {
InetSocketAddress endpoint = new InetSocketAddress(address, port);
// One alternative is InetAddress.isReachable(), but it seems to require
// root privileges under some operating systems
sock.connect(endpoint, timeout);
Instant end = Instant.now();
sock.close();
long millis = Duration.between(start, end).toMillis();
return millis;
}
}Example 63
| Project: selenese-runner-java-master File: StopWatch.java View source code |
/**
* Get human readable duration string.
*
* @return duration string.
*/
public String getDurationString() {
StringBuilder ds = new StringBuilder();
Duration d = Duration.ofMillis(endTime - startTime);
long h = d.toHours();
if (h > 0)
ds.append(h).append("hour");
long m = d.toMinutes() % 60;
if (ds.length() > 0)
ds.append('/').append(m).append("min");
else if (m > 0)
ds.append(m).append("min");
long s = d.getSeconds() % 60;
double ms = (d.toMillis() % 1000) / 1000.0;
if (ds.length() > 0)
ds.append('/');
ds.append(String.format("%.3fsec", s + ms));
return ds.toString();
}Example 64
| Project: spring-ide-master File: AppInstancesRefreshOperation.java View source code |
@Override
protected void doCloudOp(IProgressMonitor monitor) throws Exception {
this.model.setBaseRefreshState(RefreshState.loading("Fetching App Instances..."));
try {
if (!appsToLookUp.isEmpty()) {
Duration timeToWait = Duration.ofSeconds(30);
model.getRunTarget().getClient().getApplicationDetails(appsToLookUp).doOnNext(this.model::updateApplication).then().block(timeToWait);
}
model.setBaseRefreshState(RefreshState.READY);
} catch (Exception e) {
this.model.setBaseRefreshState(RefreshState.error(e));
throw e;
}
}Example 65
| Project: stability-master File: OverloadBasedHealthPolicy.java View source code |
@Override
public boolean isHealthy(String scope) {
// [1] all servlet container threads taken?
Threadpool pool = environment.getThreadpoolUsage();
if (pool.getCurrentThreadsBusy() >= pool.getMaxThreads()) {
TransactionMetrics metrics = metricsRegistry.transactions(scope);
// [2] more than 80% currently consumed by this operation?
if (metrics.running().size() > (pool.getMaxThreads() * 0.8)) {
// [3] is 50percentile higher than slow threshold?
Duration current50percentile = metrics.ofLast(Duration.ofMinutes(3)).percentile(50);
if (thresholdSlowTransaction.minus(current50percentile).isNegative()) {
return false;
}
}
}
return true;
}Example 66
| Project: teamengine-master File: TestRunSummary.java View source code |
/**
* Reads the test results and extracts summary information. Each entry in
* the results corresponds to a test set (conformance class).
*
* @param results
* The results for all test sets that were executed.
*/
void summarizeResults(Map<String, ISuiteResult> results) {
Date earliestStartDate = new Date();
Date latestEndDate = new Date();
for (Map.Entry<String, ISuiteResult> entry : results.entrySet()) {
ITestContext testContext = entry.getValue().getTestContext();
this.totalPassed += testContext.getPassedTests().size();
this.totalFailed += testContext.getFailedTests().size();
this.totalSkipped += testContext.getSkippedTests().size();
Date startDate = testContext.getStartDate();
if (earliestStartDate.after(startDate)) {
earliestStartDate = startDate;
}
Date endDate = testContext.getEndDate();
if (latestEndDate.before(endDate)) {
latestEndDate = (endDate != null) ? endDate : startDate;
}
}
this.totalDuration = Duration.between(earliestStartDate.toInstant(), latestEndDate.toInstant());
}Example 67
| Project: tempto-master File: JSchCliProcess.java View source code |
@Override
public void waitForWithTimeoutAndKill(Duration timeout) throws InterruptedException {
Thread thread = new Thread(() -> {
readRemainingOutputLines();
readRemainingErrorLines();
// active waiting based on http://www.jcraft.com/jsch/examples/Exec.java.html example
while (!channel.isClosed()) {
try {
sleep(100);
} catch (InterruptedException e) {
LOGGER.error("Interrupted exception", e);
}
}
});
thread.start();
thread.join(timeout.toMillis());
if (!channel.isClosed()) {
close();
thread.join();
throw new TimeoutRuntimeException("SSH channel did not finish within given timeout");
}
close();
int exitStatus = channel.getExitStatus();
if (channel.getExitStatus() != 0) {
throw new CommandExecutionException("SSH command exited with status: " + exitStatus, exitStatus);
}
}Example 68
| Project: Terasology-master File: PingService.java View source code |
/**
* @return the ping time in milliseconds
*/
@Override
public Long call() throws IOException {
Instant start = Instant.now();
try (Socket sock = new Socket()) {
InetSocketAddress endpoint = new InetSocketAddress(address, port);
// One alternative is InetAddress.isReachable(), but it seems to require
// root privileges under some operating systems
sock.connect(endpoint, timeout);
Instant end = Instant.now();
sock.close();
long millis = Duration.between(start, end).toMillis();
return millis;
}
}Example 69
| Project: threeten-jpa-master File: DurationConverterTest.java View source code |
@Test
public void reference() {
byte[] data = new byte[] { -128, 0, 0, 4, 65, 72, 70, -115, 59, 115, -128 };
Duration attribute = Duration.parse("P4DT5H12M10.222S");
assertEquals(attribute, IntervalConverter.intervaldsToDuration(new INTERVALDS(data)));
assertArrayEquals(data, IntervalConverter.durationToIntervalds(attribute).toBytes());
}Example 70
| Project: tradelib-master File: BarHierarchy.java View source code |
public BarHistory getHistory(String symbol, Duration duration) { HashMap<Duration, BarHistory> symbolHistories = historiesMap.get(symbol); if (symbolHistories == null) { return null; } BarHistory barHistory = symbolHistories.get(duration); if (barHistory == null) { barHistory = new BarHistory(); symbolHistories.put(duration, barHistory); } return barHistory; }
Example 71
| Project: tripled-framework-master File: LoggingEventBusInterceptor.java View source code |
@Override
public <ReturnType> ReturnType intercept(InterceptorChain<ReturnType> chain, Object event, UnitOfWork unitOfWork) {
LOGGER.debug("Executing command {}", event.getClass().getSimpleName());
Instant start = Instant.now();
try {
ReturnType proceed = chain.proceed();
LOGGER.debug("Finished executing command {}.", event.getClass().getSimpleName());
return proceed;
} catch (Throwable ex) {
LOGGER.debug("Command {} failed", event.getClass().getSimpleName());
throw ex;
} finally {
Instant end = Instant.now();
LOGGER.debug("Execution of {} took {}ms", event.getClass().getSimpleName(), Duration.between(start, end).toMillis());
}
}Example 72
| Project: clc-java-sdk-master File: SshjClient.java View source code |
private void withTimeout(Duration timeout, SshConnectFunc func) {
notNull(func);
notNull(timeout);
long startTime = System.currentTimeMillis();
for (; ; ) {
try {
func.connect();
return;
} catch (IOException ex) {
long curTime = System.currentTimeMillis();
if (timeout.toMillis() < curTime - startTime) {
throw new SshException(ex);
}
}
}
}Example 73
| Project: armeria-master File: SessionOptionsTest.java View source code |
@Test
public void valueOverrideTest() {
Duration connectionTimeout = Duration.ofMillis(10);
Duration idleTimeout = Duration.ofMillis(200);
EventLoop eventLoop = mock(EventLoop.class);
TrustManagerFactory trustManagerFactory = mock(TrustManagerFactory.class);
Integer maxConcurrency = 1;
SessionOptions options = SessionOptions.of(CONNECT_TIMEOUT.newValue(connectionTimeout), IDLE_TIMEOUT.newValue(idleTimeout), EVENT_LOOP_GROUP.newValue(eventLoop), TRUST_MANAGER_FACTORY.newValue(trustManagerFactory));
assertThat(options.get(CONNECT_TIMEOUT), is(Optional.of(connectionTimeout)));
assertThat(options.get(IDLE_TIMEOUT), is(Optional.of(idleTimeout)));
assertThat(options.get(EVENT_LOOP_GROUP), is(Optional.of(eventLoop)));
}Example 74
| Project: atomix-master File: DistributedValueExample.java View source code |
/**
* Starts the client.
*/
public static void main(String[] args) throws Exception {
if (args.length < 2)
throw new IllegalArgumentException("must supply a path and set of host:port tuples");
// Parse the address to which to bind the server.
String[] mainParts = args[1].split(":");
Address address = new Address(mainParts[0], Integer.valueOf(mainParts[1]));
// Build a list of all member addresses to which to connect.
List<Address> cluster = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
String[] parts = args[i].split(":");
cluster.add(new Address(parts[0], Integer.valueOf(parts[1])));
}
// Create a stateful Atomix replica. The replica communicates with other replicas in the cluster
// to replicate state changes.
AtomixReplica atomix = AtomixReplica.builder(address).withTransport(new NettyTransport()).withStorage(Storage.builder().withStorageLevel(StorageLevel.DISK).withDirectory(args[0]).withMinorCompactionInterval(Duration.ofSeconds(30)).withMajorCompactionInterval(Duration.ofMinutes(1)).withMaxSegmentSize(1024 * 1024 * 8).withMaxEntriesPerSegment(1024 * 8).build()).build();
atomix.bootstrap(cluster).join();
atomix.<String>getValue("value").thenAccept(DistributedValueExample::recursiveSet);
for (; ; ) {
Thread.sleep(1000);
}
}Example 75
| Project: autopsy-master File: DurationCellRenderer.java View source code |
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Long) {
{
Duration d = Duration.ofMillis((long) value);
if (d.isNegative()) {
d = Duration.ofMillis(-(long) value);
}
String result;
long days = d.toDays();
long hours = d.minusDays(days).toHours();
long minutes = d.minusDays(days).minusHours(hours).toMinutes();
long seconds = d.minusDays(days).minusHours(hours).minusMinutes(minutes).getSeconds();
if (minutes > 0) {
if (hours > 0) {
if (days > 0) {
result = days + " d " + hours + " h " + minutes + " m " + seconds + " s";
} else {
result = hours + " h " + minutes + " m " + seconds + " s";
}
} else {
result = minutes + " m " + seconds + " s";
}
} else {
result = seconds + " s";
}
setText(result);
}
}
grayCellIfTableNotEnabled(table, isSelected);
return this;
}Example 76
| Project: aws-big-data-blog-master File: ClickEventsToKinesisTestDriver.java View source code |
public static void main(String[] args) throws Exception {
final BlockingQueue<ClickEvent> events = new ArrayBlockingQueue<ClickEvent>(65536);
final ExecutorService exec = Executors.newCachedThreadPool();
// Change this line to use a different implementation
final AbstractClickEventsToKinesis worker = new BasicClickEventsToKinesis(events);
exec.submit(worker);
// Warm up the KinesisProducer instance
if (worker instanceof KPLClickEventsToKinesis) {
for (int i = 0; i < 200; i++) {
events.offer(generateClickEvent());
}
Thread.sleep(1000);
}
final LocalDateTime testStart = LocalDateTime.now();
final LocalDateTime testEnd = testStart.plus(TEST_DURATION);
exec.submit(() -> {
try {
while (LocalDateTime.now().isBefore(testEnd)) {
events.put(generateClickEvent());
}
worker.stop();
// This will unblock worker if it's blocked on the queue
events.offer(generateClickEvent());
exec.shutdown();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
});
// This reports the average records per second over a 10 second sliding window
new Thread(() -> {
Map<Long, Long> history = new TreeMap<>();
try {
while (!exec.isTerminated()) {
long seconds = Duration.between(testStart, LocalDateTime.now()).getSeconds();
long records = worker.recordsPut();
history.put(seconds, records);
long windowStart = seconds - 10;
long recordsAtWinStart = history.containsKey(windowStart) ? history.get(windowStart) : 0;
double rps = (double) (records - recordsAtWinStart) / 10;
System.out.println(String.format("%d seconds, %d records total, %.2f RPS (avg last 10s)", seconds, records, rps));
Thread.sleep(1000);
}
System.out.println("Finished.");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}).start();
}Example 77
| Project: buck-master File: HangMonitorTest.java View source code |
@Test
public void reportContainsCurrentThread() throws Exception {
final AtomicBoolean sleepingThreadShouldRun = new AtomicBoolean(true);
final SettableFuture<Void> sleepingThreadRunning = SettableFuture.create();
try {
Thread sleepingThread = new Thread("testThread") {
@Override
public void run() {
hangForHangMonitorTestReport();
}
private void hangForHangMonitorTestReport() {
sleepingThreadRunning.set(null);
try {
while (sleepingThreadShouldRun.get()) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
}
};
sleepingThread.start();
sleepingThreadRunning.get(1, TimeUnit.SECONDS);
final SettableFuture<String> result = SettableFuture.create();
HangMonitor hangMonitor = new HangMonitor(result::set, Duration.ofMillis(10));
hangMonitor.runOneIteration();
assertThat(result.isDone(), Matchers.is(true));
String report = result.get();
assertThat(report, Matchers.containsString("hangForHangMonitorTestReport"));
} finally {
sleepingThreadShouldRun.set(false);
}
}Example 78
| Project: camel-master File: BasicReactorToCamelExample.java View source code |
@PostConstruct
public void setupStreams() {
// Get a subscriber from camel
Subscriber<String> elements = camel.streamSubscriber("elements", String.class);
// Emit a string every 7 seconds and push it to the Camel "elements" stream
Flux.interval(Duration.ofSeconds(7)).map( item -> "element " + item).subscribe(elements);
}Example 79
| Project: CISEN-master File: DailyReportProcessor.java View source code |
@Override
public void process() {
if (!disableForDemo) {
// if (lastRun == null) {
// lastRun = LocalDate.now();
// } else {
// if (Duration.between(lastRun, LocalDate.now()).toDays() == 0) {
// return;
// }
// }
}
Map<String, DailyReportProcessorConfigDTO> jobs = getJobs();
MongoCollection collection = mongoDBService.getCollection(Constants.DB.BUILDS);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -1);
long timeInMills = calendar.getTimeInMillis();
for (Map.Entry<String, DailyReportProcessorConfigDTO> entry : jobs.entrySet()) {
String query = String.format("{ $and : [" + " {jobId : '%s'}, " + " {startTime : {$gt: %d}}, " + " {processed:false}" + "]}", entry.getKey(), timeInMills);
DailyStatistic statistic = new DailyStatistic();
try {
MongoCursor<CiReport> dailyReports = collection.find(query).as(CiReport.class);
if (dailyReports.count() > 0) {
while (dailyReports.hasNext()) {
CiReport report = dailyReports.next();
statistic.putReportToStatistic(report);
}
if (statistic.isNotEmpty()) {
generateReport(entry.getKey(), statistic);
}
dailyReports.close();
collection.update(query).with("{processed:true}");
}
} catch (IOException ex) {
LOGGER.error("Fail to close db cursor", ex);
}
}
}Example 80
| Project: copycat-master File: ValueStateMachineExample.java View source code |
/**
* Starts the server.
*/
public static void main(String[] args) throws Exception {
if (args.length < 2)
throw new IllegalArgumentException("must supply a path and set of host:port tuples");
// Parse the address to which to bind the server.
String[] mainParts = args[1].split(":");
Address address = new Address(mainParts[0], Integer.valueOf(mainParts[1]));
// Build a list of all member addresses to which to connect.
List<Address> members = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
String[] parts = args[i].split(":");
members.add(new Address(parts[0], Integer.valueOf(parts[1])));
}
CopycatServer server = CopycatServer.builder(address).withStateMachine(ValueStateMachine::new).withTransport(new NettyTransport()).withStorage(Storage.builder().withDirectory(args[0]).withMaxSegmentSize(1024 * 1024 * 32).withMinorCompactionInterval(Duration.ofMinutes(1)).withMajorCompactionInterval(Duration.ofMinutes(15)).build()).build();
server.serializer().register(SetCommand.class, 1);
server.serializer().register(GetQuery.class, 2);
server.serializer().register(DeleteCommand.class, 3);
server.bootstrap(members).join();
while (server.isRunning()) {
Thread.sleep(1000);
}
}Example 81
| Project: drools-master File: DurationFunction.java View source code |
public FEELFnResult<TemporalAmount> invoke(@ParameterName("from") String val) {
if (val == null) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
// try to parse as days/hours/minute/seconds
return FEELFnResult.ofResult(Duration.parse(val));
} catch (DateTimeParseException e) {
try {
return FEELFnResult.ofResult(Period.parse(val));
} catch (DateTimeParseException e2) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "date-parsing exception", new RuntimeException(new Throwable() {
public final List<Throwable> causes = Arrays.asList(new Throwable[] { e, e2 });
})));
}
}
}Example 82
| Project: dropwizard-experiment-master File: EmailVerificationResourceTest.java View source code |
@Test
public void shouldChangePasswordWhenUsed() {
EmailVerification verify = new EmailVerification(user, Duration.ofDays(2), EmailVerification.Type.PASSWORD_RESET);
db.save(verify);
POST("/verifications/" + verify.getToken() + "/passwordreset", formParameters("newPassword", "testpassword2"));
db.refresh(user);
assertThat(user.getPassword().equalsPlaintext("testpassword2")).isTrue();
}Example 83
| Project: elasticsearch-readonlyrest-plugin-master File: LdapClientWithCacheDecoratorTests.java View source code |
@Test
public void testIfAuthenticatedUserIsCachedByGivenDuration() throws Exception {
GroupsProviderLdapClient client = Mockito.mock(GroupsProviderLdapClient.class);
String dn = "cn=Example user,ou=People,dc=example,dc=com";
LdapCredentials credentials = new LdapCredentials("user", "password");
when(client.authenticate(any(LdapCredentials.class))).thenReturn(CompletableFuture.completedFuture(Optional.of(new LdapUser("user", dn))));
Duration ttl = Duration.ofSeconds(1);
GroupsProviderLdapClientCacheDecorator clientWithCache = new GroupsProviderLdapClientCacheDecorator(client, ttl);
Optional<LdapUser> ldapUser = clientWithCache.authenticate(credentials).get();
assertEquals(ldapUser.get().getDN(), dn);
Optional<LdapUser> ldapUserSecondAttempt = clientWithCache.authenticate(credentials).get();
assertEquals(ldapUserSecondAttempt.get().getDN(), dn);
Thread.sleep((long) (ttl.toMillis() * 1.5));
Optional<LdapUser> ldapUserThirdAttempt = clientWithCache.authenticate(credentials).get();
assertEquals(ldapUserThirdAttempt.get().getDN(), dn);
verify(client, times(2)).authenticate(credentials);
}Example 84
| Project: hibernate-semantic-query-master File: DurationJavaDescriptor.java View source code |
@Override
@SuppressWarnings("unchecked")
public <X> X unwrap(Duration duration, Class<X> type, WrapperOptions options) {
if (duration == null) {
return null;
}
if (Duration.class.isAssignableFrom(type)) {
return (X) duration;
}
if (String.class.isAssignableFrom(type)) {
return (X) duration.toString();
}
if (Long.class.isAssignableFrom(type)) {
return (X) Long.valueOf(duration.toNanos());
}
throw unknownUnwrap(type);
}Example 85
| Project: jackson-datatype-jsr310-master File: DurationDeserializer.java View source code |
@Override public Duration deserialize(JsonParser parser, DeserializationContext context) throws IOException { switch(parser.getCurrentTokenId()) { case JsonTokenId.ID_NUMBER_FLOAT: BigDecimal value = parser.getDecimalValue(); long seconds = value.longValue(); int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); return Duration.ofSeconds(seconds, nanoseconds); case JsonTokenId.ID_NUMBER_INT: if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { return Duration.ofSeconds(parser.getLongValue()); } return Duration.ofMillis(parser.getLongValue()); case JsonTokenId.ID_STRING: String string = parser.getText().trim(); if (string.length() == 0) { return null; } try { return Duration.parse(string); } catch (DateTimeException e) { return _rethrowDateTimeException(parser, context, e, string); } case JsonTokenId.ID_EMBEDDED_OBJECT: // values quite easily return (Duration) parser.getEmbeddedObject(); } throw context.mappingException("Expected type float, integer, or string."); }
Example 86
| Project: jdbi-master File: DurationColumnMapperFactory.java View source code |
@Override
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) {
if (type != Duration.class) {
return Optional.empty();
}
return Optional.of(( r, i, c) -> {
final Object obj = r.getObject(i);
if (obj == null) {
return null;
}
if (!(obj instanceof PGInterval)) {
throw new IllegalArgumentException(String.format("got non-pginterval %s", obj));
}
final PGInterval interval = (PGInterval) obj;
if (interval.getYears() != 0 || interval.getMonths() != 0) {
throw new IllegalArgumentException(String.format("pginterval \"%s\" not representable as duration", interval.getValue()));
}
final double seconds = interval.getSeconds();
if (seconds > Long.MAX_VALUE || seconds < Long.MIN_VALUE) {
throw new IllegalArgumentException(String.format("pginterval \"%s\" has seconds too extreme to represent as duration", interval.getValue()));
}
final long secondsLong = (long) seconds;
final long nanos = (long) ((seconds - secondsLong) * 1e9);
return Duration.ofDays(interval.getDays()).plusHours(interval.getHours()).plusMinutes(interval.getMinutes()).plusSeconds(secondsLong).plusNanos(nanos);
});
}Example 87
| Project: ldaptive-master File: PropertyValueParserTest.java View source code |
/**
* Property test data.
*
* @return configuration properties
*/
@DataProvider(name = "properties")
public Object[][] createProperties() {
final String p1 = "org.ldaptive.handler.RecursiveEntryHandler" + "{{searchAttribute=member}{mergeAttributes=mail,department}}";
final RecursiveEntryHandler o1 = new RecursiveEntryHandler();
o1.setSearchAttribute("member");
o1.setMergeAttributes("mail", "department");
final String p2 = "org.ldaptive.handler.MergeAttributeEntryHandler{ }";
final MergeAttributeEntryHandler o2 = new MergeAttributeEntryHandler();
final String p3 = "org.ldaptive.pool.IdlePruneStrategy{{prunePeriod=PT1M}{idleTime=PT2M}";
final IdlePruneStrategy o3 = new IdlePruneStrategy();
o3.setPrunePeriod(Duration.ofMinutes(1));
o3.setIdleTime(Duration.ofMinutes(2));
final String p4 = "org.ldaptive.sasl.CramMd5Config" + "{{securityStrength=LOW}{qualityOfProtection=AUTH}}";
final CramMd5Config o4 = new CramMd5Config();
o4.setSecurityStrength(SecurityStrength.LOW);
o4.setQualityOfProtection(QualityOfProtection.AUTH);
final String p5 = "{{mechanism=DIGEST_MD5}{authorizationId=test1}}";
final SaslConfig o5 = new SaslConfig();
o5.setMechanism(Mechanism.DIGEST_MD5);
o5.setAuthorizationId("test1");
final String p6 = "{mechanism=EXTERNAL}";
final SaslConfig o6 = new SaslConfig();
o6.setMechanism(Mechanism.EXTERNAL);
return new Object[][] { new Object[] { p1, null, o1 }, new Object[] { p2, null, o2 }, new Object[] { p3, null, o3 }, new Object[] { p4, null, o4 }, new Object[] { p5, SaslConfig.class, o5 }, new Object[] { p6, SaslConfig.class, o6 } };
}Example 88
| Project: nuxeo-master File: StandbyCommand.java View source code |
@Override
public void standby(int delay) throws InterruptedException {
if (Framework.getRuntime().isStandby()) {
return;
}
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());
try {
Framework.getRuntime().standby(Instant.now().plus(Duration.ofSeconds(delay)));
} finally {
Thread.currentThread().setContextClassLoader(loader);
}
}Example 89
| Project: openjdk-master File: TestChronologyPerf.java View source code |
@Test
public void test_chronologyGetAvailablePerf() {
long start = System.nanoTime();
Set<Chronology> chronos = Chronology.getAvailableChronologies();
long end = System.nanoTime();
Duration d = Duration.of(end - start, ChronoUnit.NANOS);
System.out.printf(" Cold Duration of Chronology.getAvailableChronologies(): %s%n", d);
start = System.nanoTime();
chronos = Chronology.getAvailableChronologies();
end = System.nanoTime();
d = Duration.of(end - start, ChronoUnit.NANOS);
System.out.printf(" Warm Duration of Chronology.getAvailableChronologies(): %s%n", d);
start = System.nanoTime();
HijrahChronology.INSTANCE.date(1434, 1, 1);
end = System.nanoTime();
d = Duration.of(end - start, ChronoUnit.NANOS);
System.out.printf(" Warm Duration of HijrahDate.date(1434, 1, 1): %s%n", d);
}Example 90
| Project: openjdk8-jdk-master File: TestChronologyPerf.java View source code |
@Test
public void test_chronologyGetAvailablePerf() {
long start = System.nanoTime();
Set<Chronology> chronos = Chronology.getAvailableChronologies();
long end = System.nanoTime();
Duration d = Duration.of(end - start, ChronoUnit.NANOS);
System.out.printf(" Cold Duration of Chronology.getAvailableChronologies(): %s%n", d);
start = System.nanoTime();
chronos = Chronology.getAvailableChronologies();
end = System.nanoTime();
d = Duration.of(end - start, ChronoUnit.NANOS);
System.out.printf(" Warm Duration of Chronology.getAvailableChronologies(): %s%n", d);
start = System.nanoTime();
HijrahChronology.INSTANCE.date(1434, 1, 1);
end = System.nanoTime();
d = Duration.of(end - start, ChronoUnit.NANOS);
System.out.printf(" Warm Duration of HijrahDate.date(1434, 1, 1): %s%n", d);
}Example 91
| Project: package-drone-master File: P2PerformanceTest.java View source code |
@Test
public void test1() throws Exception {
final Creator creator = new Creator(P2PerformanceTest.context, factoryLocal::get);
final ArtifactInformation artifact = new ArtifactInformation("abc", null, null, "foo-bar.jar", 100_000, Instant.now(), Collections.singleton("stored"), Collections.emptyList(), null, null, null);
final BundleInformation bi = new BundleInformation();
bi.setId("foo-bar");
bi.setVersion(new Version("1.0.0"));
bi.setName("Foo Bar");
bi.setVendor("Some Vendor");
final Instant start = Instant.now();
final int it = 50_000;
for (int i = 0; i < it; i++) {
creator.createBundleP2Artifacts(artifact, bi);
}
final Duration diff = Duration.between(start, Instant.now());
System.out.format("%s ms (%.2f ms/it)", diff.toMillis(), (double) diff.toMillis() / (double) it);
}Example 92
| Project: platform_build-master File: HangMonitorTest.java View source code |
@Test
public void reportContainsCurrentThread() throws Exception {
final AtomicBoolean sleepingThreadShouldRun = new AtomicBoolean(true);
final SettableFuture<Void> sleepingThreadRunning = SettableFuture.create();
try {
Thread sleepingThread = new Thread("testThread") {
@Override
public void run() {
hangForHangMonitorTestReport();
}
private void hangForHangMonitorTestReport() {
sleepingThreadRunning.set(null);
try {
while (sleepingThreadShouldRun.get()) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
}
};
sleepingThread.start();
sleepingThreadRunning.get(1, TimeUnit.SECONDS);
final SettableFuture<String> result = SettableFuture.create();
HangMonitor hangMonitor = new HangMonitor(result::set, Duration.ofMillis(10));
hangMonitor.runOneIteration();
assertThat(result.isDone(), Matchers.is(true));
String report = result.get();
assertThat(report, Matchers.containsString("hangForHangMonitorTestReport"));
} finally {
sleepingThreadShouldRun.set(false);
}
}Example 93
| Project: sample-data-generator-master File: TimestampedValueGroupGenerationServiceUnitTests.java View source code |
@Test
public void generateValueGroupsShouldWork() {
String trendKey = "foo";
double minimumValue = 50d;
double maximumValue = 90d;
BoundedRandomVariable randomVariable = new BoundedRandomVariable(1.0, minimumValue, maximumValue);
BoundedRandomVariableTrend randomVariableTrend = new BoundedRandomVariableTrend(randomVariable, 60d, 80d);
OffsetDateTime startDateTime = OffsetDateTime.now().minusDays(10);
OffsetDateTime endDateTime = OffsetDateTime.now();
MeasureGenerationRequest request = new MeasureGenerationRequest();
request.setStartDateTime(startDateTime);
request.setEndDateTime(endDateTime);
request.setMeanInterPointDuration(Duration.ofHours(6));
request.addTrend(trendKey, randomVariableTrend);
Iterable<TimestampedValueGroup> valueGroups;
do {
valueGroups = service.generateValueGroups(request);
} while (// in the extremely unlikely case of an empty list
Iterables.size(valueGroups) == 0);
for (TimestampedValueGroup valueGroup : valueGroups) {
assertThat(valueGroup.getValue(trendKey), greaterThanOrEqualTo(minimumValue));
assertThat(valueGroup.getValue(trendKey), lessThanOrEqualTo(maximumValue));
long effectiveDateTime = valueGroup.getTimestamp().toEpochSecond();
assertThat(effectiveDateTime, greaterThanOrEqualTo(startDateTime.toEpochSecond()));
assertThat(effectiveDateTime, lessThanOrEqualTo(endDateTime.toEpochSecond()));
}
}Example 94
| Project: spring-data-redis-master File: LettuceReactiveClusterListCommandsTests.java View source code |
// DATAREDIS-525
@Test
public void bRPopLPushShouldWorkCorrectlyWhenAllKeysMapToSameSlot() {
nativeCommands.rpush(SAME_SLOT_KEY_1, VALUE_1, VALUE_2, VALUE_3);
nativeCommands.rpush(SAME_SLOT_KEY_2, VALUE_1);
ByteBuffer result = connection.listCommands().bRPopLPush(SAME_SLOT_KEY_1_BBUFFER, SAME_SLOT_KEY_2_BBUFFER, Duration.ofSeconds(1)).block();
assertThat(result, is(equalTo(VALUE_3_BBUFFER)));
assertThat(nativeCommands.llen(SAME_SLOT_KEY_2), is(2L));
assertThat(nativeCommands.lindex(SAME_SLOT_KEY_2, 0), is(equalTo(VALUE_3)));
}Example 95
| Project: spring-metrics-master File: PrometheusTest.java View source code |
@Test
@Ignore
public void executeRequestsForOneMinute() {
Flux<String> flux = Flux.interval(Duration.ofSeconds(1)).map( input -> input + ": " + IntStream.of(1, numberOfRequests()).map( n -> {
restTemplate.getForObject("/index", String.class);
return 1;
}).sum());
flux.subscribe(System.out::println);
flux.blockLast();
}Example 96
| Project: spring-security-master File: StrictTransportSecurityHttpHeadersWriterTests.java View source code |
@Test
public void writeHttpHeadersWhenCustomMaxAgeThenWrites() {
Duration maxAge = Duration.ofDays(1);
hsts.setMaxAge(maxAge);
exchange = MockServerHttpRequest.get("https://example.com/").toExchange();
hsts.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, Arrays.asList("max-age=" + maxAge.getSeconds() + " ; includeSubDomains"));
}Example 97
| Project: torodb-master File: ExecutorServiceShutdownHelper.java View source code |
public void shutdown(ExecutorService executorService) throws InterruptedException {
Instant start = clock.instant();
executorService.shutdown();
boolean terminated = false;
int waitTime = 1;
while (!terminated) {
terminated = executorService.awaitTermination(waitTime, TimeUnit.SECONDS);
if (!terminated) {
LOGGER.info("ExecutorService {} did not finished in {}", executorService, Duration.between(start, clock.instant()));
}
}
}Example 98
| Project: tpop-examples-master File: S1Test.java View source code |
@Before
public void setup() {
driver = new HtmlUnitDriver(BrowserVersion.CHROME);
driver.setJavascriptEnabled(true);
WaitExecutor waitExecutor = new SeleniumWaitExecutor(driver, Duration.ofSeconds(5));
PageObjectFactory pageObjectFactory = new PageObjectFactory(driver, waitExecutor);
page = pageObjectFactory.newPageObject(S1Page.class);
driver.get("http://localhost:8085/view/s1.html");
}Example 99
| Project: wildfly-master File: ScheduleSchedulerCommand.java View source code |
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
Instant creationTime = this.metaData.getCreationTime();
Duration maxInactiveInterval = this.metaData.getMaxInactiveInterval();
Duration lastAccessedDuration = Duration.between(creationTime, this.metaData.getLastAccessedTime());
out.defaultWriteObject();
out.writeObject(creationTime);
out.writeObject(maxInactiveInterval);
out.writeObject(lastAccessedDuration);
}Example 100
| Project: XCoLab-master File: MessageLimitManager.java View source code |
/**
* Method responsible for checking if user is allowed to send given number
* of messages.
*
* @param messagesToSend
* number of messages that user wants to send
*/
public boolean canSendMessages(int messagesToSend, long memberId) {
synchronized (getMutex(memberId)) {
int messageLimit = getMessageLimit(memberId);
final Timestamp yesterday = Timestamp.from(Instant.now().minus(Duration.ofDays(1)));
long count = messageDao.countByGiven(memberId, null, null, null, yesterday);
return messageLimit >= count + messagesToSend;
}
}Example 101
| Project: AisStore-master File: PastTrackResource.java View source code |
/**
*/
@RequestMapping(value = "/pastTrack/{mmsi}", produces = MediaType.APPLICATION_JSON_VALUE)
List<IPositionMessage> track(@PathVariable int mmsi, @RequestParam(value = "sourceFilter", required = false) String sourceFilterExpression, @RequestParam(value = "duration", required = true) String iso8601Duration) {
Objects.requireNonNull(iso8601Duration);
List<IPositionMessage> pastTrack = pastTrackRepository.findByMmsi(createSourceFilterPredicate(sourceFilterExpression), Duration.parse(iso8601Duration), mmsi);
LOG.debug("Found " + pastTrack.size() + " past track entries for MMSI " + mmsi);
return pastTrack;
}