Example usage for java.time Instant now

List of usage examples for java.time Instant now

Introduction

In this page you can find the example usage for java.time Instant now.

Prototype

public static Instant now() 

Source Link

Document

Obtains the current instant from the system clock.

Usage

From source file:com.orange.cepheus.broker.controller.NgsiControllerTest.java

@Test
public void postUpdateContextWithoutProvidingApplicationAndWithoutRemoteBrokerButWithNotify() throws Exception {

    when(configuration.getRemoteUrl()).thenReturn(null);

    //localRegistrations mock return always without providingApplication
    when(providingApplication.hasNext()).thenReturn(false);
    when(localRegistrations.findProvidingApplication(any(), any())).thenReturn(providingApplication);

    //subscriptions mock return always with matched subscriptions
    when(matchedSubscriptions.hasNext()).thenReturn(true, false);
    SubscribeContext subscribeContext = createSubscribeContextTemperature();
    Subscription subscription = new Subscription("999999", Instant.now().plus(1, ChronoUnit.DAYS),
            subscribeContext);/*from   w ww  .  jav  a 2 s .  co  m*/
    when(matchedSubscriptions.next()).thenReturn(subscription);
    when(subscriptions.findSubscriptions(any(), any())).thenReturn(matchedSubscriptions);

    //ngsiclient mock return always createUpdateContextREsponseTemperature when call updateContext
    when(ngsiClient.updateContext(any(), any(), any())).thenReturn(updateContextResponseListenableFuture);

    //ngsiClient mock return always CODE_200
    when(ngsiClient.notifyContext(any(), any(), any())).thenReturn(notifyContextResponseListenableFuture);

    mockMvc.perform(post("/v1/updateContext").content(json(mapper, createUpdateContextTempSensorAndPressure()))
            .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.errorCode").doesNotExist())
            .andExpect(MockMvcResultMatchers.jsonPath("$.contextElementResponses[0].contextElement.id")
                    .value("S1"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.contextElementResponses[0].contextElement.type")
                    .value("TempSensor"))
            .andExpect(MockMvcResultMatchers
                    .jsonPath("$.contextElementResponses[0].contextElement.attributes[0].name").value("temp"))
            .andExpect(MockMvcResultMatchers
                    .jsonPath("$.contextElementResponses[0].contextElement.attributes[0].type").value("float"))
            .andExpect(MockMvcResultMatchers
                    .jsonPath("$.contextElementResponses[0].contextElement.attributes[0].value").value("15.5"))
            .andExpect(MockMvcResultMatchers
                    .jsonPath("$.contextElementResponses[0].contextElement.attributes[1].name")
                    .value("pressure"))
            .andExpect(MockMvcResultMatchers
                    .jsonPath("$.contextElementResponses[0].contextElement.attributes[1].type").value("int"))
            .andExpect(MockMvcResultMatchers
                    .jsonPath("$.contextElementResponses[0].contextElement.attributes[1].value").value("1015"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.contextElementResponses[0].statusCode.code")
                    .value("200"));

    //Capture attributes (Set<String> searchAttributes) when findProvidingApplication is called on localRegistrations Set<String> searchAttributes
    verify(localRegistrations).findProvidingApplication(entityIdArgumentCaptor.capture(),
            attributeArgumentCaptor.capture());

    //check entityId
    assertEquals("S1", entityIdArgumentCaptor.getValue().getId());
    assertEquals("TempSensor", entityIdArgumentCaptor.getValue().getType());
    assertFalse(entityIdArgumentCaptor.getValue().getIsPattern());

    //check attributes
    assertEquals(2, attributeArgumentCaptor.getValue().size());
    assertTrue(attributeArgumentCaptor.getValue().contains("temp"));
    assertTrue(attributeArgumentCaptor.getValue().contains("pressure"));

    //check ListenableFuture is called never and with addCallback method
    verify(updateContextResponseListenableFuture, never()).addCallback(any(), any());

    //verify ngsiClient.updateContext is never called
    verify(ngsiClient, never()).updateContext(any(), any(), any());

    //check ngsiClient.notify is called at least once
    // Capture notifyContext when postNotifyContextRequest is called on updateContextRequest,
    ArgumentCaptor<NotifyContext> notifyContextArg = ArgumentCaptor.forClass(NotifyContext.class);
    verify(notifyContextResponseListenableFuture, atLeastOnce()).addCallback(any(), any());
    String urlReference = subscribeContext.getReference().toString();
    verify(ngsiClient, atLeastOnce()).notifyContext(eq(urlReference), any(), notifyContextArg.capture());
    // Check id and status correspond to the required
    assertEquals(1, notifyContextArg.getValue().getContextElementResponseList().size());
    ContextElementResponse contextElementResponse = notifyContextArg.getValue().getContextElementResponseList()
            .get(0);
    assertEquals("S1", contextElementResponse.getContextElement().getEntityId().getId());
    assertEquals("200", contextElementResponse.getStatusCode().getCode());
}

From source file:com.vmware.photon.controller.api.client.resource.VmApiTest.java

@Test
public void testPerformResumeOperationAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    VmApi vmApi = new VmApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.performResumeOperationAsync("foo", new FutureCallback<Task>() {
        @Override/*from w w w .  j a  v  a 2  s .c o  m*/
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.VmRestApiTest.java

@Test
public void testPerformResumeOperationAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    VmApi vmApi = new VmRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.performResumeOperationAsync("foo", new FutureCallback<Task>() {
        @Override/* www .  ja v a 2 s  . c  o  m*/
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:io.dropwizard.revolver.resource.RevolverRequestResource.java

private Response executeCommandAsync(final String service, final RevolverHttpApiConfig api,
        final RevolverHttpApiConfig.RequestMethod method, final String path, final HttpHeaders headers,
        final UriInfo uriInfo, final byte[] body, final boolean isDownstreamAsync, final String callMode)
        throws Exception {
    val sanatizedHeaders = new MultivaluedHashMap<String, String>();
    headers.getRequestHeaders().forEach(sanatizedHeaders::put);
    cleanHeaders(sanatizedHeaders, api);
    val httpCommand = RevolverBundle.getHttpCommand(service);
    val requestId = headers.getHeaderString(RevolversHttpHeaders.REQUEST_ID_HEADER);
    val transactionId = headers.getHeaderString(RevolversHttpHeaders.TXN_ID_HEADER);
    val mailBoxId = headers.getHeaderString(RevolversHttpHeaders.MAILBOX_ID_HEADER);
    //Short circuit if it is a duplicate request
    if (persistenceProvider.exists(requestId)) {
        return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(Collections.singletonMap("message", "Duplicate")).build();
    }//w ww. j ava2s .c o  m
    persistenceProvider.saveRequest(requestId, mailBoxId,
            RevolverCallbackRequest.builder().api(api.getApi())
                    .mode(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALL_MODE_HEADER))
                    .callbackUri(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALLBACK_URI_HEADER))
                    .method(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALLBACK_METHOD_HEADER))
                    .service(service).path(path).headers(headers.getRequestHeaders())
                    .queryParams(uriInfo.getQueryParameters()).body(body).build());
    CompletableFuture<RevolverHttpResponse> response = httpCommand.executeAsync(RevolverHttpRequest.builder()
            .traceInfo(TraceInfo.builder().requestId(requestId).transactionId(transactionId)
                    .timestamp(System.currentTimeMillis()).build())
            .api(api.getApi()).service(service).path(path).method(method).headers(sanatizedHeaders)
            .queryParams(uriInfo.getQueryParameters()).body(body).build());
    //Async Downstream send accept on request path (Still circuit breaker will kick in. Keep circuit breaker aggressive)
    if (isDownstreamAsync) {
        val result = response.get();
        if (result.getStatusCode() == Response.Status.ACCEPTED.getStatusCode()) {
            persistenceProvider.setRequestState(requestId, RevolverRequestState.REQUESTED);
        } else {
            persistenceProvider.setRequestState(requestId, RevolverRequestState.RESPONDED);
            saveResponse(requestId, result);
        }
        return transform(headers, result, api.getApi(), path, method);
    } else {
        response.thenAcceptAsync(result -> {
            if (result.getStatusCode() == Response.Status.ACCEPTED.getStatusCode()) {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.REQUESTED);
            } else if (result.getStatusCode() == Response.Status.OK.getStatusCode()) {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.RESPONDED);
                saveResponse(requestId, result);
            } else {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.ERROR);
                saveResponse(requestId, result);
            }
            if (callMode != null && callMode.equals(RevolverHttpCommand.CALL_MODE_CALLBACK)) {
                callbackHandler.handle(requestId);
            }
        });
        return Response.accepted().entity(RevolverAckMessage.builder().requestId(requestId)
                .acceptedAt(Instant.now().toEpochMilli()).build()).build();
    }
}

From source file:keywhiz.service.resources.admin.SecretsResource.java

/**
 * Delete Secret by ID//from   ww  w.ja  v a 2 s.c  o m
 *
 * @excludeParams user
 * @param secretId the ID of the Secret to be deleted
 *
 * @description Deletes a single Secret if found.
 * Used by Keywhiz CLI and the web ui.
 * @responseMessage 200 Found and deleted Secret with given ID
 * @responseMessage 404 Secret with given ID not Found
 */
@Path("{secretId}")
@Timed
@ExceptionMetered
@DELETE
public Response deleteSecret(@Auth User user, @PathParam("secretId") LongParam secretId) {
    Optional<Secret> secret = secretController.getSecretById(secretId.get());
    if (!secret.isPresent()) {
        logger.info("User '{}' tried deleting a secret which was not found (id={})", user, secretId.get());
        throw new NotFoundException("Secret not found.");
    }

    logger.info("User '{}' deleting secret id={}, name='{}'", user, secretId, secret.get().getName());

    // Get the groups for this secret, so they can be restored manually if necessary
    Set<String> groups = aclDAOReadOnly.getGroupsFor(secret.get()).stream().map(Group::getName)
            .collect(toSet());

    secretDAOReadWrite.deleteSecretsByName(secret.get().getName());

    // Record the deletion
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("groups", groups.toString());
    extraInfo.put("current version", secret.get().getVersion().toString());
    auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_DELETE, user.getName(),
            secret.get().getName(), extraInfo));
    return Response.noContent().build();
}

From source file:com.derpgroup.echodebugger.resource.EchoDebuggerResource.java

public Object getUserContent(User user, String intent, String state, Map<String, String> slots) {

    if (MapUtils.isEmpty(slots)) {
        slots = null;//from www .ja va  2  s . c  o  m
    }

    Object response = null;
    IntentResponses intentResponses = user.getIntents().get(intent);
    if (intentResponses == null || MapUtils.isEmpty(intentResponses.getData())) {
        ResponseKey responseKey = new ResponseKey(intent, slots, state);
        String serializedResponseKey = ResponderUtils.serialize(responseKey);
        response = AlexaResponseUtil.createSimpleResponse("There is no response for this input",
                "There is no response for this input\n" + serializedResponseKey,
                "There is no response for this input");
    } else {
        response = intentResponses.getData();
    }

    // Update statistics for the user
    user.setNumContentDownloads(user.getNumContentDownloads() + 1);
    user.setLastEchoDownloadTime(Instant.now());
    int contentLength = ResponderUtils.getLengthOfContent(response);
    user.setNumCharactersDownloaded(user.getNumCharactersDownloaded() + contentLength);
    userDao.saveUser(user);

    return response;
}

From source file:com.vmware.photon.controller.api.client.resource.ProjectApiTest.java

@Test
public void testCreateVm() throws IOException {
    Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ProjectApi projectApi = new ProjectApi(restClient);

    Task task = projectApi.createVm("foo", new VmCreateSpec());
    assertEquals(task, responseTask);/*from  w w w.j  a v  a2  s  .c o m*/
}

From source file:com.vmware.photon.controller.api.client.resource.VmApiTest.java

@Test
public void testPerformSuspendOperation() throws IOException {
    Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    VmApi vmApi = new VmApi(restClient);

    Task task = vmApi.performSuspendOperation("foo");
    assertEquals(task, responseTask);//  w  w  w .  j a  va 2 s . c  o  m
}