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.noorganization.instalist.server.api.CategoriesResourceTest.java

@Before
public void setUp() throws Exception {
    super.setUp();

    CommonData data = new CommonData();

    mManager = DatabaseHelper.getInstance().getManager();
    mManager.getTransaction().begin();//from  w  ww . j  a v  a  2  s.c  o m
    mGroup = new DeviceGroup();
    Instant now = Instant.now();
    Device aDev = new Device().withAuthorized(true).withGroup(mGroup).withSecret(data.mEncryptedSecret)
            .withName("testDev");
    mCategory = new Category().withGroup(mGroup).withName("cat1").withUUID(UUID.randomUUID()).withUpdated(now);
    mDeletedCategory = new DeletedObject().withGroup(mGroup).withType(DeletedObject.Type.CATEGORY)
            .withUUID(UUID.randomUUID()).withUpdated(now);
    mNotAccessibleGroup = new DeviceGroup().withUpdated(Date.from(now));
    mNotAccessibleCategory = new Category().withGroup(mNotAccessibleGroup).withName("cat2")
            .withUUID(UUID.randomUUID()).withUpdated(now);

    mManager.persist(mGroup);
    mManager.persist(aDev);
    mManager.persist(mCategory);
    mManager.persist(mDeletedCategory);
    mManager.persist(mNotAccessibleGroup);
    mManager.persist(mNotAccessibleCategory);
    mManager.flush();
    mManager.getTransaction().commit();
    mManager.refresh(mGroup);
    mManager.refresh(aDev);
    mManager.refresh(mCategory);
    mManager.refresh(mDeletedCategory);
    mManager.refresh(mNotAccessibleGroup);
    mManager.refresh(mNotAccessibleCategory);

    mToken = ControllerFactory.getAuthController().getTokenByHttpAuth(mManager, aDev.getId(), data.mSecret);
    assertNotNull(mToken);
}

From source file:com.netflix.genie.web.tasks.job.JobMonitorTest.java

/**
 * Setup for the tests./*from  w  w  w. j  a  v a2s .co m*/
 */
@Before
public void setup() {
    final Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
    this.jobExecution = new JobExecution.Builder(UUID.randomUUID().toString()).withProcessId(3808)
            .withCheckDelay(DELAY).withTimeout(tomorrow).withId(UUID.randomUUID().toString()).build();
    this.executor = Mockito.mock(Executor.class);
    this.genieEventBus = Mockito.mock(GenieEventBus.class);
    this.successfulCheckRate = Mockito.mock(Counter.class);
    this.timeoutRate = Mockito.mock(Counter.class);
    this.finishedRate = Mockito.mock(Counter.class);
    this.unsuccessfulCheckRate = Mockito.mock(Counter.class);
    this.stdOutTooLarge = Mockito.mock(Counter.class);
    this.stdErrTooLarge = Mockito.mock(Counter.class);
    this.registry = Mockito.mock(MeterRegistry.class);
    this.stdOut = Mockito.mock(File.class);
    this.stdErr = Mockito.mock(File.class);
    this.processChecker = Mockito.mock(ProcessChecker.class);
    Mockito.when(this.registry.counter("genie.jobs.successfulStatusCheck.rate"))
            .thenReturn(this.successfulCheckRate);
    Mockito.when(this.registry.counter("genie.jobs.timeout.rate")).thenReturn(this.timeoutRate);
    Mockito.when(this.registry.counter("genie.jobs.finished.rate")).thenReturn(this.finishedRate);
    Mockito.when(this.registry.counter("genie.jobs.unsuccessfulStatusCheck.rate"))
            .thenReturn(this.unsuccessfulCheckRate);
    Mockito.when(this.registry.counter("genie.jobs.stdOutTooLarge.rate")).thenReturn(this.stdOutTooLarge);
    Mockito.when(this.registry.counter("genie.jobs.stdErrTooLarge.rate")).thenReturn(this.stdErrTooLarge);

    final JobsProperties outputMaxProperties = JobsProperties.getJobsPropertiesDefaults();
    outputMaxProperties.getMax().setStdOutSize(MAX_STD_OUT_LENGTH);
    outputMaxProperties.getMax().setStdErrSize(MAX_STD_ERR_LENGTH);

    this.monitor = new JobMonitor(this.jobExecution, this.stdOut, this.stdErr, this.genieEventBus,
            this.registry, outputMaxProperties, this.processChecker);
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java

void hillClimbing(Solution solution) {
    logger.info(//from w  w  w .  ja va 2s . c om
            String.format("---------- Starting hill climbing for instance %s ----------", solution.getId()));
    Technology technology = solverChecker.enforceSolverSettings(solution.getLstSolutions());

    List<SolutionPerJob> lst = solution.getLstSolutions();
    Stream<SolutionPerJob> strm = settings.isParallel() ? lst.parallelStream() : lst.stream();
    AtomicLong executionTime = new AtomicLong();
    boolean overallSuccess = strm.map(s -> {
        Instant first = Instant.now();
        boolean success = hillClimbing(s, technology);
        Instant after = Instant.now();
        executionTime.addAndGet(Duration.between(first, after).toMillis());
        return success;
    }).reduce(true, Boolean::logicalAnd);

    if (!overallSuccess)
        stateHandler.sendEvent(Events.STOP);
    else {
        solution.setEvaluated(false);
        evaluator.evaluate(solution);

        Phase phase = new Phase();
        phase.setId(PhaseID.OPTIMIZATION);
        phase.setDuration(executionTime.get());
        solution.addPhase(phase);
    }
}

From source file:com.pw.ism.controllers.CommunicationController.java

@RequestMapping(value = "/addheartbeat", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
public ResponseEntity<String> addHeartbeat(@Valid @RequestBody Heartbeat hb, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        LOGGER.info("Bad request!");
        return new ResponseEntity<>("NOK!", HttpStatus.BAD_REQUEST);
    } else {//www .j  a  v a 2 s  .  c o m
        heartbeatRepository.addHeartbeat(hb, Instant.now());
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }
}

From source file:dk.dma.ais.track.rest.resource.TrackResource.java

/**
 * Show status page.//from ww w . ja  v a2  s. c o m
 *
 * Example URL:
 * - http://localhost:8080/?sourceFilter=s.country%20in%20(DK)
 *
 * @param sourceFilterExpression Source filter expression
 * @return
 */
@RequestMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
String home(@RequestParam(value = "sourceFilter", required = false) String sourceFilterExpression) {
    StringBuilder sb = new StringBuilder();

    sb.append("Danish Maritime Authority - AIS Tracker\n").append("---------------------------------------\n")
            .append("\n").append("Tracking started: ").append(timeStarted).append('\n').append("Current time: ")
            .append(Instant.now()).append('\n').append("Total targets tracked: ")
            .append(trackService.numberOfTargets()).append('\n');

    if (!isBlank(sourceFilterExpression))
        sb.append("Targets matching source filter expression: ")
                .append(trackService.numberOfTargets(createSourceFilterPredicate(sourceFilterExpression)))
                .append('\n');

    return sb.toString();
}

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

@Test
public void testXmlExpiration() throws Exception {
    ObjectNode jsonOriginal = (ObjectNode) new ObjectMapper().readTree("{\"foo\":\"bar\"}");

    long now = Instant.now().getEpochSecond();
    ResumptionTokenType token = ResumptionToken.toToken(jsonOriginal, 0);

    OAIPMH oaipmh = OBJECT_FACTORY.createOAIPMH();
    ListRecordsType getRecord = OBJECT_FACTORY.createListRecordsType();
    oaipmh.setListRecords(getRecord);/*from  w  w  w  .j av  a 2 s .  co m*/
    getRecord.setResumptionToken(token);
    JAXBContext context = JAXBContext.newInstance(OAIPMH.class);
    StringWriter writer = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(oaipmh, writer);
    String xml = writer.getBuffer().toString();
    System.out.println("XML is:\n" + xml);
    int start = xml.indexOf("expirationDate=\"") + "expirationDate=\"".length();
    int end = xml.indexOf("\"", start);
    String timestamp = xml.substring(start, end);
    System.out.println("timestamp = " + timestamp);

    assertTrue("Timestamp should be in ISO_INSTANT ending with Z", timestamp.endsWith("Z"));
    TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).parse(timestamp);
    long epochSecond = Instant.from(parse).getEpochSecond();
    long diff = Math.abs(now - epochSecond);
    System.out.println("diff = " + diff);
    assertTrue("Difference between expirationdate and now should be 10 sec or less", diff <= 10);
}

From source file:org.ng200.openolympus.controller.task.TaskCreationController.java

@RequestMapping(method = RequestMethod.POST)
public String createTask(final Model model, final HttpServletRequest request, @Valid final TaskDto taskDto,
        final BindingResult bindingResult) throws IllegalStateException, IOException, ArchiveException {
    this.taskDtoValidator.validate(taskDto, bindingResult, null);
    if (bindingResult.hasErrors()) {
        model.addAttribute("submitURL", "/archive/add");
        model.addAttribute("mode", "add");
        return "tasks/add";
    }/*from  w ww. j  a  v a 2  s .c om*/
    final UUID uuid = UUID.randomUUID();

    Task task = new Task(taskDto.getName(), uuid.toString(), uuid.toString(), Date.from(Instant.now()));

    this.uploadTaskData(task, taskDto);

    task = this.taskRepository.save(task);

    return "redirect:/task/" + task.getId();
}

From source file:io.kamax.mxisd.threepid.session.ThreePidSession.java

public ThreePidSession(String id, String server, ThreePid tPid, String secret, int attempt, String nextLink,
        String token) {//from ww  w.  j  a  v a  2  s.co  m
    this.id = id;
    this.server = server;
    this.tPid = new ThreePid(tPid.getMedium(), tPid.getAddress());
    this.secret = secret;
    this.attempt = attempt;
    this.nextLink = nextLink;
    this.token = token;

    this.timestamp = Instant.now();
}

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

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

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

/**
 * Set an expire time. Useful for anonymous users and tokens
 * @param time seconds from now when the Authentication expires
 *//*from w  ww  . j ava2 s.  c o m*/
public void setExpireTime(long time) {
    this.json.put("expires_on", Instant.now().getEpochSecond() + time);
    if (this.parent != null && this.credential.isPersistent())
        this.parent.commit();
}