Example usage for java.time ZoneId of

List of usage examples for java.time ZoneId of

Introduction

In this page you can find the example usage for java.time ZoneId of.

Prototype

public static ZoneId of(String zoneId) 

Source Link

Document

Obtains an instance of ZoneId from an ID ensuring that the ID is valid and available for use.

Usage

From source file:io.werval.modules.jose.JwtPluginTest.java

@Test
public void http() throws InterruptedException {
    String tokenHeaderName = WERVAL.application().config().string(JWT.HTTP_HEADER_CONFIG_KEY);
    JWT jwt = WERVAL.application().plugin(JWT.class);

    // Unauthorized access to authenticated resource
    when().get("/authenticated").then().statusCode(UNAUTHORIZED_CODE);

    // Login/*w  w  w. ja  va 2 s  . c  o  m*/
    String token = given().body("{\"email\":\"admin@example.com\",\"password\":\"admin-password\"}")
            .contentType(APPLICATION_JSON).when().post("/login").then().statusCode(OK_CODE)
            .header(tokenHeaderName, notNullValue()).log().all().extract().header(tokenHeaderName);

    // Authenticated access
    given().header(tokenHeaderName, token).when().get("/authenticated").then().statusCode(OK_CODE);

    // Authorized access
    given().header(tokenHeaderName, token).when().get("/authorized").then().statusCode(OK_CODE);

    // Gather time related claims from token
    ZoneId utc = ZoneId.of("UTC");
    Map<String, Object> claims = jwt.claimsOfToken(token);
    ZonedDateTime iat = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_ISSUED_AT)),
            utc);
    ZonedDateTime nbf = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_NOT_BEFORE)),
            utc);
    ZonedDateTime exp = ZonedDateTime.ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_EXPIRATION)),
            utc);

    // Wait at least one second before renewal so new dates will be different
    Thread.sleep(1200);

    // Renew token
    String renewed = given().header(tokenHeaderName, token).when().post("/renew").then().statusCode(OK_CODE)
            .header(tokenHeaderName, notNullValue()).log().all().extract().header(tokenHeaderName);

    // Gather time related claims from renewed token
    claims = jwt.claimsOfToken(renewed);
    ZonedDateTime renewedIat = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_ISSUED_AT)), utc);
    ZonedDateTime renewedNbf = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_NOT_BEFORE)), utc);
    ZonedDateTime renewedExp = ZonedDateTime
            .ofInstant(Instant.ofEpochSecond((Long) claims.get(JWT.CLAIM_EXPIRATION)), utc);

    // Assert renewed token time related claims are greater than the ones in the original token
    assertTrue(renewedIat.isAfter(iat));
    assertTrue(renewedNbf.isAfter(nbf));
    assertTrue(renewedExp.isAfter(exp));
}

From source file:com.cohesionforce.dis.ConvertCSV.java

public void run() {

    int count = 0;

    System.out.println("Opening file to convert: " + inputFile);
    BufferedReader br;//from   ww  w.  j  a  v a  2 s  .c o m
    try {
        br = new BufferedReader(new FileReader(inputFile));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    startWriters();
    marking.setCharacterSet(0);

    dr.setDeadReckoningAlgorithm(2);
    dr.setEntityLinearAcceleration(zeroVector);
    dr.setEntityAngularVelocity(zeroVector);

    System.out.println("Starting to convert PDUs");

    while (done == false) {
        String line = null;
        try {
            line = br.readLine(); // throw away header

            // medallion, hack_license, vendor_id, rate_code,
            // store_and_fwd_flag,pickup_datetime,dropoff_datetime,passenger_count,
            // trip_time_in_secs,trip_distance,pickup_longitude,pickup_latitude,
            // dropoff_longitude,dropoff_latitude
            while ((line = br.readLine()) != null) {
                String[] pieces = line.split(cvsSplitBy);

                String medallion = pieces[0];

                LocalDateTime localTime = LocalDateTime.from(formatter.parse(pieces[5]));
                ZonedDateTime zoneTime = localTime.atZone(ZoneId.of("America/New_York"));
                long ts = zoneTime.toInstant().toEpochMilli();

                EntityStatePdu output = getNewEntityState(medallion);
                output.setTimestamp(ts);

                // Create EntityLocation from string
                double plon = Double.parseDouble(pieces[10]);
                double plat = Double.parseDouble(pieces[11]);
                Vector3Double loc = getLocation(plon, plat);
                output.setEntityLocation(loc);

                logPdu(output, 1);

                if (++count % 100000 == 0) {
                    System.out.println("Converted " + count + " PDUs");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        done = true;
    } // end
    try {
        br.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    System.out.print("Waiting on writers to clear their queues");

    boolean emptyQueue = false;
    while (!emptyQueue)

    {
        emptyQueue = true;
        for (LogWriter<?> writer : writers) {
            // If any queue is not empty, sleep and check again
            if (!writer.getQueue().isEmpty()) {
                try {
                    emptyQueue = false;
                    System.out.print(".");
                    Thread.sleep(1000);
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    System.out.println("");
    System.out.println("PDUs converted: " + count);
    System.out.println("Shutting down logging threads");
    threadGroup.interrupt();

    int tries = 0;
    while (threadGroup.activeCount() > 0 && tries < 10)

    {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        ++tries;
    }
    System.out.println("Completed logging threads shutdown");

}

From source file:org.openmhealth.shim.jawbone.mapper.JawboneDataPointMapper.java

/**
 * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response
 * @return a {@link DataPointHeader} for containing the appropriate information based on the input parameters
 *//*from  w  w  w. j ava 2s .c  o m*/
protected DataPointHeader getHeader(JsonNode listEntryNode, T measure) {

    DataPointAcquisitionProvenance.Builder provenanceBuilder = new DataPointAcquisitionProvenance.Builder(
            RESOURCE_API_SOURCE_NAME);

    if (isSensed(listEntryNode)) {
        provenanceBuilder.setModality(SENSED);
    }

    DataPointAcquisitionProvenance acquisitionProvenance = provenanceBuilder.build();

    asOptionalString(listEntryNode, "xid")
            .ifPresent(externalId -> acquisitionProvenance.setAdditionalProperty("external_id", externalId));
    // TODO discuss the name of the external identifier, to make it clear it's the ID used by the source

    asOptionalLong(listEntryNode, "time_updated").ifPresent(
            sourceUpdatedDateTime -> acquisitionProvenance.setAdditionalProperty("source_updated_date_time",
                    OffsetDateTime.ofInstant(Instant.ofEpochSecond(sourceUpdatedDateTime), ZoneId.of("Z"))));

    DataPointHeader header = new DataPointHeader.Builder(UUID.randomUUID().toString(), measure.getSchemaId())
            .setAcquisitionProvenance(acquisitionProvenance).build();

    // FIXME "shared" is never documented
    asOptionalBoolean(listEntryNode, "shared")
            .ifPresent(isShared -> header.setAdditionalProperty("shared", isShared));

    return header;
}

From source file:org.apache.james.mailbox.elasticsearch.json.IndexableMessageTest.java

@Test
public void textShouldContainsCcWhenCc() throws Exception {
    MailboxMessage mailboxMessage = mock(MailboxMessage.class);
    TestId mailboxId = TestId.of(1);//from  ww  w .  ja  v a  2  s  .c o  m
    when(mailboxMessage.getMailboxId()).thenReturn(mailboxId);
    when(mailboxMessage.getFullContent()).thenReturn(new ByteArrayInputStream(
            "Cc: First cc <user@james.org>\nCc: Second cc <user2@james.org>".getBytes()));
    when(mailboxMessage.createFlags()).thenReturn(new Flags());

    IndexableMessage indexableMessage = IndexableMessage.from(mailboxMessage,
            ImmutableList.of(new MockMailboxSession("username").getUser()), new DefaultTextExtractor(),
            ZoneId.of("Europe/Paris"));

    assertThat(indexableMessage.getText()).isEqualTo("First cc user@james.org Second cc user2@james.org");
}

From source file:org.openlmis.fulfillment.Application.java

/**
 * Creates new Clock.
 *
 * @return Created clock.
 */
@Bean
public Clock clock() {
    return Clock.system(ZoneId.of(timeZoneId));
}

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();//from   w w w . j  a va 2  s .c o  m

    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());
}

From source file:io.stallion.tests.integration.aMinimalSite.AMinimalSiteTest.java

@Test
public void testMarkdown() throws IOException {
    String page = IOUtils.toString(getClass().getResource("/text_files/busted-page.txt"), "UTF-8");
    TextFilePersister persister = new TextFilePersister();
    persister.setModelClass(TextItem.class);
    TextItem item = persister.fromString(page, Paths.get("/naming-things.txt"));
    assertEquals("/how-to-name-variables", item.getSlug());
    // publishDate:2013-12-12 11:30:00
    ZonedDateTime dt = ZonedDateTime.of(2013, 12, 12, 11, 30, 0, 0, ZoneId.of("America/New_York"));
    assertEquals(dt, item.getPublishDate());
}

From source file:org.apache.james.mailbox.elasticsearch.json.MailboxMessageToElasticSearchJsonTest.java

@Test
public void htmlEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage htmlMail = new SimpleMailboxMessage(date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/htmlMail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("social", "pocket-money").build(),
            propertyBuilder, MAILBOX_ID);
    htmlMail.setModSeq(MOD_SEQ);/*from w w  w.ja  va2  s  .  c om*/
    htmlMail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(htmlMail,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/htmlMail.json")));
}

From source file:lumbermill.internal.aws.AWSV4SignerImpl.java

public AWSV4SignerImpl(AWSCredentialsProvider credentialsProvider, String region, String service) {
    this.credentialsProvider = credentialsProvider;
    this.region = region;
    this.service = service;
    clock = () -> ZonedDateTime.ofInstant(ZonedDateTime.now().toInstant(), ZoneId.of("UTC")).toLocalDateTime();
}

From source file:org.openlmis.fulfillment.web.ShipmentControllerIntegrationTest.java

@Before
public void setUp() {
    when(dateHelper.getCurrentDateTimeWithSystemZone()).thenReturn(ZonedDateTime.now(ZoneId.of("UTC")));
    when(authenticationHelper.getCurrentUser()).thenReturn(new UserDto(userId));

    generateShipment();//w ww  .ja  va 2  s  .  c  o m

    when(shipmentRepository.findOne(shipmentDtoExpected.getId())).thenReturn(shipment);
    when(shipmentRepository.save(any(Shipment.class))).thenAnswer(new SaveAnswer<>());
    when(orderRepository.findOne(shipmentDtoExpected.getOrder().getId())).thenReturn(order);
    when(orderRepository.save(any(Order.class))).thenAnswer(new SaveAnswer<>());

    when(order.canBeFulfilled()).thenReturn(true);
}