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.vmware.photon.controller.api.client.resource.DisksApiTest.java

@Test
public void testDelete() 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);

    DisksApi disksApi = new DisksApi(restClient);

    Task task = disksApi.delete("foo");
    assertEquals(task, responseTask);/*www.j a v  a  2  s.c  om*/
}

From source file:org.noorganization.instalist.server.api.UnitResourceTest.java

@Test
public void testPostUnit() throws Exception {
    String url = "/groups/%d/units";
    UnitInfo newUnit = new UnitInfo().withUUID(mUnit.getUUID()).withName("unit4");
    Instant preInsert = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request()
            .post(Entity.json(newUnit));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").post(Entity.json(newUnit));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newUnit));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newUnit));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mUnit);//from ww  w  .j a v  a 2  s.co m
    assertEquals("unit1", mUnit.getName());

    newUnit.setUUID(UUID.randomUUID());
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newUnit));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<Unit> savedUnitQuery = mManager
            .createQuery("select u from " + "Unit u where u.group = :group and u.UUID = :uuid", Unit.class);
    savedUnitQuery.setParameter("group", mGroup);
    savedUnitQuery.setParameter("uuid", UUID.fromString(newUnit.getUUID()));
    List<Unit> savedUnits = savedUnitQuery.getResultList();
    assertEquals(1, savedUnits.size());
    assertEquals("unit4", savedUnits.get(0).getName());
    assertTrue(preInsert.isBefore(savedUnits.get(0).getUpdated()));
}

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

@Test
public void testDelete() 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);

    DisksApi disksApi = new DisksRestApi(restClient);

    Task task = disksApi.delete("foo");
    assertEquals(task, responseTask);//  w w  w. jav a2 s.com
}

From source file:org.apache.solr.cloud.CreateRoutedAliasTest.java

@Test
public void testV1() throws Exception {
    final String aliasName = getTestName();
    final String baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
    Instant start = Instant.now().truncatedTo(ChronoUnit.HOURS); // mostly make sure no millis
    HttpGet get = new HttpGet(baseUrl + "/admin/collections?action=CREATEALIAS" + "&wt=xml" + "&name="
            + aliasName + "&router.field=evt_dt" + "&router.name=time" + "&router.start=" + start
            + "&router.interval=%2B30MINUTE" + "&create-collection.collection.configName=_default"
            + "&create-collection.router.field=foo_s" + "&create-collection.numShards=1"
            + "&create-collection.replicationFactor=2");
    assertSuccess(get);/*from www.ja v a 2  s  . com*/

    String initialCollectionName = TimeRoutedAlias.formatCollectionNameFromInstant(aliasName, start);
    assertCollectionExists(initialCollectionName);

    // Test created collection:
    final DocCollection coll = solrClient.getClusterStateProvider().getState(initialCollectionName).get();
    //TODO how do we assert the configSet ?
    assertEquals(CompositeIdRouter.class, coll.getRouter().getClass());
    assertEquals("foo_s", ((Map) coll.get("router")).get("field"));
    assertEquals(1, coll.getSlices().size()); // numShards
    assertEquals(2, coll.getReplicationFactor().intValue()); // num replicas
    //TODO SOLR-11877 assertEquals(2, coll.getStateFormat());

    // Test Alias metadata
    Aliases aliases = cluster.getSolrClient().getZkStateReader().getAliases();
    Map<String, String> collectionAliasMap = aliases.getCollectionAliasMap();
    String alias = collectionAliasMap.get(aliasName);
    assertNotNull(alias);
    Map<String, String> meta = aliases.getCollectionAliasProperties(aliasName);
    assertNotNull(meta);
    assertEquals("evt_dt", meta.get("router.field"));
    assertEquals("_default", meta.get("create-collection.collection.configName"));
    assertEquals(null, meta.get("start"));
}

From source file:no.ssb.jsonstat.v2.DatasetTest.java

@Test
public void testSerialize() throws Exception {

    DatasetBuilder builder = Dataset.create().withLabel("");
    builder.withSource("");
    builder.updatedAt(Instant.now());

    Dimension.Builder dimension = Dimension.create("year").withRole(Dimension.Roles.TIME)
            .withCategories(ImmutableSet.of("2003", "2004", "2005"));

    builder.withExtension(ImmutableMap.of("arbitrary_field", "arbitrary_value"));

    // TODO: addDimension("name") returning Dimension.Builder? Super fluent?
    // TODO: How to ensure valid data with the geo builder? Add the type first and extend builders?
    // TODO: express hierarchy with the builder? Check how ES did that with the query builders.
    // example: builder.withDimension(Dimension.create("location")
    //        .withGeoRole());

    // Supplier./*from  w w  w  . j a  v  a  2  s  .  c  om*/
    List<Number> collect = cartesianProduct(ImmutableList.of("2003", "2004", "2005"),
            ImmutableList.of("may", "june", "july"), ImmutableList.of("30", "31", "32"),
            ImmutableMap.of("A", "active population", "E", "employment", "U", "unemployment", "I",
                    "inactive population", "T", "population 15 years old and over").keySet().asList()).stream()
                            .map(dimensions -> dimensions.hashCode()).collect(Collectors.toList());

    // Some extension.
    List<Map<String, List<Instant>>> extension = Collections
            .singletonList(ImmutableMap.of("now", Collections.singletonList(Instant.now())));

    Dataset dataset = builder.withExtension(extension)
            .withDimensions(dimension,
                    Dimension.create("month").withRole(Dimension.Roles.TIME)
                            .withCategories(ImmutableSet.of("may", "june", "july")),
                    Dimension.create("week").withTimeRole().withLabels(ImmutableList.of("30", "31", "32")),
                    Dimension.create("population")
                            .withIndexedLabels(ImmutableMap.of("A", "active population", "E", "employment", "U",
                                    "unemployment", "I", "inactive population", "T",
                                    "population 15 years old and over")))
            .withValues(collect).build();

    String value = mapper.writeValueAsString(dataset);

    assertThat(value).isNotNull();

}

From source file:io.jwt.primer.resource.TokenResource.java

@POST
@Path("/v1/verify/{app}/{id}")
@ApiOperation(value = "Verify the token for a given user")
@ApiResponses({ @ApiResponse(code = 200, response = VerifyResponse.class, message = "Success"),
        @ApiResponse(code = 401, response = PrimerError.class, message = "Unauthorized"),
        @ApiResponse(code = 404, response = PrimerError.class, message = "Not Found"),
        @ApiResponse(code = 403, response = PrimerError.class, message = "Forbidden"),
        @ApiResponse(code = 412, response = PrimerError.class, message = "Expired"),
        @ApiResponse(code = 500, response = PrimerError.class, message = "Error") })
@Metered/*from  w w  w.j  a v  a  2  s . c o m*/
public VerifyResponse verify(@HeaderParam("X-Auth-Token") String token, @PathParam("app") String app,
        @PathParam("id") String id, @Valid ServiceUser user) throws PrimerException {
    try {
        DynamicToken dynamicToken = PrimerCommands.getDynamic(aerospikeConfig, app, id);
        if (dynamicToken == null)
            throw new PrimerException(Response.Status.NOT_FOUND.getStatusCode(), "PR001", "Not Found");
        if (!dynamicToken.isEnabled()) {
            throw new PrimerException(Response.Status.FORBIDDEN.getStatusCode(), "PR002", "Forbidden");
        }
        final long adjusted = Instant.ofEpochSecond(dynamicToken.getExpiresAt().getTime())
                .plusSeconds(jwtConfig.getClockSkew()).getEpochSecond();
        final long now = Instant.now().getEpochSecond();
        if (adjusted <= now) {
            throw new PrimerException(Response.Status.PRECONDITION_FAILED.getStatusCode(), "PR003", "Expired");
        }
        if (token.equals(dynamicToken.getToken()) && user.getId().equals(dynamicToken.getSubject())
                && user.getName().equals(dynamicToken.getName())
                && user.getRole().equals(dynamicToken.getRole())) {
            return VerifyResponse.builder().expiresAt(dynamicToken.getExpiresAt().getTime())
                    .token(dynamicToken.getToken()).userId(dynamicToken.getSubject()).build();
        } else {
            throw new PrimerException(Response.Status.UNAUTHORIZED.getStatusCode(), "PR004", "Unauthorized");
        }
    } catch (Exception e) {
        PrimerExceptionUtil.handleException(e);
        log.error("Execution Error verifying token", e);
        throw new PrimerException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "PR001", "Error");
    }
}

From source file:com.torchmind.stockpile.server.service.api.ProfileService.java

/**
 * Fetches a profile from the specified URL.
 *
 * @param url a url./*from w w w  . jav  a 2  s  . com*/
 * @return a profile
 *
 * @throws IOException when an error occurs.
 */
@Nonnull
private Profile fetchProfile(@Nonnull URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    switch (connection.getResponseCode()) {
    case 204:
        // Dear Mojang,
        // 204 No Content is not the correct status code to signify no results
        // Thanks for your time
        throw new NoSuchProfileException();
    case 429:
        throw new TooManyRequestsException("Rate limit exceeded");
    }

    try (InputStream inputStream = connection.getInputStream()) {
        JsonNode node = reader.readTree(inputStream);
        UUID identifier = (new MojangUUID(node.get("id").asText())).toUUID();

        // try to fetch a profile or create a new one if none is stored within the database
        final Profile profile;
        {
            Profile prof = this.profileRepository.findOne(identifier);

            if (prof == null) {
                profile = new Profile(identifier);
            } else {
                profile = prof;
                profile.setLastSeen(Instant.now());
            }
        }
        this.profileRepository.save(profile);

        // try to fetch a display name for the current profile and create a new one if none is stored in
        // the database
        DisplayName displayName = this.displayNameRepository
                .findOneByNameAndProfile(node.get("name").asText(), profile)
                .orElseGet(() -> new DisplayName(node.get("name").asText(), Instant.now(), profile));

        displayName.setLastSeen(Instant.now());
        this.displayNameRepository.save(displayName);

        // iterate over all properties and create/update their respective values
        node.get("properties").forEach((p) -> {
            String name = p.get("name").asText();

            ProfileProperty property = this.profilePropertyRepository.findByNameAndProfile(name, profile)
                    .orElseGet(() -> new ProfileProperty(profile, name, p.get("value").asText(),
                            (p.has("signature") ? p.get("signature").asText() : null)));

            property.setLastSeen(Instant.now());
            this.profilePropertyRepository.save(property);
            profile.addProperty(property);
        });

        return profile;
    }
}

From source file:org.noorganization.instalist.server.api.RecipeResourceTest.java

@Test
public void testPostRecipe() throws Exception {
    String url = "/groups/%d/recipes";
    RecipeInfo newRecipe = new RecipeInfo().withUUID(mRecipe.getUUID()).withName("recipe3");
    Instant preInsert = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request()
            .post(Entity.json(newRecipe));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").post(Entity.json(newRecipe));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newRecipe));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newRecipe));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mRecipe);/*w ww  . jav a 2s.com*/
    assertEquals("recipe1", mRecipe.getName());

    newRecipe.setUUID(UUID.randomUUID());
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newRecipe));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<Recipe> savedRecipeQuery = mManager
            .createQuery("select r from " + "Recipe r where r.group = :group and r.UUID = :uuid", Recipe.class);
    savedRecipeQuery.setParameter("group", mGroup);
    savedRecipeQuery.setParameter("uuid", UUID.fromString(newRecipe.getUUID()));
    List<Recipe> savedRecipes = savedRecipeQuery.getResultList();
    assertEquals(1, savedRecipes.size());
    assertEquals("recipe3", savedRecipes.get(0).getName());
    assertTrue(preInsert.isBefore(savedRecipes.get(0).getUpdated()));
}

From source file:org.ulyssis.ipp.ui.widgets.TeamPanel.java

private void updateCharts() {
    Instant now = Instant.now();
    Instant anHourAgo = now.minus(Duration.ofHours(1L));
    try (Connection connection = Database.createConnection(EnumSet.of(Database.ConnectionFlags.READ_ONLY))) {
        List<Event> events = Event.loadFrom(connection, anHourAgo);
        if (events.size() == 0) {
            LOG.warn("No events");
            return;
        }/*from ww w .  ja v a  2 s  .  c o m*/
        Snapshot snapshot = Snapshot.loadForEvent(connection, events.get(0)).get(); // If it's not there, this is a fatal error
        List<Optional<Instant>> eventTimes = new ArrayList<>();
        List<List<TagSeenEvent>> eventLists = new ArrayList<>();
        for (int i = 0; i < config.getNbReaders(); i++) {
            eventTimes.add(Optional.empty());
            eventLists.add(new ArrayList<>());
        }
        for (int i = 1; i < events.size(); ++i) {
            Event event = events.get(i);
            snapshot = event.apply(snapshot);
            if (event instanceof TagSeenEvent && !event.isRemoved()) { // TODO(Roel): Well, we can't actually remove it, right?
                final TagSeenEvent tagSeenEvent = (TagSeenEvent) event;
                Optional<Integer> teamNb = snapshot.getTeamTagMap().tagToTeam(tagSeenEvent.getTag());
                if (teamNb.isPresent() && teamNb.get().equals(team.getTeamNb())) {
                    // TODO(Roel): This hack is kind of dirty. In fact, all of this
                    //             code is kind of dirty.
                    if (eventTimes.get(tagSeenEvent.getReaderId()).isPresent()) {
                        if (Duration.between(eventTimes.get(tagSeenEvent.getReaderId()).get(), event.getTime())
                                .toMillis() <= 30_000) {
                            continue;
                        }
                    }
                    eventTimes.get(tagSeenEvent.getReaderId()).ifPresent(lastTime -> {
                        try {
                            eventLists.get(tagSeenEvent.getReaderId()).add(tagSeenEvent);
                        } catch (Exception e) {
                            LOG.error("Exception", e);
                        }
                    });
                    eventTimes.set(tagSeenEvent.getReaderId(), Optional.of(event.getTime()));
                }
            }
        }
        for (int i = 0; i < config.getNbReaders(); i++) {
            List<TagSeenEvent> eventList = eventLists.get(i);
            List<TagSeenEvent> shortenedEventList = new ArrayList<>();
            if (eventList.size() > 40) {
                for (int j = eventList.size() - 40; j < eventList.size(); j++) {
                    shortenedEventList.add(eventList.get(j));
                }
            } else {
                shortenedEventList = eventList;
            }
            itemModels.get(i).setEvents(anHourAgo, shortenedEventList);
        }
    } catch (SQLException e) {
        LOG.error("Couldn't fetch events", e);
    } catch (IOException e) {
        LOG.error("Error processing events", e);
    }
}

From source file:retsys.client.controller.DeliveryChallanController.java

@Override
Object buildRequestMsg() {/*from  ww  w . j ava 2s.c om*/
    DeliveryChallan dc = new DeliveryChallan();
    dc.setChallanDate(Date.from(Instant.now()));

    Project proj = new Project();
    proj.setId(getId(project.getText()));
    dc.setProject(proj);
    dc.setIsDelivery(true);
    dc.setOriginalDeliveryChallan(null);
    dc.setDeliveryMode(deliverymode.getText());
    dc.setConcernPerson(concernperson.getText());

    Iterator<DCItem> items = dcDetail.getItems().iterator();
    List<DeliveryChallanDetail> dcDetails = new ArrayList<>();

    while (items.hasNext()) {
        DCItem dcItem = items.next();
        DeliveryChallanDetail dcDetail = new DeliveryChallanDetail();

        Item item = new Item();
        //item.setId(getId(String.valueOf(dcItem.getId().get())));
        item.setId(dcItem.getId().get());
        dcDetail.setItem(item);
        dcDetail.setQuantity(dcItem.getQuantity().get());
        dcDetail.setUnits(dcItem.getUnits().get());
        dcDetail.setAmount(dcItem.getAmount().get());

        dcDetails.add(dcDetail);
    }

    dc.setDeliveryChallanDetail(dcDetails);

    return dc;
}