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:reactor.ipc.netty.tcp.TcpServerTests.java

@Test
public void tcpServerHandlesJsonPojosOverSsl() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);

    SslContext clientOptions = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();/* w w w. j a  v a2  s  . c om*/
    final TcpServer server = TcpServer.create(opts -> opts.listen("localhost").sslSelfSigned());

    ObjectMapper m = new ObjectMapper();

    NettyContext connectedServer = server.newHandler((in, out) -> {
        in.receive().asByteArray().map(bb -> {
            try {
                return m.readValue(bb, Pojo.class);
            } catch (IOException io) {
                throw Exceptions.propagate(io);
            }
        }).log("conn").subscribe(data -> {
            if ("John Doe".equals(data.getName())) {
                latch.countDown();
            }
        });

        return out.sendString(Mono.just("Hi")).neverComplete();
    }).block(Duration.ofSeconds(30));

    final TcpClient client = TcpClient.create(
            opts -> opts.connect("localhost", connectedServer.address().getPort()).sslContext(clientOptions));

    NettyContext connectedClient = client.newHandler((in, out) -> {
        //in
        in.receive().asString().log("receive").subscribe(data -> {
            if (data.equals("Hi")) {
                latch.countDown();
            }
        });

        //out
        return out.send(Flux.just(new Pojo("John" + " Doe")).map(s -> {
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                m.writeValue(os, s);
                return out.alloc().buffer().writeBytes(os.toByteArray());
            } catch (IOException ioe) {
                throw Exceptions.propagate(ioe);
            }
        })).neverComplete();
        //         return Mono.empty();
    }).block(Duration.ofSeconds(30));

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

    connectedClient.dispose();
    connectedServer.dispose();
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

public static Duration readTime(ByteBuf in) {
    in.readBytes(6);//from  w w w .  j  a v  a  2 s .  com
    int hour = readInt(in);
    int minute = readInt(in);
    int second = readInt(in);
    return Duration.ofSeconds(hour * 3600 + minute * 60 + second);
}

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

@Override
public Void run(Continuation cnt) throws Exception {
    Context ctx = (Context) cnt.getContext();

    if (bootstrapLink == null) {
        ctx.addOutgoingMessage(subAddress, logAddress,
                info("Initial node in the network. No bootstrap to join."));
        return null;
    }/* ww  w  . j av a  2s. c o  m*/

    // 0. Get ID of bootstarp node
    ctx.addOutgoingMessage(subAddress, logAddress, info("Getting ID for bootstrap link {}", bootstrapLink));
    Address destinationAddress = addressTransformer.toAddress(bootstrapLink)
            .appendSuffix(ROUTER_EXT_HANDLER_RELATIVE_ADDRESS);
    PingResponse pingResponse = new RequestSubcoroutine.Builder<PingResponse>()
            .sourceAddress(subAddress, idGenerator).destinationAddress(destinationAddress)
            .timerAddress(timerAddress).request(new PingRequest(null))
            .addExpectedResponseType(PingResponse.class).attemptInterval(Duration.ofSeconds(2L)).maxAttempts(5)
            .throwExceptionIfNoResponse(false).build().run(cnt);

    Validate.isTrue(pingResponse != null, "Bootstrap link {} did not respond to ping", bootstrapLink);
    Id bootstrapId = pingResponse.getId();
    Validate.isTrue(!bootstrapId.equals(baseId), "Bootstrap ID {} conflicts with self", bootstrapId); // bootstrap must not be self

    Node bootstrapNode = new Node(pingResponse.getId(), bootstrapLink);

    // 1. Add bootstrap node to routing tree
    ctx.addOutgoingMessage(subAddress, logAddress,
            info("Attempting to join the network via {}...", bootstrapNode));
    applyNodesToRouter(ctx, Collections.singletonList(bootstrapNode));

    // 2. Find yourself
    List<Node> closestNodes;

    ctx.addOutgoingMessage(subAddress, logAddress, info("Attempting to find self...", bootstrapNode));
    closestNodes = new FindSubcoroutine(subAddress.appendSuffix("selffind"), state, baseId, 20, false, false)
            .run(cnt);
    Validate.validState(!closestNodes.isEmpty(), "No results from bootstrap");
    Validate.validState(!closestNodes.get(0).getId().equals(baseId), "Self already exists in network");
    applyNodesToRouter(ctx, closestNodes);

    // There's a race condition here where 2 nodes with the same ID can be joining at the same time. There's no way to detect that case.

    // 3. Start bucket refreshes for all buckets
    ctx.addOutgoingMessage(subAddress, logAddress, info("Populating routing tree..."));
    List<BitString> bucketPrefixes = router.dumpBucketPrefixes();

    int idBitLength = baseId.getBitLength();
    int idByteLength = idBitLength / 8 + (idBitLength % 8 == 0 ? 0 : 1);
    byte[] idBytes = new byte[idByteLength];
    for (BitString bucketPrefix : bucketPrefixes) {
        // If the prefix is our own ID, don't try to find it
        if (baseId.getBitString().equals(bucketPrefix)) {
            continue;
        }

        // Create random id in bucket's range
        secureRandom.nextBytes(idBytes);
        Id randomId = Id.create(BitString.createLogicalOrder(idBytes, 0, idBitLength).setBits(0, bucketPrefix));

        ctx.addOutgoingMessage(subAddress, logAddress, info("Searching for random ID {}...", randomId));

        // Find closest nodes
        closestNodes = new FindSubcoroutine(subAddress.appendSuffix("bucketfind"), state, randomId, 20, false,
                false).run(cnt);

        // Touch router with these nodes
        applyNodesToRouter(ctx, closestNodes);
    }

    // 4. Advertise self to closest nodes so people can reach you
    ctx.addOutgoingMessage(subAddress, logAddress, info("Finding closest nodes to self..."));
    closestNodes = new FindSubcoroutine(subAddress.appendSuffix("adv"), state, baseId, 20, true, true).run(cnt);
    applyNodesToRouter(ctx, closestNodes);

    return null;
}

From source file:com.microsoft.azure.servicebus.samples.topicfilters.TopicFilters.java

void receiveAllMessageFromSubscription(String connectionString, String subsName) throws Exception {
    int receivedMessages = 0;

    // Create subscription client.
    IMessageReceiver subscriptionClient = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, TopicName + "/subscriptions/" + subsName),
            ReceiveMode.RECEIVEANDDELETE);

    // Create a receiver from the subscription client and receive all messages.
    System.out.printf("\nReceiving messages from subscription %s.\n", subsName);

    while (true) {
        IMessage receivedMessage = subscriptionClient.receive(Duration.ofSeconds(10));
        if (receivedMessage != null) {
            if (receivedMessage.getProperties() != null) {
                for (String prop : receivedMessage.getProperties().keySet()) {
                    System.out.printf("%s=%s, ", prop, receivedMessage.getProperties().get(prop));
                }// ww w.  j  a  va2s  .c o m
            }
            System.out.printf("CorrelationId=%s\n", receivedMessage.getCorrelationId());
            receivedMessages++;
        } else {
            // No more messages to receive.
            break;
        }
    }
    System.out.printf("Received %s messages from subscription %s.\n", receivedMessages, subsName);
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

CompletableFuture<Void> exceedMaxDelivery(String connectionString, String queueName) throws Exception {
    IMessageReceiver receiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK);

    while (true) {
        IMessage msg = receiver.receive(Duration.ofSeconds(2));
        if (msg != null) {
            System.out.printf("Picked up message; DeliveryCount %d\n", msg.getDeliveryCount());
            receiver.abandon(msg.getLockToken());
        } else {//from  ww w. ja v a 2 s.c  o m
            break;
        }
    }
    receiver.close();

    IMessageReceiver deadletterReceiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue/$deadletterqueue"), ReceiveMode.PEEKLOCK);
    while (true) {
        IMessage msg = deadletterReceiver.receive(Duration.ofSeconds(2));
        if (msg != null) {
            System.out.printf("\nDeadletter message:\n");
            if (msg.getProperties() != null) {
                for (String prop : msg.getProperties().keySet()) {
                    System.out.printf("\t%s=%s\n", prop, msg.getProperties().get(prop));
                }
            }
            deadletterReceiver.complete(msg.getLockToken());
        } else {
            break;
        }
    }
    deadletterReceiver.close();
    return CompletableFuture.completedFuture(null);
}

From source file:org.rakam.ui.DashboardService.java

@JsonRequest
@ApiOperation(value = "Get Report")
@Path("/get")
public List<DashboardItem> get(@Named("user_id") Project project, @ApiParam("name") String name) {
    try (Handle handle = dbi.open()) {
        return handle.createQuery("SELECT id, name, directive, options, refresh_interval, last_updated,"
                + "(case when now() - last_updated > refresh_interval * INTERVAL '1 second' then null else data end)"
                + " FROM dashboard_items WHERE dashboard = (SELECT id FROM dashboard WHERE project_id = :project AND name = :name)")
                .bind("project", project.project).bind("name", name).map((i, r, statementContext) -> {
                    return new DashboardItem(r.getInt(1), r.getString(2), r.getString(3),
                            JsonHelper.read(r.getString(4), Map.class), Duration.ofSeconds(r.getInt(5)),
                            r.getTimestamp(6) != null ? r.getTimestamp(6).toInstant() : null, r.getBytes(7));
                }).list();//w ww. j  a  v a2  s. c  om
    }
}

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

@Override
@Transient/* w  ww .ja  v  a  2 s .c o m*/
public Duration getDocumentEventProcessingTimeout() {
    return documentEventProcessingTimeoutSeconds == null ? null
            : Duration.ofSeconds(documentEventProcessingTimeoutSeconds);
}

From source file:org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundry2630AndLaterTaskLauncher.java

/**
 * Set up a reactor flow to launch a task. Before launch, check if the base application exists. If not, deploy then launch task.
 *
 * @param request description of the application to be launched
 * @return name of the launched task, returned without waiting for reactor pipeline to complete
 *///from   ww  w  .  j  a  v a 2 s . com
@Override
public String launch(AppDeploymentRequest request) {
    return getOrDeployApplication(request).then(application -> launchTask(application, request))
            .doOnSuccess(r -> logger.info("Task {} launch successful", request))
            .doOnError(t -> logger.error(String.format("Task %s launch failed", request), t))
            .block(Duration.ofSeconds(this.deploymentProperties.getApiTimeout()));
}

From source file:org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundry2630AndLaterTaskLauncher.java

@Override
public void destroy(String appName) {
    requestDeleteApplication(appName).timeout(Duration.ofSeconds(this.deploymentProperties.getApiTimeout()))
            .doOnSuccess(v -> logger.info("Successfully destroyed app {}", appName))
            .doOnError(e -> logger.error(String.format("Failed to destroy app %s", appName), e)).subscribe();
}