Example usage for java.time.format DateTimeFormatter ISO_INSTANT

List of usage examples for java.time.format DateTimeFormatter ISO_INSTANT

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ISO_INSTANT.

Prototype

DateTimeFormatter ISO_INSTANT

To view the source code for java.time.format DateTimeFormatter ISO_INSTANT.

Click Source Link

Document

The ISO instant formatter that formats or parses an instant in UTC, such as '2011-12-03T10:15:30Z'.

Usage

From source file:Main.java

public static void main(String[] argv) {

    LocalDateTime now = LocalDateTime.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.of(now, TimeZone.NEW_YORK);
    System.out.println("now = " + now);
    System.out.println("Current date and time in a particular timezone : " + zonedDateTime);

    now = LocalDateTime.now(TimeZone.INDIA);
    System.out.println("now in India = " + now);

    zonedDateTime = ZonedDateTime.now();
    System.out.println("zonedDateTime with default(system) timezone = " + zonedDateTime);
    System.out.println("zonedDateTime with India timezone = " + ZonedDateTime.now(TimeZone.INDIA));

    String isoFormatted = DateTimeFormatter.ISO_INSTANT.format(ZonedDateTime.now(TimeZone.INDIA));
    System.out.println("ISO Formatted = " + isoFormatted);

    ZonedDateTime utahMarch8thAt2AM = ZonedDateTime.of(LocalDateTime.of(2015, 3, 8, 1, 0), TimeZone.UTAH);
    System.out.println("utahMarch8thAt2AM = " + utahMarch8thAt2AM);
    System.out.println("utahMarch8thAt2AM.plusHours(1) = " + utahMarch8thAt2AM.plusHours(1));
    System.out.println("utahMarch8thAt2AM.plusHours(2) = " + utahMarch8thAt2AM.plusHours(2));
}

From source file:com.oharemza.timeteller.TimeTellerController.java

@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public String tell() {
    return DateTimeFormatter.ISO_INSTANT.format(ZonedDateTime.now(clock));
}

From source file:co.runrightfast.vertx.core.eventbus.EventBusUtils.java

/**
 * Adds the following headers://from   w  ww .  j  ava  2 s  . c  o  m
 *
 * <ul>
 * <li>{@link MessageHeader#MESSAGE_ID}
 * <li>{@link MessageHeader#MESSAGE_TIMESTAMP}
 * </ul>
 *
 * @return DeliveryOptions
 */
static DeliveryOptions deliveryOptions() {
    final DeliveryOptions options = new DeliveryOptions();
    options.addHeader(MESSAGE_ID.header, uuid());
    options.addHeader(MESSAGE_TIMESTAMP.header, DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
    options.addHeader(FROM_JVM.header, JVM_ID);
    return options;
}

From source file:fi.helsinki.opintoni.service.TimeService.java

public String nowUTCAsString() {
    ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
    return utc.format(DateTimeFormatter.ISO_INSTANT);
}

From source file:org.apache.metron.profiler.spark.TimestampParser.java

/**
 * Parses an input string and returns an optional timestamp in epoch milliseconds.
 *
 * @param inputString The input defining a timestamp.
 * @return A timestamp in epoch milliseconds.
 *//*from  w  w  w.j  a  v a 2s.  com*/
public Optional<Long> parse(String inputString) {
    Optional<Long> epochMilli = Optional.empty();

    // a blank is acceptable and treated as undefined
    if (StringUtils.isNotBlank(inputString)) {
        epochMilli = Optional.of(new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_INSTANT)
                .toFormatter().parse(inputString, Instant::from).toEpochMilli());
    }

    return epochMilli;
}

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 {/*from  ww w .j ava 2  s  .com*/
        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:com.synopsys.integration.hub.bdio.BdioNodeFactory.java

public BdioBillOfMaterials createBillOfMaterials(final String codeLocationName, final String projectName,
        final String projectVersion) {
    final BdioBillOfMaterials billOfMaterials = new BdioBillOfMaterials();
    billOfMaterials.id = String.format("uuid:%s", UUID.randomUUID());
    if (StringUtils.isNotBlank(codeLocationName)) {
        billOfMaterials.spdxName = codeLocationName;
    } else {//  w  w w. j ava2  s. c  o  m
        billOfMaterials.spdxName = String.format("%s/%s Black Duck I/O Export", projectName, projectVersion);
    }
    billOfMaterials.bdioSpecificationVersion = "1.1.0";

    billOfMaterials.creationInfo = new BdioCreationInfo();
    billOfMaterials.creationInfo.created = Instant.now().atOffset(ZoneOffset.UTC)
            .format(DateTimeFormatter.ISO_INSTANT);
    String version = "UnknownVersion";
    try (InputStream inputStream = getClass().getClassLoader()
            .getResourceAsStream("com/blackducksoftware/integration/hub/bdio/version.txt")) {
        version = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    } catch (final IOException e) {
    }
    billOfMaterials.creationInfo.addSpdxCreator(SpdxCreator.createToolSpdxCreator("IntegrationBdio", version));

    return billOfMaterials;
}

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java

/**
 * Collects metrics on messages that are sent
 *
 * <h3>Meters</h3>/*ww  w  .j  av a 2s.co m*/
 * <ol>
 * <li>{@link RunRightFastVerticleMetrics.Meters#MESSAGE_SENT}
 * <li>{@link RunRightFastVerticleMetrics.Meters#MESSAGE_PUBLISHED}
 * </ol>
 *
 * <h3>Gauges</h3>
 * <ol>
 * <li>{@link RunRightFastVerticleMetrics.Meters#MESSAGE_SENT}
 * <li>{@link RunRightFastVerticleMetrics.Meters#MESSAGE_PUBLISHED}
 * </ol>
 *
 * @param eventBus
 * @param address
 * @param codec - used to register the message codec
 * @param metricRegistry used to register the 2 meters described above
 */
public ProtobufMessageProducer(@NonNull final EventBus eventBus, final String address,
        @NonNull final ProtobufMessageCodec<A> codec, @NonNull final MetricRegistry metricRegistry) {
    checkArgument(isNotBlank(address));
    this.eventBus = eventBus;
    this.address = address;

    registerMessageCodec(codec);

    this.messageSent = metricRegistry.meter(String.format("%s::%s", MESSAGE_SENT.metricName, address));
    this.messagePublished = metricRegistry
            .meter(String.format("%s::%s", MESSAGE_PUBLISHED.metricName, address));
    metricRegistry.register(String.format("%s::%s", MESSAGE_LAST_SENT_TS.metricName, address),
            (Gauge<String>) () -> {
                return messageLastSent != null ? DateTimeFormatter.ISO_INSTANT.format(messageLastSent) : null;
            });

    metricRegistry.register(String.format("%s::%s", MESSAGE_LAST_PUBLISHED_TS.metricName, address),
            (Gauge<String>) () -> {
                return messageLastPublished != null ? DateTimeFormatter.ISO_INSTANT.format(messageLastPublished)
                        : null;
            });
}

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);/*ww w .  j av  a  2 s . c  om*/
    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:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testPostSuccess() throws InterruptedException {
    final String start = Instant.now().minusMillis(812).atZone(ZoneId.of("UTC"))
            .format(DateTimeFormatter.ISO_INSTANT);
    final String end = Instant.now().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT);
    final String id = UUID.randomUUID().toString();

    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        // Annotations
        Assert.assertEquals(7, r.getAnnotationsCount());
        assertAnnotation(r.getAnnotationsList(), "foo", "bar");
        assertAnnotation(r.getAnnotationsList(), "_service", "myservice");
        assertAnnotation(r.getAnnotationsList(), "_cluster", "mycluster");
        assertAnnotation(r.getAnnotationsList(), "_start", start);
        assertAnnotation(r.getAnnotationsList(), "_end", end);
        assertAnnotation(r.getAnnotationsList(), "_id", id);

        // Dimensions
        Assert.assertEquals(3, r.getDimensionsCount());
        assertDimension(r.getDimensionsList(), "host", "some.host.com");
        assertDimension(r.getDimensionsList(), "service", "myservice");
        assertDimension(r.getDimensionsList(), "cluster", "mycluster");

        // Samples
        assertSample(r.getTimersList(), "timerLong", 123L, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getTimersList(), "timerInt", 123, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getTimersList(), "timerShort", (short) 123, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getTimersList(), "timerByte", (byte) 123, ClientV2.Unit.Type.Value.SECOND,
                ClientV2.Unit.Scale.Value.NANO);
        assertSample(r.getCountersList(), "counter", 8d);
        assertSample(r.getGaugesList(), "gauge", 10d, ClientV2.Unit.Type.Value.BYTE,
                ClientV2.Unit.Scale.Value.UNIT);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final AtomicBoolean assertionResult = new AtomicBoolean(false);
    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH))
            .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 1, 451, true,
                    new CompletionHandler(semaphore)))
            .build();//  w  ww  .  j a  va2s  .com

    final Map<String, String> annotations = new LinkedHashMap<>();
    annotations.put("foo", "bar");
    annotations.put("_start", start);
    annotations.put("_end", end);
    annotations.put("_host", "some.host.com");
    annotations.put("_service", "myservice");
    annotations.put("_cluster", "mycluster");
    annotations.put("_id", id);

    final TsdEvent event = new TsdEvent(annotations,
            createQuantityMap("timerLong", TsdQuantity.newInstance(123L, Units.NANOSECOND), "timerInt",
                    TsdQuantity.newInstance(123, Units.NANOSECOND), "timerShort",
                    TsdQuantity.newInstance((short) 123, Units.NANOSECOND), "timerByte",
                    TsdQuantity.newInstance((byte) 123, Units.NANOSECOND)),
            createQuantityMap("counter", TsdQuantity.newInstance(8d, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(10d, Units.BYTE)));

    sink.record(event);
    semaphore.acquire();

    // Ensure expected handler was invoked
    Assert.assertTrue(assertionResult.get());

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that data was sent
    _wireMockRule.verify(1, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}