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:com.amazonaws.services.kinesis.io.JsonDataExtractor.java

/**
 * {@inheritDoc}//w w  w . j  av  a2  s .c  o m
 */
@Override
public List<AggregateData> getData(InputEvent event) throws SerializationException {
    try {
        List<AggregateData> aggregateData = new ArrayList<>();
        OffsetDateTime dateValue = null;
        JsonNode jsonContent = null;
        String dateString, summary = null;
        long localOffset = 0;

        List<String> items = (List<String>) serialiser.toClass(event);

        // log a warning if we didn't get anything back from the serialiser
        // - this could be OK, but probably isn't
        // it would be OK, for example, if you have filterRegex
        //            if (items == null || items.size() == 0)
        //                LOG.warn(String.format(
        //                        "Failed to deserialise any content for Record (Partition Key %s, Sequence %s",
        //                        event.getPartitionKey(), event.getSequenceNumber()));

        // process all the items returned by the serialiser
        for (String item : items) {
            // Convert the string to a Jackson JsonNode for navigation
            jsonContent = StreamAggregatorUtils.asJsonNode(item);
            sumUpdates = new HashMap<>();

            LabelSet labels = new LabelSet();
            for (String key : this.labelAttributes) {
                labels.put(key, StreamAggregatorUtils.readValueAsString(jsonContent, key));
            }

            // get the unique ID for the event
            String uniqueId = null;
            if (this.uniqueIdAttribute != null) {
                switch (this.uniqueIdAttribute) {
                case StreamAggregator.REF_PARTITION_KEY:
                    uniqueId = event.getPartitionKey();
                    break;
                case StreamAggregator.REF_SEQUENCE:
                    uniqueId = event.getSequenceNumber();
                    break;
                default:
                    uniqueId = StreamAggregatorUtils.readValueAsString(jsonContent, uniqueIdAttribute);
                    break;
                }
            }

            // get the date value from the line
            if (dateValueAttribute != null) {
                dateString = StreamAggregatorUtils.readValueAsString(jsonContent, dateValueAttribute);

                // bail on no date returned
                if (dateString == null || dateString.equals(""))
                    throw new SerializationException(
                            String.format("Unable to read date value attribute %s from JSON Content %s",
                                    dateValueAttribute, item));

                // turn date as long or string into Date
                if (this.dateFormat != null) {
                    dateValue = OffsetDateTime.parse(dateString, dateFormatter);
                } else {
                    // no formatter, so treat as epoch seconds
                    try {
                        dateValue = OffsetDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateString)),
                                ZoneId.of("UTC"));
                    } catch (Exception e) {
                        LOG.error(String.format(
                                "Unable to create Date Value element from item '%s' due to invalid format as Epoch Seconds",
                                dateValueAttribute));
                        throw new SerializationException(e);
                    }
                }
            } else {
                // no date value attribute configured, so use now
                dateValue = OffsetDateTime.now(ZoneId.of("UTC"));
            }

            // get the summed values
            if (this.aggregatorType.equals(AggregatorType.SUM)) {
                // get the positional sum items
                for (String s : summaryConfig.getItemSet()) {
                    try {
                        summary = StreamAggregatorUtils.readValueAsString(jsonContent, s);

                        // if a summary is not found in the data element,
                        // then we simply continue without it
                        if (summary != null)
                            sumUpdates.put(s, Double.parseDouble(summary));
                    } catch (NumberFormatException nfe) {
                        LOG.error(String
                                .format("Unable to deserialise Summary '%s' due to NumberFormatException", s));
                        throw new SerializationException(nfe);
                    }
                }
            }

            // get local offset
            if (offsetAttribute != null) {
                try {
                    String offsetString = StreamAggregatorUtils.readValueAsString(jsonContent, offsetAttribute);
                    if (offsetString != null)
                        localOffset = Long.parseLong(offsetString);
                } catch (NumberFormatException nfe) {
                    LOG.error(String.format(
                            "Unable to deserialise local offset '%s' due to NumberFormatException",
                            dateValueAttribute));
                    throw new SerializationException(nfe);
                }
            }

            aggregateData.add(new AggregateData(uniqueId, labels, dateValue, sumUpdates, localOffset));
        }

        return aggregateData;
    } catch (Exception e) {
        throw new SerializationException(e);
    }
}

From source file:alfio.datamapper.QueryType.java

private static SqlParameterSource extractParameters(Method m, Object[] args) {

    Annotation[][] parameterAnnotations = m.getParameterAnnotations();
    if (parameterAnnotations == null || parameterAnnotations.length == 0) {
        return new EmptySqlParameterSource();
    }// ww  w . j a  v a  2 s .c o m

    MapSqlParameterSource ps = new MapSqlParameterSource();
    Class<?>[] parameterTypes = m.getParameterTypes();
    for (int i = 0; i < args.length; i++) {
        String name = parameterName(parameterAnnotations[i]);
        if (name != null) {
            if (args[i] != null && ZonedDateTime.class.isAssignableFrom(parameterTypes[i])) {
                ZonedDateTime dateTime = ZonedDateTime.class.cast(args[i]);
                final ZonedDateTime utc = dateTime.withZoneSameInstant(ZoneId.of("UTC"));
                Calendar c = Calendar.getInstance();
                c.setTimeZone(TimeZone.getTimeZone("UTC"));
                c.setTimeInMillis(utc.toInstant().toEpochMilli());
                ps.addValue(name, c, Types.TIMESTAMP);
            } else {
                ps.addValue(name, args[i], StatementCreatorUtils.javaTypeToSqlParameterType(parameterTypes[i]));
            }
        }
    }

    return ps;
}

From source file:com.streamsets.pipeline.stage.processor.parser.sql.SqlParserProcessor.java

@Override
public List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();
    errorRecordHandler = new DefaultErrorRecordHandler(getContext());
    if (configBean.resolveSchema) {
        issues = configBean.hikariConfigBean.init(getContext(), issues);
        if (issues.isEmpty() && connection == null) {
            try {
                dataSource = jdbcUtil.createDataSourceForRead(configBean.hikariConfigBean.getUnderlying());
                connection = dataSource.getConnection();
                connection.setAutoCommit(false);
            } catch (StageException | SQLException e) {
                LOG.error("Error while connecting to DB", e);
                issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STR, JDBC_00,
                        e.toString()));//ww w  .  ja  v a 2  s .c om
                return issues;
            }
        }
    }
    dateTimeColumnHandler = new DateTimeColumnHandler(ZoneId.of(configBean.dbTimeZone), configBean.dateFormat,
            configBean.localDatetimeFormat, configBean.zonedDatetimeFormat);
    return issues;
}

From source file:com.github.lburgazzoli.camel.CaseToIncidentProcessor.java

private Date zonedDateTimeToDate(ZonedDateTime zdt) {
    return zdt != null ? Date.from(zdt.withZoneSameInstant(ZoneId.of("UTC")).toInstant()) : null;
}

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

@Test
public void textShouldContainsSubjectsWhenSubjects() throws Exception {
    MailboxMessage mailboxMessage = mock(MailboxMessage.class);
    TestId mailboxId = TestId.of(1);/*from  ww  w  .  j a v  a 2s  .  co  m*/
    when(mailboxMessage.getMailboxId()).thenReturn(mailboxId);
    when(mailboxMessage.getFullContent())
            .thenReturn(new ByteArrayInputStream("Subject: subject1\nSubject: subject2".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("subject1 subject2");
}

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

@Test
public void pgpSignedEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage pgpSignedMail = new SimpleMailboxMessage(MESSAGE_ID, date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/pgpSignedMail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    pgpSignedMail.setModSeq(MOD_SEQ);//from   www  . j  a v a  2  s  .  c  o m
    pgpSignedMail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(pgpSignedMail,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/pgpSignedMail.json")));
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthDataPointMapper.java

/**
 * @param dateTimeInUnixSecondsWithLocalTimeOffset A unix epoch timestamp in local time.
 * @param timeZoneString The time zone offset as a String (e.g., "+0200","-2").
 * @return The date time with the correct offset.
 *//*ww  w  .  j a  va 2 s  .  c  o m*/
protected static OffsetDateTime getDateTimeAtStartOfDayWithCorrectOffset(
        Long dateTimeInUnixSecondsWithLocalTimeOffset, String timeZoneString) {

    // Since the timestamps are in local time, we can use the local date time provided by rendering the timestamp
    // in UTC, then translating that local time to the appropriate offset.
    OffsetDateTime dateTimeFromOffsetInstant = ofInstant(
            ofEpochSecond(dateTimeInUnixSecondsWithLocalTimeOffset), ZoneId.of("Z"));

    return dateTimeFromOffsetInstant.toLocalDate().atStartOfDay().atOffset(ZoneOffset.of(timeZoneString));
}

From source file:org.dhatim.fastexcel.Correctness.java

@Test
public void singleWorksheet() throws Exception {
    String sheetName = "Worksheet 1";
    String stringValue = "Sample text with chars to escape : < > & \\ \" ' ~        ";
    Date dateValue = new Date();
    LocalDateTime localDateTimeValue = LocalDateTime.now();
    ZoneId timezone = ZoneId.of("Australia/Sydney");
    ZonedDateTime zonedDateValue = ZonedDateTime.ofInstant(dateValue.toInstant(), timezone);
    double doubleValue = 1.234;
    int intValue = 2_016;
    long longValue = 2_016_000_000_000L;
    BigDecimal bigDecimalValue = BigDecimal.TEN;
    byte[] data = writeWorkbook(wb -> {
        Worksheet ws = wb.newWorksheet(sheetName);
        int i = 1;
        ws.value(i, i++, stringValue);/*  w w w . j a va 2s  .  c  o m*/
        ws.value(i, i++, dateValue);
        ws.value(i, i++, localDateTimeValue);
        ws.value(i, i++, zonedDateValue);
        ws.value(i, i++, doubleValue);
        ws.value(i, i++, intValue);
        ws.value(i, i++, longValue);
        ws.value(i, i++, bigDecimalValue);
        try {
            ws.finish();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    // Check generated workbook with Apache POI
    XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(data));
    assertThat(xwb.getActiveSheetIndex()).isEqualTo(0);
    assertThat(xwb.getNumberOfSheets()).isEqualTo(1);
    XSSFSheet xws = xwb.getSheet(sheetName);
    @SuppressWarnings("unchecked")
    Comparable<XSSFRow> row = (Comparable) xws.getRow(0);
    assertThat(row).isNull();
    int i = 1;
    assertThat(xws.getRow(i).getCell(i++).getStringCellValue()).isEqualTo(stringValue);
    assertThat(xws.getRow(i).getCell(i++).getDateCellValue()).isEqualTo(dateValue);
    // Check zoned timestamps have the same textual representation as the Dates extracted from the workbook
    // (Excel date serial numbers do not carry timezone information)
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTimeValue));
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(zonedDateValue));
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(doubleValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(intValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(longValue);
    assertThat(new BigDecimal(xws.getRow(i).getCell(i++).getRawValue())).isEqualTo(bigDecimalValue);
}

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

@Test
public void simpleEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage mail = new SimpleMailboxMessage(date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/mail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    mail.setModSeq(MOD_SEQ);/*from  w ww  . j  a  va 2 s . c o m*/
    mail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mail,
            ImmutableList.of(new MockMailboxSession("user1").getUser(),
                    new MockMailboxSession("user2").getUser()))).when(IGNORING_ARRAY_ORDER)
                            .when(IGNORING_VALUES)
                            .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/mail.json")));
}