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:org.lendingclub.mercator.bind.BindScanner.java

private void scanZones() {

    Instant startTime = Instant.now();

    List<String> zones = getBindClient().getZones();

    zones.forEach(zone -> {/*w ww .ja v  a2s  . c o m*/

        String cypher = "MERGE (m:BindHostedZone {zoneName:{zone}}) "
                + "ON CREATE SET m.createTs = timestamp(), m.updateTs=timestamp() "
                + "ON MATCH SET  m.updateTs=timestamp();";
        getProjector().getNeoRxClient().execCypher(cypher, "zone", zone);
    });
    Instant endTime = Instant.now();
    logger.info(" Took {} secs to project Bind Zone information to Neo4j",
            Duration.between(startTime, endTime).getSeconds());

}

From source file:com.netflix.genie.web.controllers.DtoConverters.java

/**
 * Convert a V3 Application DTO to a V4 Application DTO.
 *
 * @param v3Application The V3 application to convert
 * @return The V4 application representation of the data in the V3 DTO
 *//*w  w w . jav a  2s.  c om*/
public static Application toV4Application(final com.netflix.genie.common.dto.Application v3Application) {
    final ApplicationMetadata.Builder metadataBuilder = new ApplicationMetadata.Builder(v3Application.getName(),
            v3Application.getUser(), v3Application.getVersion(), v3Application.getStatus())
                    .withTags(toV4Tags(v3Application.getTags()));

    v3Application.getMetadata().ifPresent(metadataBuilder::withMetadata);
    v3Application.getType().ifPresent(metadataBuilder::withType);
    v3Application.getDescription().ifPresent(metadataBuilder::withDescription);

    return new Application(v3Application.getId().orElseThrow(IllegalArgumentException::new),
            v3Application.getCreated().orElse(Instant.now()), v3Application.getUpdated().orElse(Instant.now()),
            new ExecutionEnvironment(v3Application.getConfigs(), v3Application.getDependencies(),
                    v3Application.getSetupFile().orElse(null)),
            metadataBuilder.build());
}

From source file:com.onyxscheduler.domain.SchedulerIT.java

private Instant buildPastDate() {
    return Instant.now().minus(PAST_DATE_MINUTES, ChronoUnit.MINUTES);
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepositoryTest.java

@Test
public void updateRegistrationTest() throws URISyntaxException, RegistrationPersistenceException {
    RegisterContext registerContext = createRegisterContextTemperature();
    registerContext.setRegistrationId("12345");
    Registration registration = new Registration(Instant.now().plus(1, ChronoUnit.DAYS), registerContext);
    registrationsRepository.saveRegistration(registration);
    Map<String, Registration> registrations = registrationsRepository.getAllRegistrations();
    Assert.assertEquals(1, registrations.size());
    Assert.assertEquals("PT10S", registrations.get("12345").getRegisterContext().getDuration());
    registerContext.setDuration("PT1D");
    registration.setExpirationDate(Instant.now().plus(1, ChronoUnit.DAYS));
    registrationsRepository.updateRegistration(registration);
    registrations = registrationsRepository.getAllRegistrations();
    Assert.assertEquals(1, registrations.size());
    Assert.assertEquals("PT1D", registrations.get("12345").getRegisterContext().getDuration());
    Assert.assertEquals(registration.getExpirationDate(), registrations.get("12345").getExpirationDate());
}

From source file:com.netflix.genie.web.util.UnixProcessCheckerTest.java

/**
 * Make sure if the timeout has been exceeded then an exception is thrown indicating the process should be killed.
 *
 * @throws GenieTimeoutException on timeout
 * @throws IOException           on any other error
 *///from   w w  w.ja  v  a  2s .  co  m
@Test(expected = GenieTimeoutException.class)
public void canCheckProcessTimeout() throws GenieTimeoutException, IOException {
    final Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
    new UnixProcessChecker(PID, this.executor, yesterday, true).checkProcess();
}

From source file:cn.edu.zjnu.acm.judge.user.ResetPasswordController.java

@PostMapping("/resetPassword")
public void doPost(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "action", required = false) String action,
        @RequestParam(value = "verify", required = false) String verify,
        @RequestParam(value = "username", required = false) String username, Locale locale) throws IOException {
    response.setContentType("text/javascript;charset=UTF-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);
    String word = null;//from  w  ww  .  j  a v a  2s .  c o  m
    if (session != null) {
        word = (String) session.getAttribute("word");
        session.removeAttribute("word");
    }
    if (word == null || !word.equalsIgnoreCase(verify)) {
        out.print("alert('??');");
        return;
    }

    User user = userMapper.findOne(username);
    if (user == null) {
        out.print("alert('?');");
        return;
    }
    String email = user.getEmail();
    if (email == null || !email.toLowerCase().matches(ValueCheck.EMAIL_PATTERN)) {
        out.print(
                "alert('???????');");
        return;
    }
    try {
        String vc = user.getVcode();
        if (vc == null || user.getExpireTime() != null && user.getExpireTime().compareTo(Instant.now()) < 0) {
            vc = Utility.getRandomString(16);
        }
        user = user.toBuilder().vcode(vc).expireTime(Instant.now().plus(1, ChronoUnit.HOURS)).build();
        userMapper.update(user);
        String url = getPath(request, "/resetPassword.html?vc=", vc + "&u=", user.getId());
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("url", url);
        map.put("ojName", judgeConfiguration.getContextPath() + " OJ");

        String content = templateEngine.process("users/password", new Context(locale, map));
        String title = templateEngine.process("users/passwordTitle", new Context(locale, map));

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo(email);
        helper.setSubject(title);
        helper.setText(content, true);
        helper.setFrom(javaMailSender.getUsername());

        javaMailSender.send(mimeMessage);
    } catch (MailException | MessagingException ex) {
        log.error("", ex);
        out.print("alert('?????')");
        return;
    }
    out.print("alert('???" + user.getEmail() + "??');");
}

From source file:co.runrightfast.component.events.impl.ComponentEventImpl.java

public ComponentEventImpl(@NonNull final ComponentId componentId, @NonNull final Event<DATA> event,
        @NonNull final DATA data, @NonNull final Throwable exception) {
    this(componentId, UUID.randomUUID(), Instant.now(), AppUtils.JVM_ID, event, Optional.of(data),
            Optional.of(exception), Optional.empty());
}

From source file:com.joyent.manta.client.multipart.JobsMultipartManagerIT.java

public void canUploadSmallMultipartString() throws IOException {
    String[] parts = new String[] { "Hello ", "world ", "Joyent", "!" };

    StringBuilder combined = new StringBuilder();
    for (String p : parts) {
        combined.append(p);//from w  w w.  ja  v  a 2 s. co  m
    }

    final String name = uploadName("can-upload-small-multipart-string");
    final String path = testPathPrefix + name;

    final JobsMultipartUpload upload = multipart.initiateUpload(path);
    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);

        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    Instant start = Instant.now();
    multipart.complete(upload, uploadedParts);

    multipart.waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
        fail("Completion operation didn't succeed within timeout");
        return null;
    });
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);

    assertEquals(status, MantaMultipartStatus.COMPLETED);

    assertEquals(mantaClient.getAsString(path), combined.toString(),
            "Manta combined string doesn't match expectation: " + multipart.findJob(upload));

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Concatenating {} parts took {} seconds", parts.length, totalCompletionTime.toMillis() / 1000);
}

From source file:de.arraying.arraybot.manager.ScriptManager.java

/**
 * Executes the script.//  w  ww  .j av  a  2  s  . com
 * @param scriptUrl The script URL.
 * @param environment The command environment.
 * @param error The error consumer.
 * @throws IOException If an exception occurs parsing the code.
 */
public void executeScript(String scriptUrl, CommandEnvironment environment, Consumer<Exception> error)
        throws Exception {
    PrimeSourceProvider provider = Prime.Util.getProvider(PRIME_TEST, scriptUrl);
    if (provider == null || provider instanceof StandardProvider) {
        invalidURL(environment.getChannel());
        return;
    }
    String code;
    try {
        code = IOUtils.toString(new URL(scriptUrl), Charset.forName("utf-8"));
    } catch (MalformedURLException exception) {
        invalidURL(environment.getChannel());
        return;
    }
    Prime.Builder primeBuilder = new Prime.Builder()
            .withVariable("guild", new ScriptGuild(environment, environment.getGuild()))
            .withVariable("channel", new ScriptTextChannel(environment, environment.getChannel()))
            .withVariable("user", new ScriptUser(environment, environment.getMember()))
            .withVariable("message", new ScriptMessage(environment, environment.getMessage()))
            .withVariable("embeds", new EmbedMethods())
            .withVariable("commands", new CommandMethods(environment))
            .withVariable("manager", new ManagerMethods(environment))
            .withVariable("storage", new StorageMethods(environment)).withVariable("time", Instant.now())
            .withBlacklistedBindings(Prime.DEFAULT_BINDINGS).withMaxRuntime(10);
    Arrays.stream(PROVIDERS).forEach(primeBuilder::withProvider);
    Prime prime = primeBuilder.build(code);
    prime.evaluate(error);
}

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

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

    ClusterApi clusterApi = new ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*from w  w w  . j  a  v  a 2  s  .  c om*/
        public void onSuccess(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));
}