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:org.openhab.binding.ntp.test.NtpOSGiTest.java

@Test
public void testDateTimeChannelTimeZoneUpdate() {

    Configuration configuration = new Configuration();
    configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID);
    initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);

    String testItemState = getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME).toString();
    assertFormat(testItemState, DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS);
    ZonedDateTime timeZoneFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME))
            .getZonedDateTime();//from w w  w  .j  a  v a 2 s .  c  om

    ZoneOffset expectedOffset = ZoneId.of(TEST_TIME_ZONE_ID).getRules()
            .getOffset(timeZoneFromItemRegistry.toInstant());
    assertEquals(expectedOffset, timeZoneFromItemRegistry.getOffset());
}

From source file:io.stallion.jobs.Schedule.java

/**
 * Runs the given days of the week, every other week.
 *
 * @param startingAt//from   w ww . j  a  v a 2s  . c  o m
 * @param days
 * @return
 */
public Schedule daysBiweekly(Long startingAt, DayOfWeek... days) {
    this._days.verifyAndUpdateUnset();
    this._days.setIntervalType(Days.IntervalType.BIWEEKLY_DAY_OF_WEEK);
    for (DayOfWeek day : days) {
        this._days.add(day.getValue());
    }
    ZonedDateTime startingWeek = ZonedDateTime.ofInstant(Instant.ofEpochMilli(startingAt), ZoneId.of("UTC"));
    // Get the Monday 12PM of that week
    startingWeek = startingWeek.minusDays(startingWeek.getDayOfWeek().getValue() - 1).withSecond(0).withHour(12)
            .withMinute(0).withNano(0);
    this._days.setStartingDate(startingWeek);
    return this;
}

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

@Test
public void emailWithNoInternalDateShouldUseNowDate() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage mailWithNoInternalDate = new SimpleMailboxMessage(null, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/recursiveMail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    mailWithNoInternalDate.setModSeq(MOD_SEQ);
    mailWithNoInternalDate.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mailWithNoInternalDate,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .when(IGNORING_VALUES)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/recursiveMail.json")));
}

From source file:com.yahoo.egads.models.tsmm.OlympicModel2.java

/**
 * Default Ctor/*from   ww w . j  a v  a2 s .  c  o m*/
 * @param config A non-null and non-empty properties map.
 * @throws IllegalArgumentException if a required property is missing.
 * @throws NumberFormatException if a numeric property could not be parsed.
 */
public OlympicModel2(final Properties config) {
    super(config);

    // TODO - some additional validation around distance being greater
    // or equal to the window size.
    String temp = config.getProperty("WINDOW_SIZE");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("WINDOW_SIZE is required, " + "e.g. 1 or 5");
    }
    windowSize = Long.parseLong(temp);
    temp = config.getProperty("WINDOW_SIZE_UNITS");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("WINDOW_SIZE_UNITS is required, " + "e.g. MINUTES OR HOURS");
    }
    windowUnits = ChronoUnit.valueOf(temp.toUpperCase());

    temp = config.getProperty("INTERVAL");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("INTERVAL is required, " + "e.g. 1 or 5");
    }
    interval = Long.parseLong(temp);
    temp = config.getProperty("INTERVAL_UNITS");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("INTERVAL_UNITS is required, " + "e.g. MINUTES OR HOURS");
    }
    intervalUnits = ChronoUnit.valueOf(temp.toUpperCase());

    temp = config.getProperty("WINDOW_DISTANCE");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("WINDOW_DISTANCE is required, " + "e.g. 1 or 5");
    }
    windowDistanceInterval = Long.parseLong(temp);

    temp = config.getProperty("WINDOW_DISTANCE_UNITS");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("WINDOW_DISTANCE_UNITS is " + "required, e.g. MINUTES OR HOURS");
    }
    windowDistanceIntervalUnits = ChronoUnit.valueOf(temp.toUpperCase());

    temp = config.getProperty("WINDOW_AGGREGATOR");
    if (temp == null || temp.isEmpty()) {
        windowAggregator = "AVG";
    } else {
        temp = temp.toUpperCase();
        if (!(temp.equals("AVG") || temp.equals("MIN") || temp.equals("MAX") || temp.equals("SUM")
                || temp.equals("COUNT") || temp.equals("WAVG") || temp.equals("MEDIAN"))) {
            throw new IllegalArgumentException("The window aggregator was" + " not implemented: " + temp);
        }
        windowAggregator = temp;
    }

    temp = config.getProperty("MODEL_START");
    if (temp == null || temp.isEmpty()) {
        throw new IllegalArgumentException("MODEL_START is required, " + "e.g. 1474756200");
    }
    modelStartEpoch = Long.parseLong(temp);

    pastWindows = Integer.parseInt(config.getProperty("HISTORICAL_WINDOWS", "1"));
    weighting = Boolean.parseBoolean(config.getProperty("ENABLE_WEIGHTING", "false"));
    futureWindows = Integer.parseInt(config.getProperty("FUTURE_WINDOWS", "1"));
    drop_highest = Integer.parseInt(config.getProperty("NUM_TO_DROP_HIGHEST", "0"));
    drop_lowest = Integer.parseInt(config.getProperty("NUM_TO_DROP_LOWEST", "0"));

    zone = ZoneId.of(config.getProperty("TIMEZONE", "UTC"));

    windowTimes = new ZonedDateTime[pastWindows];
    indices = new int[pastWindows];
    model = Lists.newArrayList();
}

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

/**
 * Translates a time zone descriptor from one of various representations (Olson, seconds offset, GMT offset) into a
 * {@link ZoneId}./*from   w  ww . j ava2s . c o m*/
 *
 * @param timeZoneValueNode the value associated with a timezone property
 */
static ZoneId parseZone(JsonNode timeZoneValueNode) {

    // default to UTC if timezone is not present
    if (timeZoneValueNode.isNull()) {
        return ZoneOffset.UTC;
    }

    // "-25200"
    if (timeZoneValueNode.asInt() != 0) {
        ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(timeZoneValueNode.asInt());

        // TODO confirm if this is even necessary, since ZoneOffset is a ZoneId
        return ZoneId.ofOffset("GMT", zoneOffset);
    }

    // e.g., "GMT-0700" or "America/Los_Angeles"
    if (timeZoneValueNode.isTextual()) {
        return ZoneId.of(timeZoneValueNode.textValue());
    }

    throw new IllegalArgumentException(format("The time zone node '%s' can't be parsed.", timeZoneValueNode));
}

From source file:ddf.catalog.registry.federationadmin.service.impl.FederationAdminServiceImpl.java

private void createIdentityNode() throws SourceUnavailableException, IngestException {

    String registryPackageId = UUID.randomUUID().toString().replaceAll("-", "");
    RegistryPackageType registryPackage = RIM_FACTORY.createRegistryPackageType();
    registryPackage.setId(registryPackageId);
    registryPackage.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    ExtrinsicObjectType extrinsicObject = RIM_FACTORY.createExtrinsicObjectType();
    extrinsicObject.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    String extrinsicObjectId = UUID.randomUUID().toString().replaceAll("-", "");
    extrinsicObject.setId(extrinsicObjectId);

    String siteName = SystemInfo.getSiteName();
    if (StringUtils.isNotBlank(siteName)) {
        extrinsicObject.setName(getInternationalStringTypeFromString(siteName));
    }/*w ww. j av  a2s.  c o  m*/

    String home = SystemBaseUrl.getBaseUrl();
    if (StringUtils.isNotBlank(home)) {
        extrinsicObject.setHome(home);
    }

    String version = SystemInfo.getVersion();
    if (StringUtils.isNotBlank(version)) {
        VersionInfoType versionInfo = RIM_FACTORY.createVersionInfoType();
        versionInfo.setVersionName(version);

        extrinsicObject.setVersionInfo(versionInfo);
    }

    OffsetDateTime now = OffsetDateTime.now(ZoneId.of(ZoneOffset.UTC.toString()));
    String rightNow = now.toString();
    ValueListType valueList = RIM_FACTORY.createValueListType();
    valueList.getValue().add(rightNow);

    SlotType1 lastUpdated = RIM_FACTORY.createSlotType1();
    lastUpdated.setValueList(RIM_FACTORY.createValueList(valueList));
    lastUpdated.setSlotType(DatatypeConstants.DATETIME.toString());
    lastUpdated.setName(RegistryConstants.XML_LAST_UPDATED_NAME);
    extrinsicObject.getSlot().add(lastUpdated);

    SlotType1 liveDate = RIM_FACTORY.createSlotType1();
    liveDate.setValueList(RIM_FACTORY.createValueList(valueList));
    liveDate.setSlotType(DatatypeConstants.DATETIME.toString());
    liveDate.setName(RegistryConstants.XML_LIVE_DATE_NAME);
    extrinsicObject.getSlot().add(liveDate);

    if (registryPackage.getRegistryObjectList() == null) {
        registryPackage.setRegistryObjectList(RIM_FACTORY.createRegistryObjectListType());
    }

    registryPackage.getRegistryObjectList().getIdentifiable()
            .add(RIM_FACTORY.createIdentifiable(extrinsicObject));

    Metacard identityMetacard = jaxbToMetacard(registryPackage);
    if (identityMetacard != null) {
        Attribute registryNodeAttribute = new AttributeImpl(RegistryObjectMetacardType.REGISTRY_IDENTITY_NODE,
                true);
        identityMetacard.setAttribute(registryNodeAttribute);

        addLocalEntry(identityMetacard);
    }
}

From source file:org.codice.ddf.registry.federationadmin.service.impl.IdentityNodeInitialization.java

private void createIdentityNode() throws FederationAdminException {
    String registryPackageId = System.getProperty(RegistryConstants.REGISTRY_ID_PROPERTY);
    if (StringUtils.isEmpty(registryPackageId)) {
        registryPackageId = RegistryConstants.GUID_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");
        setSystemRegistryId(registryPackageId);
    }/*  ww  w. j  a  va 2  s .  com*/
    LOGGER.info("Creating registry identity node: {} {}", SystemInfo.getSiteName(), registryPackageId);
    RegistryPackageType registryPackage = RIM_FACTORY.createRegistryPackageType();
    registryPackage.setId(registryPackageId);
    registryPackage.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    ExtrinsicObjectType extrinsicObject = RIM_FACTORY.createExtrinsicObjectType();
    extrinsicObject.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    String extrinsicObjectId = RegistryConstants.GUID_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");
    extrinsicObject.setId(extrinsicObjectId);

    String siteName = SystemInfo.getSiteName();
    if (StringUtils.isNotBlank(siteName)) {
        extrinsicObject.setName(internationalStringTypeHelper.create(siteName));
    } else {
        extrinsicObject.setName(internationalStringTypeHelper.create(UNKNOWN_SITE_NAME));
    }

    String home = SystemBaseUrl.EXTERNAL.getBaseUrl();
    extrinsicObject.setHome(home);

    String version = SystemInfo.getVersion();
    if (StringUtils.isNotBlank(version)) {
        VersionInfoType versionInfo = RIM_FACTORY.createVersionInfoType();
        versionInfo.setVersionName(version);

        extrinsicObject.setVersionInfo(versionInfo);
    }

    OffsetDateTime now = OffsetDateTime.now(ZoneId.of(ZoneOffset.UTC.toString()));
    String rightNow = now.toString();

    SlotType1 lastUpdated = slotTypeHelper.create(RegistryConstants.XML_LAST_UPDATED_NAME, rightNow, DATE_TIME);
    extrinsicObject.getSlot().add(lastUpdated);

    SlotType1 liveDate = slotTypeHelper.create(RegistryConstants.XML_LIVE_DATE_NAME, rightNow, DATE_TIME);
    extrinsicObject.getSlot().add(liveDate);

    if (registryPackage.getRegistryObjectList() == null) {
        registryPackage.setRegistryObjectList(RIM_FACTORY.createRegistryObjectListType());
    }

    registryPackage.getRegistryObjectList().getIdentifiable()
            .add(RIM_FACTORY.createIdentifiable(extrinsicObject));

    Metacard identityMetacard = getRegistryMetacardFromRegistryPackage(registryPackage);
    if (identityMetacard != null) {
        identityMetacard
                .setAttribute(new AttributeImpl(RegistryObjectMetacardType.REGISTRY_IDENTITY_NODE, true));
        identityMetacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.REGISTRY_LOCAL_NODE, true));
        federationAdminService.addRegistryEntry(identityMetacard);
    }
}

From source file:org.openhab.binding.ntp.test.NtpOSGiTest.java

@Test
public void testDateTimeChannelCalendarTimeZoneUpdate() {
    Configuration configuration = new Configuration();
    configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID);
    initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);
    ZonedDateTime timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME))
            .getZonedDateTime();//from w w  w . ja  v a 2  s .c o m

    ZoneOffset expectedOffset = ZoneId.of(TEST_TIME_ZONE_ID).getRules()
            .getOffset(timeZoneIdFromItemRegistry.toInstant());
    assertEquals(expectedOffset, timeZoneIdFromItemRegistry.getOffset());
}

From source file:org.symphonyoss.simplebot.LunchBoxBot.java

private void processMessage(Message message) {
    username = message.getFromUserId().toString();
    String messageString = message.getMessage();
    if (StringUtils.isNotEmpty(messageString) && StringUtils.isNotBlank(messageString)) {
        MlMessageParser messageParser = new MlMessageParser();
        try {/*w w w  . j  av  a  2  s  .  c o m*/
            messageParser.parseMessage(messageString);
            String text = messageParser.getText();
            if (isFeedback == true) {
                processFeedback(text);
                isFeedback = false;
            }

            if (StringUtils.startsWithIgnoreCase(text, "/lunchbox")) {
                LunchBotCommand cmd = getLunchBotCommand(text);

                switch (cmd) {
                case MENU:
                    HashMap lunch = parseLunchMenu(todayDateString);
                    sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body"));
                    break;
                case FEEDBACK:
                    isFeedback = true;
                    break;
                case TOMORROW:
                    LocalDate tomorrowDate = LocalDate.from(todayDate.toInstant().atZone(ZoneId.of("UTC")))
                            .plusDays(1);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy,MM,dd");
                    String tomorrowString = tomorrowDate.format(formatter);
                    lunch = parseLunchMenu(tomorrowString);
                    sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body"));
                    break;
                case FORMAT:
                    sendMessage(
                            "- For feedback on individual items on the menu, <item number> -> <number of stars (out of 5)>\n- For feedback on lunch as a whole, <overall> -> <number of stars (out of 5)>, comments (optional)\n\n\nP.S: Please provide complete feedback in a single message with each section separated by a comma");
                    break;
                case OPTIONS:
                    sendMessage(
                            "For today's menu:  '/lunchbox menu' OR '/lunchbox today's menu'\nFor tomorrow's menu: '/lunchbox tomorrow' OR '/lunchbox tomorrow's menu'\nFor tips on format for feedback: '/lunchbox format'\nFor feedback: '/lunchbox feedback' <hit enter and then provide feedback all in one message>\nFor options: '/lunchbox help'\n\n\nP.S: All commands should be typed without quotes");
                    break;
                case UNKNOWN:
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testAlreadyMigratedEvent() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {/* w w  w . ja  v a2 s  .  com*/
        ZonedDateTime migrationTs = ZonedDateTime.now(ZoneId.of("UTC"));
        eventMigrationRepository.insertMigrationData(event.getId(), currentVersion, migrationTs,
                EventMigration.Status.COMPLETE.toString());
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(migrationTs.toString(), eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(AVAILABLE_SEATS, tickets.size());//<-- the migration has not been done
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}