Example usage for java.time Duration ofSeconds

List of usage examples for java.time Duration ofSeconds

Introduction

In this page you can find the example usage for java.time Duration ofSeconds.

Prototype

public static Duration ofSeconds(long seconds) 

Source Link

Document

Obtains a Duration representing a number of seconds.

Usage

From source file:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitorTest.java

@Test
public void testShutdownNotYetStartedContainer() throws Exception {
    @Cleanup//  w w  w  .j a v a  2 s .c  o  m
    CuratorFramework zkClient = startClient();
    initializeHostContainerMapping(zkClient);

    SegmentContainerRegistry containerRegistry = createMockContainerRegistry();
    @Cleanup
    ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient);
    segMonitor.initialize(Duration.ofSeconds(1));

    // Simulate a container that takes a long time to start. Should be greater than a few monitor loops.
    ContainerHandle containerHandle = mock(ContainerHandle.class);
    when(containerHandle.getContainerId()).thenReturn(2);
    CompletableFuture<ContainerHandle> startupFuture = FutureHelpers
            .delayedFuture(() -> CompletableFuture.completedFuture(containerHandle), 3000, executorService());
    when(containerRegistry.startContainer(eq(2), any())).thenReturn(startupFuture);

    // Use ZK to send that information to the Container Manager.
    HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH);
    currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2));
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    // Verify it's not yet started.
    verify(containerRegistry, timeout(1000).atLeastOnce()).startContainer(eq(2), any());
    assertEquals(0, segMonitor.getRegisteredContainers().size());

    // Now simulate shutting it down.
    when(containerRegistry.stopContainer(any(), any())).thenReturn(CompletableFuture.completedFuture(null));

    currentData.clear();
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    verify(containerRegistry, timeout(10000).atLeastOnce()).stopContainer(any(), any());
    Thread.sleep(2000);
    assertEquals(0, segMonitor.getRegisteredContainers().size());
}

From source file:com.offbynull.voip.kademlia.FindSubcoroutine.java

@Override
public List<Node> run(Continuation cnt) throws Exception {
    Context ctx = (Context) cnt.getContext();

    ctx.addOutgoingMessage(subAddress, logAddress, info("Finding {}", findId));

    // Set up subcoroutine router
    Address routerAddress = subAddress.appendSuffix("finderreq" + idGenerator.generate());
    SubcoroutineRouter msgRouter = new SubcoroutineRouter(routerAddress, ctx);
    Controller msgRouterController = msgRouter.getController();

    // Get initial set of nodes to query from routing table
    List<Node> startNodes = router.find(findId, maxResults, false); // do not include stale nodes, we only want to contact alive nodes
    ctx.addOutgoingMessage(subAddress, logAddress,
            info("Route table entries closest to {}: {}", findId, startNodes));

    // Create sorted set of nodes to contact
    IdXorMetricComparator idClosenessComparator = new IdXorMetricComparator(findId);
    TreeSet<Node> contactSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId()));
    contactSet.addAll(startNodes);/*from w  ww  .ja  v a 2  s.  c o m*/

    // Create a sorted set of nodes to retain closest nodes in
    TreeSet<Node> closestSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId()));

    // Execute requests
    Map<Subcoroutine<?>, Node> requestSubcoroutineToNodes = new HashMap<>(); // executing requests
    Set<Id> queriedSet = new HashSet<>(); // ids that have already been queried
    while (true) {
        // If there's room left to query more contacts that are closer to findId, do so... 
        while (msgRouterController.size() < maxConcurrentRequests && !contactSet.isEmpty()) {
            // Get next farthest away node to contact
            Node contactNode = contactSet.pollLast();

            // Add it to set of set of ids that have already been queried.. if it's already there, it means that it's already been
            // queried by this find, so skip it...
            boolean added = queriedSet.add(contactNode.getId());
            if (!added) {
                continue;
            }

            // Add it to the set of closest nodes (will be removed if node fails to respond)
            closestSet.add(contactNode);

            // If we already have maxResult closer nodes to findId, skip this node
            if (closestSet.size() > maxResults) {
                Node removedNode = closestSet.pollLast();
                if (removedNode == contactNode) {
                    continue;
                }
            }

            // Initialize query
            Address destinationAddress = addressTransformer.toAddress(contactNode.getLink())
                    .appendSuffix(ROUTER_EXT_HANDLER_RELATIVE_ADDRESS);
            RequestSubcoroutine<FindResponse> reqSubcoroutine = new RequestSubcoroutine.Builder<FindResponse>()
                    .sourceAddress(routerAddress, idGenerator).destinationAddress(destinationAddress)
                    .timerAddress(timerAddress)
                    .request(new FindRequest(advertiseSelf ? baseId : null, findId, maxResults))
                    .addExpectedResponseType(FindResponse.class).attemptInterval(Duration.ofSeconds(2L))
                    .maxAttempts(5).throwExceptionIfNoResponse(false).build();

            ctx.addOutgoingMessage(subAddress, logAddress, info("Querying node {}", contactNode));

            // Add query to router
            msgRouterController.add(reqSubcoroutine, AddBehaviour.ADD_PRIME_NO_FINISH);
            requestSubcoroutineToNodes.put(reqSubcoroutine, contactNode);
        }

        // If there are no more requests running, it means we're finished
        if (msgRouterController.size() == 0) {
            ctx.addOutgoingMessage(subAddress, logAddress, info("Find complete: {}", closestSet));
            return new ArrayList<>(closestSet);
        }

        // Wait for next messange forward to the router
        cnt.suspend();
        ForwardResult fr = msgRouter.forward();

        // If a request completed from the forwarded message
        if (fr.isForwarded() && fr.isCompleted()) { // calling isCompleted by itself may throw an exception, check isForwarded first
            // Get response
            FindResponse findResponse = (FindResponse) fr.getResult();

            if (findResponse == null) {
                // If failure, then mark as stale and remove from closest
                // DONT BOTHER WITH TRYING TO CALCULATE LOCKING/UNLOCKING LOGIC. THE LOGIC WILL BECOME EXTREMELY CONVOLUTED. THE QUERY
                // DID 5 REQUEST. IF NO ANSWER WAS GIVEN IN THE ALLOTED TIME, THEN MARK AS STALE!
                Node contactedNode = requestSubcoroutineToNodes.remove(fr.getSubcoroutine());
                try {
                    // not allowed to mark self as stale -- we may want to find self, but if we do and it's not responsive dont try to
                    // mark it as stale
                    if (!contactedNode.getId().equals(baseId)) {
                        router.stale(contactedNode);
                    }
                } catch (NodeNotFoundException nnfe) { // may have been removed (already marked as stale) / may not be in routing tree
                    // Do nothing
                }
                closestSet.remove(contactedNode);
            } else {
                // If success, then add returned nodes to contacts
                Node[] nodes = findResponse.getNodes();
                contactSet.addAll(Arrays.asList(nodes));

                // If we don't want to find our own ID / query ourselves... remove any reference to our own ID in the contactSet
                // TODO: optimize this by removing before it's added to contactSet
                if (ignoreSelf) {
                    contactSet.removeIf(x -> x.getId().equals(baseId));
                }
            }
        }
    }
}

From source file:reactor.ipc.netty.tcp.TcpServerTests.java

@Test
public void exposesNettyPipelineConfiguration() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);

    final TcpClient client = TcpClient.create(port);

    BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> serverHandler = (in,
            out) -> {/*from  w w  w. ja  v  a2  s  .  c  om*/
        in.receive().asString().subscribe(data -> {
            log.info("data " + data + " on " + in);
            latch.countDown();
        });
        return Flux.never();
    };

    TcpServer server = TcpServer
            .create(opts -> opts.afterChannelInit(c -> c.pipeline().addBefore(NettyPipeline.ReactiveBridge,
                    "codec", new LineBasedFrameDecoder(8 * 1024))).listen(port));

    NettyContext connected = server.newHandler(serverHandler).block(Duration.ofSeconds(30));

    client.newHandler((in, out) -> out.send(
            Flux.just("Hello World!\n", "Hello 11!\n").map(b -> out.alloc().buffer().writeBytes(b.getBytes()))))
            .block(Duration.ofSeconds(30));

    assertTrue("Latch was counted down", latch.await(10, TimeUnit.SECONDS));

    connected.dispose();
}

From source file:org.ng200.openolympus.ContestTest.java

@Test
public void checkContestTimeExtensions() throws Exception {
    final Contest contest = this.createContestDirectly(Duration.ofSeconds(0));
    final Task task1 = this.createDummyTask();
    final Task task2 = this.createDummyTask();
    contest.setTasks(ImmutableSet.<Task>builder().add(task1).build());
    this.contestService.saveContest(contest);

    this.contestService.addContestParticipant(contest, this.testUser1);
    this.contestService.addContestParticipant(contest, this.testUser2);
    this.contestService.addContestParticipant(contest, this.testUser3);
    this.contestService.addContestParticipant(contest, this.testUser4);
    this.contestService.extendTimeForUser(contest, this.testUser4, Duration.ofSeconds(1000));

    long time = System.currentTimeMillis();
    time = this.dummyData(task1, task2, time);

    this.mockMvc.perform(MockMvcRequestBuilders.get("/api/contest/" + contest.getId() + "/completeResults"))
            .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType(this.contentType))
            .andExpect(MockMvcResultMatchers.jsonPath("$").isArray())
            .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(4)))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].username").value("test4"))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].rank").value(1))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].score", ToStringMatcher.compareBigDecimals("2.00")))
            .andExpect(MockMvcResultMatchers.jsonPath("$[1].username").value("test1"))
            .andExpect(MockMvcResultMatchers.jsonPath("$[1].rank").value(2))
            .andExpect(MockMvcResultMatchers.jsonPath("$[1].score", ToStringMatcher.compareBigDecimals("0.00")))
            .andExpect(MockMvcResultMatchers.jsonPath("$[2].username").value("test2"))
            .andExpect(MockMvcResultMatchers.jsonPath("$[2].rank").value(2))
            .andExpect(MockMvcResultMatchers.jsonPath("$[3].username").value("test3"))
            .andExpect(MockMvcResultMatchers.jsonPath("$[3].rank").value(2));

    this.mockMvc.perform(MockMvcRequestBuilders.get("/api/contest/" + contest.getId() + "/testingFinished"))
            .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string("true"));

    this.createDummySolution(time++, task1, this.testUser4, 20, 100, false);

    this.mockMvc.perform(MockMvcRequestBuilders.get("/api/contest/" + contest.getId() + "/testingFinished"))
            .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string("false"));
}

From source file:org.esbtools.eventhandler.lightblue.config.EventHandlerConfigEntity.java

@Override
@Transient//  www  .j  a va  2  s. c  o m
public Duration getNotificationProcessingTimeout() {
    return notificationProcessingTimeoutSeconds == null ? null
            : Duration.ofSeconds(notificationProcessingTimeoutSeconds);
}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

private static void initDatabase() {
    Optional<OrientDBService> orientDBService = TypeSafeObjectRegistry.GLOBAL_OBJECT_REGISTRY
            .get(OrientDBService.ORIENTDB_SERVICE);
    while (!orientDBService.isPresent()) {
        log.log(Level.WARNING, "Waiting for OrientDBService ...");
        sleep(Duration.ofSeconds(2));
        orientDBService = TypeSafeObjectRegistry.GLOBAL_OBJECT_REGISTRY.get(OrientDBService.ORIENTDB_SERVICE);
    }/*from ww w  .ja  v  a 2  s  . c  om*/

    final OServerAdmin admin = orientDBService.get().getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, EventLogRepository.DB);
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        admin.close();
    }

    EventLogRepository.initDatabase(
            orientDBService.get().getODatabaseDocumentTxSupplier(EventLogRepository.DB).get().get());
}

From source file:reactor.ipc.netty.tcp.TcpServerTests.java

@Test
@Ignore/*from   ww  w  .  ja  v a 2 s. co m*/
public void test5() throws Exception {
    //Hot stream of data, could be injected from anywhere
    EmitterProcessor<String> broadcaster = EmitterProcessor.<String>create().connect();

    //Get a reference to the tail of the operation pipeline (microbatching + partitioning)
    final Processor<List<String>, List<String>> processor = WorkQueueProcessor.create(false);

    broadcaster

            //transform 10 data in a [] of 10 elements or wait up to 1 Second before emitting whatever the list contains
            .bufferTimeout(10, Duration.ofSeconds(1)).log("broadcaster").subscribe(processor);

    //on a server dispatching data on the default shared dispatcher, and serializing/deserializing as string
    //Listen for anything exactly hitting the root URI and route the incoming connection request to the callback
    NettyContext s = HttpServer.create(0).newRouter(r -> r.get("/", (request, response) -> {
        //prepare a response header to be appended first before any reply
        response.addHeader("X-CUSTOM", "12345");
        //attach to the shared tail, take the most recent generated substream and merge it to the high level stream
        //returning a stream of String from each microbatch merged
        return response.sendString(Flux.from(processor)
                //split each microbatch data into individual data
                .flatMap(Flux::fromIterable).take(Duration.ofSeconds(5)).concatWith(Flux.just("end\n")));
    })).block(Duration.ofSeconds(30));

    for (int i = 0; i < 50; i++) {
        Thread.sleep(500);
        broadcaster.onNext(System.currentTimeMillis() + "\n");
    }

    s.dispose();

}

From source file:com.microsoft.azure.servicebus.samples.managingtopicrules.ManagingTopicRules.java

private static void receiveMessages(String subscriptionName) throws ServiceBusException, InterruptedException {
    IMessageReceiver subscriptionReceiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, topicName + "/subscriptions/" + subscriptionName),
            ReceiveMode.RECEIVEANDDELETE);

    logger.info(String.format("Receiving Messages From Subscription: %s", subscriptionName));
    int receivedMessageCount = 0;
    while (true) {
        IMessage receivedMessage = subscriptionReceiver.receive(Duration.ofSeconds(5));
        if (receivedMessage != null) {
            String colorProperty = receivedMessage.getProperties().get("Color");
            logger.info(String.format("Color Property = %s, CorrelationId = %s", colorProperty,
                    receivedMessage.getCorrelationId()));
            receivedMessageCount++;/*w  w  w.ja va 2 s . c  o  m*/
        } else {
            break;
        }
    }

    logger.info(String.format("Received '%d' Messages From Subscription: %s", receivedMessageCount,
            subscriptionName));
    subscriptionReceiver.close();
}

From source file:org.esbtools.eventhandler.lightblue.config.EventHandlerConfigEntity.java

@Override
@Transient//from   w  w w. ja va2  s .c o m
public Duration getNotificationExpireThreshold() {
    return notificationExpireThresholdSeconds == null ? null
            : Duration.ofSeconds(notificationExpireThresholdSeconds);
}

From source file:io.pravega.service.server.host.ZKSegmentContainerMonitorTest.java

@Test
public void testRetryOnStartFailures() throws Exception {
    @Cleanup//w w  w  .j  a  v  a 2 s.com
    CuratorFramework zkClient = startClient();
    initializeHostContainerMapping(zkClient);

    SegmentContainerRegistry containerRegistry = createMockContainerRegistry();
    @Cleanup
    ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient);
    segMonitor.initialize(Duration.ofSeconds(1));

    // Simulate a container that fails to start.
    CompletableFuture<ContainerHandle> failedFuture = FutureHelpers.failedFuture(new RuntimeException());
    when(containerRegistry.startContainer(eq(2), any())).thenReturn(failedFuture);

    // Use ZK to send that information to the Container Manager.
    HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH);
    currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2));
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    // Verify that it does not start.
    verify(containerRegistry, timeout(10000).atLeastOnce()).startContainer(eq(2), any());
    assertEquals(0, segMonitor.getRegisteredContainers().size());

    // Now simulate success for the same container.
    ContainerHandle containerHandle = mock(ContainerHandle.class);
    when(containerHandle.getContainerId()).thenReturn(2);
    when(containerRegistry.startContainer(eq(2), any()))
            .thenReturn(CompletableFuture.completedFuture(containerHandle));

    // Verify that it retries and starts the same container again.
    verify(containerRegistry, timeout(10000).atLeastOnce()).startContainer(eq(2), any());
    Thread.sleep(2000);
    assertEquals(1, segMonitor.getRegisteredContainers().size());
}