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:ws.salient.session.Sessions.java

public CompletableFuture execute(List<Command> commands) {
    Instant now = Instant.now();
    CompletableFuture result;/* w  ww.ja  v a  2  s  .com*/
    try {
        commands.stream().filter(command -> command instanceof ModifyProfile).forEach((command) -> {
            log.info(toJson(command));
            profiles.modified(command.getAccountId());
        });

        commands.stream().filter(command -> command.getKnowledgeBaseId() != null).forEach((command) -> {
            String knowledgeBaseId = command.getKnowledgeBaseId();
            Map<String, String> aliases = profiles.getAliases(command.getAccountId(), command.getProfiles());
            if (aliases.containsKey(knowledgeBaseId)) {
                knowledgeBaseId = aliases.get(knowledgeBaseId);
            }
            command.setKnowledgeBaseId(knowledgeBaseId);
        });

        commands.forEach((command) -> {
            command.setTimestamp(now);
        });

        // Load knowledge bases in parallel
        List<CompletableFuture<KnowledgeBase>> knowledgeBases = commands.stream()
                .filter(command -> command.getKnowledgeBaseId() != null)
                .collect(Collectors.groupingBy((command) -> {
                    // Group commands by knowledgeBaseId
                    return command.getKnowledgeBaseId();
                })).values().stream().map((kbaseCommands) -> {
                    return CompletableFuture.supplyAsync(() -> {
                        // Load each knowledge base
                        return repository.getKnowledgeBase(kbaseCommands.get(0).getKnowledgeBaseId());
                    });
                }).collect(Collectors.toList());
        CompletableFuture.allOf(knowledgeBases.toArray(new CompletableFuture[knowledgeBases.size()])).get();

        // Load sessions in parallel
        List<CompletableFuture<Session>> sessions = commands.stream()
                .filter(command -> command.getSessionId() != null).collect(Collectors.groupingBy((command) -> {
                    // Group commands by sessionId
                    return command.getSessionId();
                })).values().stream().map((sessionCommands) -> {
                    return CompletableFuture.supplyAsync(() -> {
                        // Load each session
                        return getSession(sessionCommands.get(0));
                    });
                }).collect(Collectors.toList());
        CompletableFuture.allOf(sessions.toArray(new CompletableFuture[sessions.size()])).get();

        result = CompletableFuture.runAsync(() -> {
            int requestIndex = 0;
            for (Command command : commands) {
                if (command.getSessionId() != null) {
                    command.setTimestamp(now);
                    Session session = getSession(command);
                    session.accept(command);
                    store.put(session, command, requestIndex);
                    requestIndex++;
                }
            }
        }, commandExecutor).thenRun(() -> {
            this.sessions.forEach((id, session) -> {
                if (session.expired(now)) {
                    if (session.getProcessCount() == 0) {
                        int oldcount = sessions.size();
                        sessions.remove(id);
                        session.dispose();
                        log.info("Session count was " + oldcount + " now " + sessions.size());
                    }
                }
            });
        });
    } catch (InterruptedException | ExecutionException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
    return result;
}

From source file:info.losd.galen.scheduler.Scheduler.java

@Scheduled(fixedDelay = 500)
public void processTasks() {
    List<Task> tasks = repo.findTasksToBeRun();
    LOG.debug("There are {} tasks waiting", tasks.size());

    tasks.forEach(task -> {//  w w w .  j  a v  a 2  s . c o  m
        LOG.debug("processing: {}", task.toString());

        Map<String, String> headers = new HashMap<>();
        task.getHeaders().forEach(header -> {
            headers.put(header.getHeader(), header.getValue());
        });

        SchedulerHealthcheck healthcheckRequest = new SchedulerHealthcheck();
        healthcheckRequest.setHeaders(headers);
        healthcheckRequest.setMethod(task.getMethod());
        healthcheckRequest.setTag(task.getName());
        healthcheckRequest.setUrl(task.getUrl());

        try {
            String body = mapper.writeValueAsString(healthcheckRequest);

            HttpResponse response = Request.Post("http://127.0.0.1:8080/healthchecks")
                    .bodyString(body, ContentType.APPLICATION_JSON).execute().returnResponse();

            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                task.setLastUpdated(Instant.now());
                repo.save(task);
                LOG.debug("processed:  {}", task.getId());
            } else {
                LOG.error("task: {}, status code: {}, reason: {}\nbody: {}", task.getId(),
                        status.getStatusCode(), status.getReasonPhrase(),
                        IOUtils.toString(response.getEntity().getContent()));
            }
        } catch (Exception e) {
            LOG.error("Problem processing task {}", task.getId(), e);
        }
    });
}

From source file:mcp.tools.nmap.parser.NmapXmlParser.java

public static void parse(File xmlResultsFile, String scanDescription, String commandLine) {
    Pattern endTimePattern = Pattern.compile("<runstats><finished time=\"(\\d+)");
    String xmlResults;/*from w w  w .  j  a va 2s.  c o m*/
    try {
        xmlResults = FileUtils.readFileToString(xmlResultsFile);
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }

    Matcher m = endTimePattern.matcher(xmlResults);
    Instant scanTime = null;
    if (m.find()) {
        int t;
        try {
            t = Integer.parseInt(m.group(1));
            scanTime = Instant.ofEpochSecond(t);
        } catch (NumberFormatException e) {

        }
    }

    if (scanTime == null) {
        logger.debug("Failed to find scan completion time in nmap results. Using current time.");
        scanTime = Instant.now();
    }
    String path;
    try {
        path = xmlResultsFile.getCanonicalPath();
    } catch (IOException e1) {
        logger.debug("Why did the canonical path fail?");
        path = xmlResultsFile.getAbsolutePath();
    }

    NmapScanSource source = new NmapScanSourceImpl(path, scanDescription, commandLine);

    NMapXmlHandler nmxh = new NMapXmlHandler(scanTime, source);
    SAXParserFactory spf = SAXParserFactory.newInstance();

    SAXParser sp;
    try {
        sp = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    } catch (SAXException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    }

    try {
        sp.parse(xmlResultsFile, nmxh);
    } catch (SAXException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }
}

From source file:info.losd.galen.scheduler.repository.TestTaskRepo.java

@Test
public void test_it_can_get_a_list_of_tasks_to_be_run() {
    List<Header> headers = Arrays.asList(new Header("h1", "v1"), new Header("h2", "v2"));
    String url = "http://localhost:8080/test";
    String method = HttpMethod.GET.toString();

    repo.save(new Task("test_task", 10, Instant.now().minusSeconds(10), url, method, Collections.emptyList()));
    repo.save(new Task("test_task", 10, Instant.now().minusSeconds(10), url, method, Collections.emptyList()));
    repo.save(new Task("test_task", 10, Instant.now().minusSeconds(10), url, method, headers));
    repo.save(new Task("test_task", 10, Instant.now().plusSeconds(11), url, method, Collections.emptyList()));
    repo.save(new Task("test_task", 10, Instant.now().plusSeconds(12), url, method, Collections.emptyList()));

    List<Task> result = repo.findTasksToBeRun();

    assertThat(result, IsCollectionWithSize.hasSize(3));

    result.forEach(res -> {// ww  w  .j  a  v  a  2  s. c  o m
        LOG.info("{} has {} headers", res.toString(), res.getHeaders().size());
    });
}

From source file:com.pepaproch.gtswsdl.client.RateLimitTest.java

private synchronized void addTask(AtomicInteger cc, ScheduledExecutorService schelduler, RateLimit rate,
        Instant[] end) {//from  ww w  . ja  v  a  2  s  .  c  o  m

    Callable<Integer> callable = (Callable<Integer>) () -> {

        return cc.get();
    };
    ListenableFutureTask request = new ListenableFutureTask(callable);

    schelduler.schedule(() -> {
        FutureTask<?> schelduledTask = request;
        if (!request.isCancelled() && !request.isDone()) {
            schelduledTask.run();
        }

    }, rate.consumeSlot(), TimeUnit.MILLISECONDS);

    request.addCallback(new ListenableFutureCallback<Integer>() {

        @Override
        public void onSuccess(Integer result) {
            cc.incrementAndGet();
            end[0] = Instant.now();
            System.out.println("FINISHEDLISTENBALE: " + result + end[0].toString());
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("FAILURE");
        }
    });

}

From source file:eu.hansolo.tilesfx.tools.Location.java

public Location(final double LATITUDE, final double LONGITUDE, final String NAME, final TileColor COLOR) {
    this(LATITUDE, LONGITUDE, 0, Instant.now(), NAME, "", COLOR);
}

From source file:io.pivotal.strepsirrhini.chaosloris.data.EventRepositoryTest.java

@Test
public void findByExecutedAtBefore() throws ExecutionException, InterruptedException {
    Schedule schedule = new Schedule("test-schedule", "test-name");
    this.scheduleRepository.saveAndFlush(schedule);

    Application application = new Application(UUID.randomUUID());
    this.applicationRepository.saveAndFlush(application);

    Chaos chaos = new Chaos(application, 0.1, schedule);
    this.chaosRepository.saveAndFlush(chaos);

    Instant now = Instant.now();

    Event event1 = new Event(chaos, now.minus(1, DAYS), Collections.emptyList(), Integer.MIN_VALUE);
    this.eventRepository.saveAndFlush(event1);

    Event event2 = new Event(chaos, now, Collections.emptyList(), Integer.MIN_VALUE);
    this.eventRepository.saveAndFlush(event2);

    Event event3 = new Event(chaos, now.plus(1, DAYS), Collections.emptyList(), Integer.MIN_VALUE);
    this.eventRepository.saveAndFlush(event3);

    List<Event> events = this.eventRepository.findByExecutedAtBefore(now.minus(1, HOURS));
    assertThat(events).containsExactly(event1);
}

From source file:org.createnet.raptor.models.auth.Token.java

public Instant getExpiresInstant() {
    if (expires == null)
        return null;
    return Instant.now().plusSeconds(expires);
}

From source file:org.elasticstore.server.service.impl.ElasticSearchServiceImpl.java

@Override
public void saveOrUpdateItem(Item item) throws ElasticStoreException {
    log.debug("indexing item " + item.getId());
    // set created date for new items
    if (!exists(item.getId())) {
        item.setCreated(Instant.now());
    }/*from w w w  .  j av a2  s .  c o  m*/
    // set the last modifed date
    item.setLastModified(Instant.now());

    // store the item in ElasticSearch
    try {
        final IndexResponse resp = client.prepareIndex(INDEX_ITEMS, INDEX_ITEM_TYPE, item.getId())
                .setSource(mapper.writeValueAsBytes(item)).execute().actionGet();
    } catch (IOException e) {
        throw new ElasticStoreException(e);
    }
    refreshIndex(INDEX_ITEMS);
}

From source file:ai.susi.server.Authentication.java

/**
 * Check if the authentication is still valid
 * @return true if the Authentication is still valid or does not have an expire time set. false otherwise
 *//*from  w w  w. j  a v a  2  s  .  com*/
public boolean checkExpireTime() {
    return !this.json.has("expires_on") || this.json.getLong("expires_on") > Instant.now().getEpochSecond();
}