Example usage for java.time ZonedDateTime now

List of usage examples for java.time ZonedDateTime now

Introduction

In this page you can find the example usage for java.time ZonedDateTime now.

Prototype

public static ZonedDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:com.github.dokandev.dokanjava.samples.memoryfs.MemFileInfo.java

MemFileInfo(String fileName, boolean isDirectory) {
    this.fileName = fileName;
    this.isDirectory = isDirectory;
    fileIndex = getNextFileIndex();// w  ww  .  j a va  2  s.  com
    if (isDirectory)
        fileAttribute |= FILE_ATTRIBUTE_DIRECTORY.mask();
    long fileTime = FileTime.toFileTime(ZonedDateTime.now());
    creationTime = fileTime;
    lastAccessTime = fileTime;
    lastWriteTime = fileTime;
}

From source file:dk.dma.vessel.track.store.AisStoreClient.java

public List<PastTrackPos> getPastTrack(int mmsi, Integer minDist, Duration age) {

    // Determine URL
    age = age != null ? age : Duration.parse(pastTrackTtl);
    minDist = minDist == null ? Integer.valueOf(pastTrackMinDist) : minDist;
    ZonedDateTime now = ZonedDateTime.now();
    String from = now.format(DateTimeFormatter.ISO_INSTANT);
    ZonedDateTime end = now.minus(age);
    String to = end.format(DateTimeFormatter.ISO_INSTANT);
    String interval = String.format("%s/%s", to, from);
    String url = String.format("%s?mmsi=%d&interval=%s", aisViewUrl, mmsi, interval);

    final List<PastTrackPos> track = new ArrayList<>();
    try {// ww  w .j av  a2 s  . co m
        long t0 = System.currentTimeMillis();

        // TEST
        url = url + "&filter=" + URLEncoder.encode("(s.country not in (GBR)) & (s.region!=808)", "UTF-8");

        // Set up a few timeouts and fetch the attachment
        URLConnection con = new URL(url).openConnection();
        con.setConnectTimeout(10 * 1000); // 10 seconds
        con.setReadTimeout(60 * 1000); // 1 minute

        if (!StringUtils.isEmpty(aisAuthHeader)) {
            con.setRequestProperty("Authorization", aisAuthHeader);
        }

        try (InputStream in = con.getInputStream(); BufferedInputStream bin = new BufferedInputStream(in)) {
            AisReader aisReader = AisReaders.createReaderFromInputStream(bin);
            aisReader.registerPacketHandler(new Consumer<AisPacket>() {
                @Override
                public void accept(AisPacket p) {
                    AisMessage message = p.tryGetAisMessage();
                    if (message == null || !(message instanceof IVesselPositionMessage)) {
                        return;
                    }
                    VesselTarget target = new VesselTarget();
                    target.merge(p, message);
                    if (!target.checkValidPos()) {
                        return;
                    }
                    track.add(new PastTrackPos(target.getLat(), target.getLon(), target.getCog(),
                            target.getSog(), target.getLastPosReport()));
                }
            });
            aisReader.start();
            try {
                aisReader.join();
            } catch (InterruptedException e) {
                return null;
            }
        }
        LOG.info(String.format("Read %d past track positions in %d ms", track.size(),
                System.currentTimeMillis() - t0));
    } catch (IOException e) {
        LOG.error("Failed to make REST query: " + url);
        throw new InternalError("REST endpoint failed");
    }
    LOG.info("AisStore returned track with " + track.size() + " points");
    return PastTrack.downSample(track, minDist, age.toMillis());
}

From source file:io.yields.math.framework.kpi.ScoreDAO.java

/**
 * Persists a #{ScoreResult}./*from  w w w. j av a  2 s .  c  o  m*/
 * If a system property yields.score.path is found, this result is written to that location.
 * Otherwise, this result is written to the path defined by the system property java.io.tmpDir.
 *
 * @param scoreResult Score Result to persist
 */
public static void save(ScoreResult scoreResult) {

    File destinationFolder = getRootFolder();

    if (!destinationFolder.exists()) {
        try {
            forceMkdir(destinationFolder);
        } catch (IOException ioe) {
            throw new IllegalStateException(format("Destination folder for scores could not be created at %s",
                    destinationFolder.getAbsolutePath()), ioe);
        }
    }

    if (!destinationFolder.isDirectory()) {
        throw new IllegalStateException(
                format("Destination path for scores %s is not a folder", destinationFolder.getAbsolutePath()));
    }

    if (!destinationFolder.canWrite()) {
        throw new IllegalStateException(format("Destination folder for scores %s is not writable",
                destinationFolder.getAbsolutePath()));
    }

    ObjectMapper jsonMapper = getObjectMapper();
    File destinationFile = new File(destinationFolder, scoreResult.getName().replaceAll("[^a-zA-Z0-9]", "_")
            + "_" + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + "." + FILE_SUFFIX);
    try {
        scoreResult.setTimestamp(ZonedDateTime.now());
        jsonMapper.writeValue(destinationFile, scoreResult);
        logger.info("Written score result to {}", destinationFile.getAbsolutePath());
    } catch (IOException ioe) {
        logger.error("Could not write score result to file " + destinationFile.getAbsolutePath(), ioe);
        throw new IllegalStateException(
                format("Could not write score file at %s", destinationFile.getAbsolutePath()), ioe);
    }

}

From source file:org.springframework.social.twitter.api.impl.ton.TonTemplateTest.java

@Test
public void uploadChunk() throws IOException {
    mockServer.expect(requestTo("https://ton.twitter.com/1.1/ton/bucket/ta_partner")).andExpect(method(POST))
            .andRespond(withCreatedEntity(URI.create(RESPONSE_URI)));

    Resource resource = dataResource("hashed_twitter.txt");
    InputStream is = resource.getInputStream();
    String contentType = URLConnection.guessContentTypeFromName(resource.getFilename());
    byte[] data = bufferObj(is);
    ZonedDateTime expiry = ZonedDateTime.now().plusDays(7);
    URI uri = twitter.tonOperations().uploadSingleChunk(BUCKET_NAME, data, contentType, expiry);
    assertEquals(uri.toString(), RESPONSE_URI);
}

From source file:com.streamsets.datacollector.json.TestJsonRecordWriterImpl.java

@Test
public void testZonedDateTime() throws Exception {
    ZonedDateTime now = ZonedDateTime.now();
    StringWriter writer = new StringWriter();
    JsonRecordWriterImpl jsonRecordWriter = new JsonRecordWriterImpl(writer, Mode.MULTIPLE_OBJECTS);

    Record record = new RecordImpl("stage", "id", null, null);
    record.set(Field.createZonedDateTime(now));
    jsonRecordWriter.write(record);/*  w ww . j a  v a 2 s .c  om*/
    jsonRecordWriter.close();

    Assert.assertEquals("\"" + now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME) + "\"", writer.toString());
}

From source file:com.example.jpa.UserEntity.java

@PrePersist
public void setCreatedAt() {
    final ZonedDateTime now = ZonedDateTime.now();
    final Instant instant = now.toInstant();
    this.createdAt = Date.from(instant);
}

From source file:org.apache.james.jmap.model.SetMessagesResponseTest.java

@Test
public void builderShouldWork() {
    ZonedDateTime currentDate = ZonedDateTime.now();
    ImmutableMap<CreationMessageId, Message> created = ImmutableMap.of(CreationMessageId.of("user|created|1"),
            Message.builder().id(MessageId.of("user|created|1")).blobId(BlobId.of("blobId"))
                    .threadId("threadId").mailboxIds(ImmutableList.of(InMemoryId.of(123)))
                    .headers(ImmutableMap.of("key", "value")).subject("subject").size(123).date(currentDate)
                    .preview("preview").build());
    ImmutableList<MessageId> updated = ImmutableList.of(MessageId.of("user|updated|1"));
    ImmutableList<MessageId> destroyed = ImmutableList.of(MessageId.of("user|destroyed|1"));
    ImmutableMap<CreationMessageId, SetError> notCreated = ImmutableMap
            .of(CreationMessageId.of("dead-beef-defec8"), SetError.builder().type("created").build());
    ImmutableMap<MessageId, SetError> notUpdated = ImmutableMap.of(MessageId.of("user|update|2"),
            SetError.builder().type("updated").build());
    ImmutableMap<MessageId, SetError> notDestroyed = ImmutableMap.of(MessageId.of("user|destroyed|3"),
            SetError.builder().type("destroyed").build());
    SetMessagesResponse expected = new SetMessagesResponse(null, null, null, created, updated, destroyed,
            notCreated, notUpdated, notDestroyed);

    SetMessagesResponse setMessagesResponse = SetMessagesResponse.builder().created(created).updated(updated)
            .destroyed(destroyed).notCreated(notCreated).notUpdated(notUpdated).notDestroyed(notDestroyed)
            .build();/*from   w ww  .  j  a  v a2 s .c  o  m*/

    assertThat(setMessagesResponse).isEqualToComparingFieldByField(expected);
}

From source file:alfio.util.TemplateResourceTest.java

private Pair<ZonedDateTime, ZonedDateTime> getDates() {
    ZonedDateTime eventBegin = ZonedDateTime.now().plusDays(1);
    ZonedDateTime eventEnd = ZonedDateTime.now().plusDays(3);
    ZonedDateTime validityStart = ZonedDateTime.now().plusDays(2);

    when(event.getBegin()).thenReturn(eventBegin);
    when(event.getZoneId()).thenReturn(ZoneId.systemDefault());
    when(event.getEnd()).thenReturn(eventEnd);
    when(ticketCategory.getTicketValidityStart(eq(ZoneId.systemDefault()))).thenReturn(validityStart);
    when(ticket.ticketCode(anyString())).thenReturn("abcd");
    return Pair.of(validityStart, eventEnd);
}

From source file:com.github.ibm.domino.client.CalendarClientTest.java

@Test
public void test1PostEvents() {
    System.out.println("postEvents");
    DominoRestClient instance = initClient();
    CalendarEventsWrapper events = new CalendarEventsWrapper();
    CalendarEvent event = new CalendarEvent();
    event.setSummary("This is a new event");
    event.setLocation("here");
    ZonedDateTime zdt = ZonedDateTime.now().plusDays(10);
    event.getStart().setDateTime(zdt);/*  w w w  .  ja va2  s  .c o  m*/
    event.getEnd().setDateTime(zdt.plusHours(2));
    events.getEvents().add(event);
    ResponseEntity<Object> response = instance.postEvent(events);
    assertTrue(response.getStatusCode().is2xxSuccessful());
}

From source file:com.cosmicpush.pub.push.LqNotificationPush.java

@JsonCreator
private LqNotificationPush(@JsonProperty("topic") String topic, @JsonProperty("summary") String summary,
        @JsonProperty("trackingId") String trackingId, @JsonProperty("createdAt") ZonedDateTime createdAt,
        @JsonProperty("exceptionInfo") LqExceptionInfo exceptionInfo,
        @JsonProperty("attachmentsArg") Collection<LqAttachment> attachments,
        @JsonProperty("callbackUrl") String callbackUrl, @JsonProperty("remoteHost") String remoteHost,
        @JsonProperty("remoteAddress") String remoteAddress,
        @JsonProperty("traits") Map<String, String> traits) {

    this.topic = (topic != null) ? topic : "none";
    this.summary = (summary != null) ? summary : "none";
    this.trackingId = trackingId;
    this.exceptionInfo = exceptionInfo;
    this.createdAt = (createdAt != null) ? createdAt : ZonedDateTime.now();

    if (traits != null) {
        this.traits.putAll(traits);
    }// w w  w .jav  a2  s  .c o  m

    if (attachments != null) {
        this.attachments.addAll(attachments);
    }

    this.remoteHost = remoteHost;
    this.remoteAddress = remoteAddress;

    this.callbackUrl = callbackUrl;

    String[] keys = ReflectUtils.toArray(String.class, this.traits.keySet());

    for (String key : keys) {
        if (StringUtils.isBlank(this.traits.get(key))) {
            this.traits.remove(key);
        }
    }
}