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.persistence.RegistrationsRepositoryTest.java

@Test
public void getRegistrationTest()
        throws URISyntaxException, RegistrationPersistenceException, EmptyResultDataAccessException {
    RegisterContext registerContext = createRegisterContextTemperature();
    registerContext.setRegistrationId("12345");
    Instant expirationDate = Instant.now().plus(1, ChronoUnit.DAYS);
    Registration registration = new Registration(expirationDate, registerContext);
    registrationsRepository.saveRegistration(registration);
    Registration foundRegistration = registrationsRepository.getRegistration("12345");
    Assert.assertNotNull(foundRegistration);
    Assert.assertEquals(expirationDate, foundRegistration.getExpirationDate());
}

From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollectionIT.java

private void loadRecordsFrom(String... jsons) throws SQLException, IOException {
    Connection connection = pg.getConnection();
    connection.prepareStatement("SET TIMEZONE TO 'UTC'").execute();
    try (PreparedStatement rec = connection
            .prepareStatement("INSERT INTO oairecords (pid, changed, deleted) VALUES(?, ?::timestamp, ?)");
            PreparedStatement recSet = connection
                    .prepareStatement("INSERT INTO oairecordsets (pid, setSpec) VALUES(?, ?)")) {

        for (String json : jsons) {
            InputStream is = getClass().getClassLoader().getResourceAsStream(json);
            if (is == null) {
                throw new RuntimeException("Cannot find: " + json);
            }//from   ww w. j a  v  a 2s .c  o m
            ObjectMapper objectMapper = new ObjectMapper();
            List<ObjectNode> array = objectMapper.readValue(is, List.class);
            for (Object object : array) {
                Map<String, Object> obj = (Map<String, Object>) object;
                rec.setString(1, (String) obj.get("pid"));
                rec.setString(2, (String) obj.getOrDefault("changed",
                        DateTimeFormatter.ISO_INSTANT.format(Instant.now().atZone(ZoneId.systemDefault()))));
                rec.setBoolean(3, (boolean) obj.getOrDefault("deleted", false));
                rec.executeUpdate();
                recSet.setString(1, (String) obj.get("pid"));
                List<Object> sets = (List<Object>) obj.get("sets");

                for (Object set : sets) {
                    recSet.setString(2, (String) set);
                    recSet.executeUpdate();
                }
            }
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:com.joyent.manta.client.crypto.AbstractAesCipherDetails.java

/**
 * <p>Gets the current instance of {@link SecureRandom} and periodically adds
 * new random material to the seed.</p>
 * @see <a href="https://www.cigital.com/blog/proper-use-of-javas-securerandom/">Proper Use Of Java SecureRandom</a>
 *
 * @return entropy source//from   ww  w .  j av  a  2s.com
 */
protected SecureRandom getSecureRandom() {
    Instant nextRefreshTimestamp = seedLastRefreshedTimestamp.plus(SEED_REFRESH_INTERVAL);
    if (seedLastRefreshedTimestamp.isAfter(nextRefreshTimestamp)) {
        this.random.setSeed(this.random.generateSeed(32));
        seedLastRefreshedTimestamp = Instant.now();
    }

    return this.random;
}

From source file:ai.grakn.engine.tasks.manager.multiqueue.Scheduler.java

/**
 * Schedule a task to be submitted to the work queue when it is supposed to be run
 * @param state state of the task/*  w w  w.j  a v  a 2  s.c  om*/
 */
private void scheduleTask(TaskState state) {
    TaskSchedule schedule = state.schedule();
    long delay = Duration.between(Instant.now(), schedule.runAt()).toMillis();

    Runnable submit = () -> {
        markAsScheduled(state);
        sendToWorkQueue(state);
    };

    Optional<Duration> interval = schedule.interval();
    if (interval.isPresent()) {
        schedulingService.scheduleAtFixedRate(submit, delay, interval.get().toMillis(), MILLISECONDS);
    } else {
        schedulingService.schedule(submit, delay, MILLISECONDS);
    }
}

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

/**
 * Updates the recipe./*from  ww w .j  a  v a2 s. c om*/
 * @param _groupId The id of the group containing the recipe to change.
 * @param _recipeUUID The uuid of the recipe identifying it in the group.
 * @param _entity Data to change.
 */
@PUT
@TokenSecured
@Path("{recipeuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putRecipe(@PathParam("groupid") int _groupId, @PathParam("recipeuuid") String _recipeUUID,
        RecipeInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_recipeUUID))
            || (_entity.getName() != null && _entity.getName().length() == 0)
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    try {
        toUpdate = UUID.fromString(_recipeUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IRecipeController recipeController = ControllerFactory.getRecipeController(manager);
    try {
        recipeController.update(_groupId, toUpdate, _entity.getName(), updated);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The recipe was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The recipe has been " + "deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved recipe."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:com.perry.infrastructure.call.CallDaoServiceImpl.java

@Override
public Call edit(Call call) {
    String sql = "UPDATE calls set customer_first_name = :customerFirstName, \r\n" + //
            "       customer_last_name = :customerLastName, \r\n" + //
            "       pick_up_location = :pickUpLocation, \r\n" + //
            "       drop_off_location =:dropOffLocation, \r\n" + //
            "       customer_vehicle_year=:customerVehicleYear, \r\n" + //
            "       customer_vehicle_make=:customerVehicleMake, \r\n" + //
            "       customer_vehicle_model= :customerVehicleModel, \r\n" + //
            "       customer_vehicle_color=:customerVehicleColor, \r\n" + //
            "       customer_vehicle_license_plate_number=:customerVehicleLiscensePlateNumber, \r\n" + //
            "       customer_phone_number=:customerPhoneNumber, \r\n" + //
            "       customer_vehicle_key_location=:customerVehicleKeyLocation, \r\n" + //
            "       customer_call_type=:customerCallType, \r\n" + //
            "       customer_payment_information=:customerPaymentInformation, \r\n" + //
            "       insert_by=:insertBy, \r\n" + //
            "       update_by=:updateBy, \r\n" + //
            "       update_time=:updateTime WHERE call_id = :callId";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("customerFirstName", call.getCustomer().getFirstName());
    params.addValue("customerLastName", call.getCustomer().getLastName());
    params.addValue("pickUpLocation", call.getPickUpLocation());
    params.addValue("dropOffLocation", call.getDropOffLocation());
    params.addValue("customerVehicleYear", call.getCustomer().getVehicle().getYear());
    params.addValue("customerVehicleMake", call.getCustomer().getVehicle().getMake());
    params.addValue("customerVehicleModel", call.getCustomer().getVehicle().getMake());
    params.addValue("customerVehicleColor", call.getCustomer().getVehicle().getColor());
    params.addValue("customerVehicleLiscensePlateNumber",
            call.getCustomer().getVehicle().getLicensePlateNumber());
    params.addValue("customerPhoneNumber", call.getCustomer().getPhoneNumber());
    params.addValue("customerVehicleKeyLocation",
            call.getCustomer().getVehicle().getKeyLocationType().getValue());
    params.addValue("customerCallType", call.getCallType().getValue());
    params.addValue("customerPaymentInformation", call.getCustomer().getVehicle().getMake());
    params.addValue("insertBy", 1);
    params.addValue("updateBy", 1);
    params.addValue("updateTime", Instant.now().getEpochSecond());
    params.addValue("callId", call.getId());

    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    namedParameterJdbcTemplate.update(sql, params, keyHolder);

    // update call with primary key returned from DB
    call.setId((Long) keyHolder.getKeys().get("call_id"));
    return call;/*from   w w  w  . j a v  a2s .c  om*/
}

From source file:io.pivotal.strepsirrhini.chaosloris.docs.ChaosDocumentation.java

@Test
public void chaosRead() throws Exception {
    Application application = new Application(UUID.randomUUID());
    application.setId(1L);//from  w w w . ja va  2  s.c om

    Schedule schedule = new Schedule("0 0 * * * *", "hourly");
    schedule.setId(2L);

    Chaos chaos = new Chaos(application, 0.1, schedule);
    chaos.setId(3L);

    Event event = new Event(chaos, Instant.now(), Collections.singletonList(3), 10);
    event.setId(4L);

    when(this.chaosRepository.getOne(chaos.getId())).thenReturn(chaos);

    when(this.eventRepository.findByChaos(chaos)).thenReturn(Collections.singletonList(event));

    this.mockMvc.perform(get("/chaoses/{id}", chaos.getId()).accept(HAL_JSON)).andDo(document(
            pathParameters(parameterWithName("id").description("The chaos' id")),
            responseFields(fieldWithPath("probability")
                    .description("The probability of an instance of the application experiencing chaos")),
            links(linkWithRel("application").description("The [Application](#applications) to create chaos on"),
                    linkWithRel("event").description("The [Events](#events) performed by this chaos"),
                    linkWithRel("schedule").description("The [Schedule](#schedules) to create chaos on"))));
}

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

@Test
public void testPostTag() throws Exception {
    String url = "/groups/%d/tags";
    TagInfo newTag = new TagInfo().withUUID(mTag.getUUID()).withName("tag3");
    Instant preInsert = Instant.now();

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

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

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

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newTag));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mTag);//w ww.  ja  va2s .  c  o  m
    assertEquals("tag1", mTag.getName());

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

From source file:com.searchcode.app.jobs.repository.IndexBaseRepoJob.java

/**
 * Determines if anything has changed or if the last index operation faild and if so
 * triggers the index process.//from w  w  w .  jav  a 2  s. c om
 */
public void triggerIndex(RepoResult repoResult, String repoName, String repoRemoteLocation,
        String repoLocations, String repoGitLocation, boolean existingRepo,
        RepositoryChanged repositoryChanged) {
    // If the last index was not sucessful, then trigger full index
    boolean indexSuccess = this.checkIndexSucess(repoGitLocation);

    if (repositoryChanged.isChanged() || indexSuccess == false) {
        Singleton.getLogger().info("Update found indexing " + repoRemoteLocation);
        this.updateIndex(repoName, repoLocations, repoRemoteLocation, existingRepo, repositoryChanged);

        int runningTime = Singleton.getHelpers().getCurrentTimeSeconds()
                - Singleton.getRunningIndexRepoJobs().get(repoResult.getName()).startTime;
        repoResult.getData().averageIndexTimeSeconds = (repoResult.getData().averageIndexTimeSeconds
                + runningTime) / 2;
        repoResult.getData().indexStatus = "success";
        repoResult.getData().jobRunTime = Instant.now();
        Singleton.getRepo().saveRepo(repoResult);
    }
}

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

@Test
public void testPutCategory() throws Exception {
    final String url = "/groups/%d/categories/%s";
    Response wrongTokenResponse = target(String.format(url, mGroup.getId(), mCategory.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongToken")
            .put(Entity.json(new CategoryInfo().withName("dev111")));
    assertEquals(401, wrongTokenResponse.getStatus());

    Response wrongGroupResponse = target(
            String.format(url, mNotAccessibleGroup.getId(), mCategory.getUUID().toString())).request()
                    .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken)
                    .put(Entity.json(new CategoryInfo().withName("dev111")));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response wrongCatResponse = target(
            String.format(url, mGroup.getId(), mNotAccessibleCategory.getUUID().toString())).request()
                    .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken)
                    .put(Entity.json(new CategoryInfo().withName("dev111")));
    assertEquals(404, wrongCatResponse.getStatus());

    Response invalidCatResponse = target(String.format(url, mGroup.getId(), mCategory.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(new CategoryInfo()
                    .withUUID(mNotAccessibleCategory.getUUID().toString()).withName("dev111")));
    assertEquals(400, invalidCatResponse.getStatus());
    mManager.refresh(mNotAccessibleCategory);
    mManager.refresh(mCategory);/*from w  w w . j av a  2  s  .c  o  m*/
    assertEquals("cat1", mCategory.getName());
    assertEquals("cat2", mNotAccessibleCategory.getName());

    Instant beforeChange = Instant.now();
    Thread.sleep(200);
    Response validCatResponse = target(String.format(url, mGroup.getId(), mCategory.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken)
            .put(Entity.json(new CategoryInfo().withName("dev111")));
    assertEquals(200, validCatResponse.getStatus());
    mManager.refresh(mCategory);
    assertEquals("dev111", mCategory.getName());
    assertTrue(beforeChange.isBefore(mCategory.getUpdated()));

    Response conflictCatResponse = target(String.format(url, mGroup.getId(), mCategory.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken)
            .put(Entity.json(new CategoryInfo().withName("cat1").withLastChanged(Date.from(beforeChange))));
    assertEquals(409, conflictCatResponse.getStatus());
    mManager.refresh(mCategory);
    assertEquals("dev111", mCategory.getName());
    assertTrue(beforeChange.isBefore(mCategory.getUpdated()));
}