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.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importTimeslotList() {
    List<Timeslot> timeslotList = new ArrayList<>();
    Map<Timeslot, List<Room>> timeslotToAvailableRoomsMap = new HashMap<>();
    Map<Pair<LocalDateTime, LocalDateTime>, Timeslot> startAndEndTimeToTimeslotMap = new HashMap<>();

    Long timeSlotId = 0L;/*from  ww w. ja  v  a  2  s  . c o m*/
    String schedulesUrl = conferenceBaseUrl + "/schedules/";
    LOGGER.debug("Sending a request to: " + schedulesUrl);
    JsonArray daysArray = readJson(schedulesUrl, JsonReader::readObject).getJsonArray("links");
    for (int i = 0; i < daysArray.size(); i++) {
        JsonObject dayObject = daysArray.getJsonObject(i);
        String dayUrl = dayObject.getString("href");

        LOGGER.debug("Sending a request to: " + dayUrl);
        JsonArray daySlotsArray = readJson(dayUrl, JsonReader::readObject).getJsonArray("slots");

        for (int j = 0; j < daySlotsArray.size(); j++) {
            JsonObject timeslotObject = daySlotsArray.getJsonObject(j);

            LocalDateTime startDateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeslotObject.getJsonNumber("fromTimeMillis").longValue()),
                    ZoneId.of(ZONE_ID));
            LocalDateTime endDateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeslotObject.getJsonNumber("toTimeMillis").longValue()),
                    ZoneId.of(ZONE_ID));

            Room room = roomIdToRoomMap.get(timeslotObject.getString("roomId"));
            if (room == null) {
                throw new IllegalStateException("The timeslot (" + timeslotObject.getString("slotId")
                        + ") has a roomId (" + timeslotObject.getString("roomId")
                        + ") that does not exist in the rooms list");
            }

            // Assuming slotId is of format: tia_room6_monday_12_.... take only "tia"
            String talkTypeName = timeslotObject.getString("slotId").split("_")[0];
            TalkType timeslotTalkType = talkTypeNameToTalkTypeMap.get(talkTypeName);
            if (Arrays.asList(IGNORED_TALK_TYPES).contains(talkTypeName)) {
                continue;
            }

            Timeslot timeslot;
            if (startAndEndTimeToTimeslotMap.keySet().contains(Pair.of(startDateTime, endDateTime))) {
                timeslot = startAndEndTimeToTimeslotMap.get(Pair.of(startDateTime, endDateTime));
                timeslotToAvailableRoomsMap.get(timeslot).add(room);
                if (timeslotTalkType != null) {
                    timeslot.getTalkTypeSet().add(timeslotTalkType);
                }
            } else {
                timeslot = new Timeslot(timeSlotId++);
                timeslot.withStartDateTime(startDateTime).withEndDateTime(endDateTime)
                        .withTalkTypeSet(timeslotTalkType == null ? new HashSet<>()
                                : new HashSet<>(Arrays.asList(timeslotTalkType)));
                timeslot.setTagSet(new HashSet<>());

                timeslotList.add(timeslot);
                timeslotToAvailableRoomsMap.put(timeslot, new ArrayList<>(Arrays.asList(room)));
                startAndEndTimeToTimeslotMap.put(Pair.of(startDateTime, endDateTime), timeslot);
            }

            if (!timeslotObject.isNull("talk")) {
                scheduleTalk(timeslotObject, room, timeslot);
            }

            for (TalkType talkType : timeslot.getTalkTypeSet()) {
                talkType.getCompatibleTimeslotSet().add(timeslot);
            }
            timeslotTalkTypeToTotalMap.merge(talkTypeName, 1, Integer::sum);
        }
    }

    for (Room room : solution.getRoomList()) {
        room.setUnavailableTimeslotSet(timeslotList.stream()
                .filter(timeslot -> !timeslotToAvailableRoomsMap.get(timeslot).contains(room))
                .collect(Collectors.toSet()));
    }

    solution.setTimeslotList(timeslotList);
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherBeforeCalendarZoneIdOnSeveralDaysEventOf2HoursShouldWork()
        throws Exception {
    final CalendarEvent calendarEvent = setupSeveralDaysEventOn2Hours(ZoneId.of("America/Cancun"));
    final DurationReminder durationReminder = initReminderBuilder(calendarEvent).triggerBefore(0,
            TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);/* w ww  . j  a v a2s  . com*/
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE),
            is("Reminder about the event super test - 21.02.2018 23:00 - 22.02.2018 01:00 (America/Cancun)"));
    assertThat(titles.get(EN),
            is("Reminder about the event super test - 02/21/2018 23:00 - 02/22/2018 01:00 (America/Cancun)"));
    assertThat(titles.get(FR),
            is("Rappel sur l'vnement super test - 21/02/2018 23:00 - 22/02/2018 01:00 (America/Cancun)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(
            "REMINDER: The event <b>super test</b> will be from 21.02.2018 at 23:00 to 22.02.2018 at 01:00 (America/Cancun)."));
    assertThat(contents.get(EN), is(
            "REMINDER: The event <b>super test</b> will be from 02/21/2018 at 23:00 to 02/22/2018 at 01:00 (America/Cancun)."));
    assertThat(contents.get(FR), is(
            "RAPPEL : L'vnement <b>super test</b> aura lieu du 21/02/2018  23:00 au 22/02/2018  01:00 (America/Cancun)."));
}

From source file:com.amazonaws.services.kinesis.aggregators.StreamAggregator.java

/**
 * {@inheritDoc}/*from  w  w  w.  ja v  a2s .co  m*/
 */
public void aggregateEvents(List<InputEvent> events) throws Exception {
    start = System.currentTimeMillis();
    int aggregatedEventCount = 0;
    int aggregatedElementCount = 0;

    if (!online) {
        throw new Exception("Aggregator Not Initialised");
    }

    BigInteger thisSequence;
    List<AggregateData> extractedItems = null;
    OffsetDateTime eventDate = null;

    try {
        for (InputEvent event : events) {
            // reset extracted items
            extractedItems = null;

            if (event.getSequenceNumber() != null) {
                thisSequence = new BigInteger(event.getSequenceNumber());
                // ignore any records which are going backward with regard
                // to
                // the current hwm
                if (highSeq != null && highSeq.compareTo(thisSequence) != -1) {
                    ignoredRecordsBelowHWM++;
                    continue;
                }
            }

            // set the low sequence if this is the first record received
            // after a flush
            if (lowSeq == null)
                lowSeq = event.getSequenceNumber();

            // high sequence is always the latest value
            highSeq = new BigInteger(event.getSequenceNumber());

            // extract the data from the input event
            try {
                extractedItems = dataExtractor.getData(event);
            } catch (SerializationException se) {
                // customer may have elected to suppress serialisation
                // errors if the stream is expected have heterogenous data
                // on it
                if (this.raiseExceptionOnDataExtractionErrors) {
                    throw se;
                } else {
                    logWarn(String.format("Serialisation Exception Sequence %s Partition Key %s",
                            event.getSequenceNumber(), event.getPartitionKey()), se);
                }
            }

            // data extractor may have returned multiple data elements, or
            // be empty if there were serialisation problems which are
            // suppressed
            if (extractedItems != null) {
                aggregatedEventCount++;

                for (AggregateData data : extractedItems) {
                    // run the idempotency check
                    if (!this.idempotencyCheck.doProcess(event.getPartitionKey(), event.getSequenceNumber(),
                            data, event.getData())) {
                        logInfo(String.format("Ignoring Event %s as it failed Idempotency Check",
                                event.getPartitionKey()));
                        continue;
                    }

                    aggregatedElementCount++;

                    // if the data extractor didn't have a date value to
                    // extract, then use the current time
                    eventDate = data.getDate();
                    if (eventDate == null) {
                        eventDate = OffsetDateTime.now(ZoneId.of("UTC"));
                    }

                    // generate the local updates, one per time horizon that
                    // is requested
                    for (TimeHorizon h : timeHorizons) {
                        OffsetDateTime localEventDate = eventDate;
                        if (!h.isUTC())
                            localEventDate = eventDate.minus(Duration.ofMillis(data.getLocalOffset()));

                        // atomically update the aggregate table with event
                        // count or count + summaries
                        cache.update(aggregatorType, data.getLabels(),
                                (timeHorizons.size() > 1 ? h.getItemWithMultiValueFormat(localEventDate)
                                        : h.getValue(localEventDate)),
                                h, event.getSequenceNumber(), 1, data.getSummaries(),
                                dataExtractor.getSummaryConfig());
                    }
                }
            }
        }

        logInfo(String.format("Aggregation Complete - %s Records and %s Elements in %s ms",
                aggregatedEventCount, aggregatedElementCount, (System.currentTimeMillis() - start)));
    } catch (SerializationException se) {
        shutdown(true, InventoryModel.STATE.SERIALISATION_ERROR);
        LOG.error(se);
        throw se;
    } catch (Exception e) {
        shutdown(true, InventoryModel.STATE.UNKNOWN_ERROR);
        LOG.error(e);
        throw e;
    }
}

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

private void updateDateFields(RegistryPackageType rpt) {

    ExtrinsicObjectType nodeInfo = null;
    for (JAXBElement identifiable : rpt.getRegistryObjectList().getIdentifiable()) {
        RegistryObjectType registryObject = (RegistryObjectType) identifiable.getValue();

        if (registryObject instanceof ExtrinsicObjectType
                && RegistryConstants.REGISTRY_NODE_OBJECT_TYPE.equals(registryObject.getObjectType())) {
            nodeInfo = (ExtrinsicObjectType) registryObject;
            break;
        }// ww w.ja  v  a2 s .c o m
    }
    if (nodeInfo != null) {
        boolean liveDateFound = false;
        boolean lastUpdatedFound = false;

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

        for (SlotType1 slot : nodeInfo.getSlot()) {
            if (slot.getName().equals(RegistryConstants.XML_LIVE_DATE_NAME)) {
                liveDateFound = true;
            } else if (slot.getName().equals(RegistryConstants.XML_LAST_UPDATED_NAME)) {
                ValueListType valueList = EbrimConstants.RIM_FACTORY.createValueListType();
                valueList.getValue().add(rightNow);
                slot.setValueList(EbrimConstants.RIM_FACTORY.createValueList(valueList));
                lastUpdatedFound = true;
            }
        }

        if (!liveDateFound) {
            SlotType1 liveDate = slotHelper.create(RegistryConstants.XML_LIVE_DATE_NAME, rightNow, DATE_TIME);

            nodeInfo.getSlot().add(liveDate);
        }

        if (!lastUpdatedFound) {
            SlotType1 lastUpdated = slotHelper.create(RegistryConstants.XML_LAST_UPDATED_NAME, rightNow,
                    DATE_TIME);

            nodeInfo.getSlot().add(lastUpdated);
        }
    }
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherAfterCalendarZoneIdOnSeveralDaysEventOf2HoursShouldWork()
        throws Exception {
    final CalendarEvent calendarEvent = setupSeveralDaysEventOn2Hours(ZoneId.of("Asia/Muscat"));
    final DurationReminder durationReminder = initReminderBuilder(calendarEvent).triggerBefore(0,
            TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);//from  w w w .  j av  a2  s. co  m
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE),
            is("Reminder about the event super test - 21.02.2018 23:00 - 22.02.2018 01:00 (Asia/Muscat)"));
    assertThat(titles.get(EN),
            is("Reminder about the event super test - 02/21/2018 23:00 - 02/22/2018 01:00 (Asia/Muscat)"));
    assertThat(titles.get(FR),
            is("Rappel sur l'vnement super test - 21/02/2018 23:00 - 22/02/2018 01:00 (Asia/Muscat)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(
            "REMINDER: The event <b>super test</b> will be from 21.02.2018 at 23:00 to 22.02.2018 at 01:00 (Asia/Muscat)."));
    assertThat(contents.get(EN), is(
            "REMINDER: The event <b>super test</b> will be from 02/21/2018 at 23:00 to 02/22/2018 at 01:00 (Asia/Muscat)."));
    assertThat(contents.get(FR), is(
            "RAPPEL : L'vnement <b>super test</b> aura lieu du 21/02/2018  23:00 au 22/02/2018  01:00 (Asia/Muscat)."));
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testStop() throws InterruptedException {
    _wireMockRule//from  ww  w .j a  v  a2 s.  c  o  m
            .stubFor(WireMock.post(WireMock.urlEqualTo(PATH)).willReturn(WireMock.aResponse().withStatus(200)));

    final Semaphore semaphore = new Semaphore(0);
    @SuppressWarnings("unchecked")
    final ApacheHttpSink sink = (ApacheHttpSink) new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH))
            .setEventHandler(new CompletionHandler(semaphore)).build();

    final Map<String, String> annotations = new LinkedHashMap<>();
    annotations.put("foo", "bar");
    annotations.put("_start",
            Instant.now().minusMillis(812).atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT));
    annotations.put("_end", Instant.now().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT));
    annotations.put("_host", "some.host.com");
    annotations.put("_service", "myservice");
    annotations.put("_cluster", "mycluster");
    annotations.put("_id", UUID.randomUUID().toString());

    final TsdEvent event = new TsdEvent(annotations,
            createQuantityMap("timer", TsdQuantity.newInstance(123, Units.NANOSECOND)),
            createQuantityMap("counter", TsdQuantity.newInstance(8, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(10, Units.BYTE)));

    sink.stop();
    Thread.sleep(1000);
    sink.record(event);
    Assert.assertFalse(semaphore.tryAcquire(1, TimeUnit.SECONDS));

    // 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(0, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testNoEventHandler() throws InterruptedException {
    _wireMockRule//from  www  .  jav a  2  s .  c  om
            .stubFor(WireMock.post(WireMock.urlEqualTo(PATH)).willReturn(WireMock.aResponse().withStatus(200)));

    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)).build();

    final Map<String, String> annotations = new LinkedHashMap<>();
    annotations.put("foo", "bar");
    annotations.put("_start",
            Instant.now().minusMillis(812).atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT));
    annotations.put("_end", Instant.now().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT));
    annotations.put("_host", "some.host.com");
    annotations.put("_service", "myservice");
    annotations.put("_cluster", "mycluster");
    annotations.put("_id", UUID.randomUUID().toString());

    final TsdEvent event = new TsdEvent(annotations,
            createQuantityMap("timer", TsdQuantity.newInstance(123, Units.NANOSECOND)),
            createQuantityMap("counter", TsdQuantity.newInstance(8, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(10, Units.BYTE)));

    sink.record(event);
}

From source file:com.github.helenusdriver.driver.impl.DataDecoder.java

/**
 * Gets an element decoder that can be used to convert a Cassandra
 * returned data type into another data type based on special supported
 * combinations./*  w  ww  . j a v  a2s. c  om*/
 *
 * @author paouelle
 *
 * @param  eclass the non-<code>null</code> element class to decode to
 * @param  reclass the non-<code>null</code> row's element class
 * @return a non-<code>null</code> element decoder for the provided combination
 * @throws IllegalArgumentException if the combination is not supported
 */
@SuppressWarnings("rawtypes")
static ElementConverter getConverter(final Class eclass, Class reclass) {
    if (Enum.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @SuppressWarnings("unchecked")
            @Override
            public Object convert(Object re) {
                return Enum.valueOf(eclass, (String) re);
            }
        };
    } else if (Locale.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return LocaleUtils.toLocale((String) re);
            }
        };
    } else if (ZoneId.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                try {
                    return ZoneId.of((String) re);
                } catch (DateTimeException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        };
    } else if (eclass.isArray() && (Byte.TYPE == eclass.getComponentType())
            && ByteBuffer.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return Bytes.getArray((ByteBuffer) re);
            }
        };
    } else if ((Long.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).getTime();
            }
        };
    } else if ((Instant.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).toInstant();
            }
        };
    } else if (eclass == reclass) { // special case for maps
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return re;
            }
        };
    }
    throw new IllegalArgumentException(
            "unsupported element conversion from: " + reclass.getName() + " to: " + eclass.getName());
}

From source file:nu.yona.server.device.service.DeviceServiceTestConfiguration.java

private Activity makeActivity(LocalDateTime startTime, ActivityData activityData, UserDevice device) {
    LocalDateTime activityStartTime = startTime.minusMinutes(activityData.minutesAgo);
    return activityRepository.save(Activity.createInstance(device.getDeviceAnonymized(),
            ZoneId.of("Europe/Amsterdam"), activityStartTime,
            activityStartTime.plusMinutes(activityData.durationMinutes), Optional.of(activityData.app)));
}

From source file:alfio.manager.TicketReservationManager.java

private void acquireItems(TicketStatus ticketStatus, AdditionalServiceItemStatus asStatus,
        PaymentProxy paymentProxy, String reservationId, String email, CustomerName customerName,
        String userLanguage, String billingAddress, int eventId) {
    Map<Integer, Ticket> preUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream()
            .collect(toMap(Ticket::getId, Function.identity()));
    int updatedTickets = ticketRepository.updateTicketsStatusWithReservationId(reservationId,
            ticketStatus.toString());//from   ww w . j  ava2  s  .  c o m
    Map<Integer, Ticket> postUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream()
            .collect(toMap(Ticket::getId, Function.identity()));

    postUpdateTicket.forEach((id, ticket) -> {
        auditUpdateTicket(preUpdateTicket.get(id), Collections.emptyMap(), ticket, Collections.emptyMap(),
                eventId);
    });

    int updatedAS = additionalServiceItemRepository.updateItemsStatusWithReservationUUID(reservationId,
            asStatus);
    Validate.isTrue(updatedTickets + updatedAS > 0, "no items have been updated");
    specialPriceRepository.updateStatusForReservation(singletonList(reservationId), Status.TAKEN.toString());
    ZonedDateTime timestamp = ZonedDateTime.now(ZoneId.of("UTC"));
    int updatedReservation = ticketReservationRepository.updateTicketReservation(reservationId,
            TicketReservationStatus.COMPLETE.toString(), email, customerName.getFullName(),
            customerName.getFirstName(), customerName.getLastName(), userLanguage, billingAddress, timestamp,
            paymentProxy.toString());
    Validate.isTrue(updatedReservation == 1,
            "expected exactly one updated reservation, got " + updatedReservation);
    waitingQueueManager.fireReservationConfirmed(reservationId);
    if (paymentProxy == PaymentProxy.PAYPAL || paymentProxy == PaymentProxy.ADMIN) {
        //we must notify the plugins about ticket assignment and send them by email
        Event event = eventRepository.findByReservationId(reservationId);
        TicketReservation reservation = findById(reservationId).orElseThrow(IllegalStateException::new);
        findTicketsInReservation(reservationId).stream()
                .filter(ticket -> StringUtils.isNotBlank(ticket.getFullName())
                        || StringUtils.isNotBlank(ticket.getFirstName())
                        || StringUtils.isNotBlank(ticket.getEmail()))
                .forEach(ticket -> {
                    Locale locale = Locale.forLanguageTag(ticket.getUserLanguage());
                    if (paymentProxy == PaymentProxy.PAYPAL) {
                        sendTicketByEmail(ticket, locale, event,
                                getTicketEmailGenerator(event, reservation, locale));
                    }
                    pluginManager.handleTicketAssignment(ticket);
                    extensionManager.handleTicketAssignment(ticket);
                });

    }
}