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.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void htmlEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage htmlMail = new SimpleMailboxMessage(MESSAGE_ID, 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);//w w  w .  ja  v a 2 s .co m
    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:io.stallion.dataAccess.file.TextFilePersister.java

public T fromString(String fileContent, Path fullPath) {
    if (fullPath.toString().endsWith(".html") || fullPath.toString().endsWith(".htm")) {
        return fromHtml(fileContent, fullPath);
    }//from ww  w . j a v a2s.co  m
    String relativePath = fullPath.toString().replace(getBucketFolderPath(), "");
    Path path = fullPath;

    T item = null;
    try {
        item = getModelClass().newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    item.setTags(new ArrayList<String>()).setElementById(new HashMap<>()).setElements(new ArrayList<>())
            .setPublishDate(ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC"))).setTitle("")
            .setDraft(false).setTemplate("").setContent("").setSlug("");

    /* Get the id and slug */

    item.setSlug(FilenameUtils.removeExtension(relativePath));
    if (!item.getSlug().startsWith("/")) {
        item.setSlug("/" + item.getSlug());
    }
    if (item.getSlug().endsWith("/index")) {
        item.setSlug(item.getSlug().substring(item.getSlug().length() - 6));
    }

    if (empty(fileContent.trim())) {
        return item;
    }

    /* Parse out toml properties, if found */
    String tomlContent;
    Matcher tomlMatcher = tomlPattern.matcher(fileContent);
    if (tomlMatcher.find()) {
        tomlContent = tomlMatcher.group(1).trim();
        fileContent = tomlMatcher.replaceAll("\n");
        Map tomlMap = new Toml().read(tomlContent).to(HashMap.class);
        for (Object key : tomlMap.keySet()) {
            Object value = tomlMap.get(key);
            setProperty(item, key.toString(), value);
        }
    }

    List<String> allLines = Arrays.asList(fileContent.split("\n"));

    if (allLines.size() == 0) {
        return item;
    }

    if (empty(item.getTitle())) {
        item.setTitle(allLines.get(0));
    }

    String titleLine = "";
    List<String> propertiesSection = list();
    String rawContent = "";
    int propertiesStartAt = 0;
    if (allLines.size() > 1) {
        if (allLines.get(1).startsWith("----") || allLines.get(1).startsWith("====")) {
            titleLine = allLines.get(0);
            propertiesStartAt = 2;
            item.setTitle(titleLine);
        }
    }

    int propertiesEndAt = propertiesStartAt;
    for (; propertiesEndAt < allLines.size(); propertiesEndAt++) {
        String line = allLines.get(propertiesEndAt);
        if (line.trim().equals("---")) {
            continue;
        }
        int colon = line.indexOf(':');
        if (colon == -1) {
            break;
        }
        String key = line.substring(0, colon).trim();
        String value = line.substring(colon + 1, line.length()).trim();
        if ("oldUrls".equals(key)) {
            setProperty(item, key, apply(list(StringUtils.split(value, ";")), (aUrl) -> aUrl.trim()));
        } else {
            setProperty(item, key, value);
        }
    }
    if (propertiesEndAt < allLines.size()) {
        rawContent = StringUtils.join(allLines.subList(propertiesEndAt, allLines.size()), "\n").trim();
    }

    Boolean isMarkdown = false;
    if (path.toString().toLowerCase().endsWith(".txt") || path.toString().toLowerCase().endsWith(".md")) {
        isMarkdown = true;
    }
    item.setElements(StElementParser.parseElements(rawContent, isMarkdown));
    List<StElement> items = item.getElements();
    for (StElement ele : items) {
        item.getElementById().put(ele.getId(), ele);
    }

    String itemContent = StElementParser.removeTags(rawContent).trim();
    item.setOriginalContent(itemContent);

    if (isMarkdown) {
        Log.fine("Parse for page {0} {1} {2}", item.getId(), item.getSlug(), item.getTitle());
        String cacheKey = DigestUtils.md5Hex("markdown-to-html" + Literals.GSEP + itemContent);
        String cached = null;
        if (!"test".equals(Settings.instance().getEnv())) {
            cached = PermaCache.get(cacheKey);
        }
        if (cached == null) {
            itemContent = Markdown.instance().process(itemContent);
            PermaCache.set(cacheKey, itemContent);
        } else {
            itemContent = cached;
        }

        item.setContent(itemContent);
    }

    if (empty(item.getId())) {
        item.setId(makeIdFromFilePath(relativePath));
    }

    Log.fine("Loaded text item: id:{0} slug:{1} title:{2} draft:{3}", item.getId(), item.getSlug(),
            item.getTitle(), item.getDraft());
    return item;
}

From source file:com.streamsets.pipeline.stage.cloudstorage.destination.GoogleCloudStorageTarget.java

@Override
public void write(Batch batch) throws StageException {
    String pathExpression = GcsUtil.normalizePrefix(gcsTargetConfig.commonPrefix)
            + gcsTargetConfig.partitionTemplate;
    if (gcsTargetConfig.dataFormat == DataFormat.WHOLE_FILE) {
        handleWholeFileFormat(batch, elVars);
    } else {//from www  .  j  av a  2s.  c om
        Multimap<String, Record> pathToRecordMap = ELUtils.partitionBatchByExpression(partitionEval, elVars,
                pathExpression, timeDriverElEval, elVars, gcsTargetConfig.timeDriverTemplate,
                Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(gcsTargetConfig.timeZoneID))), batch);

        pathToRecordMap.keySet().forEach(path -> {
            Collection<Record> records = pathToRecordMap.get(path);
            String fileName = GcsUtil.normalizePrefix(path) + gcsTargetConfig.fileNamePrefix + '_'
                    + UUID.randomUUID();
            if (StringUtils.isNotEmpty(gcsTargetConfig.fileNameSuffix)) {
                fileName = fileName + "." + gcsTargetConfig.fileNameSuffix;
            }
            try {
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                OutputStream os = bOut;
                if (gcsTargetConfig.compress) {
                    fileName = fileName + ".gz";
                    os = new GZIPOutputStream(bOut);
                }
                BlobId blobId = BlobId.of(gcsTargetConfig.bucketTemplate, fileName);
                BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(getContentType()).build();
                final AtomicInteger recordsWithoutErrors = new AtomicInteger(0);
                try (DataGenerator dg = gcsTargetConfig.dataGeneratorFormatConfig.getDataGeneratorFactory()
                        .getGenerator(os)) {
                    records.forEach(record -> {
                        try {
                            dg.write(record);
                            recordsWithoutErrors.incrementAndGet();
                        } catch (DataGeneratorException | IOException e) {
                            LOG.error("Error writing record {}. Reason {}", record.getHeader().getSourceId(),
                                    e);
                            getContext().toError(record, Errors.GCS_02, record.getHeader().getSourceId(), e);
                        }
                    });
                } catch (IOException e) {
                    LOG.error("Error happened when creating Output stream. Reason {}", e);
                    records.forEach(record -> getContext().toError(record, e));
                }

                try {
                    if (recordsWithoutErrors.get() > 0) {
                        Blob blob = storage.create(blobInfo, bOut.toByteArray());
                        GCSEvents.GCS_OBJECT_WRITTEN.create(getContext())
                                .with(GCSEvents.BUCKET, blob.getBucket())
                                .with(GCSEvents.OBJECT_KEY, blob.getName())
                                .with(GCSEvents.RECORD_COUNT, recordsWithoutErrors.longValue()).createAndSend();
                    }
                } catch (StorageException e) {
                    LOG.error("Error happened when writing to Output stream. Reason {}", e);
                    records.forEach(record -> getContext().toError(record, e));
                }
            } catch (IOException e) {
                LOG.error("Error happened when creating Output stream. Reason {}", e);
                records.forEach(record -> getContext().toError(record, e));
            }
        });
    }
}

From source file:org.openmhealth.shim.googlefit.mapper.GoogleFitDataPointMapper.java

/**
 * Converts a nanosecond timestamp from the Google Fit API into an offset datetime value.
 *
 * @param unixEpochNanosString the timestamp directly from the Google JSON document
 * @return an offset datetime object representing the input timestamp
 *//*w w  w  .j av a 2s  .  c om*/
public OffsetDateTime convertGoogleNanosToOffsetDateTime(String unixEpochNanosString) {

    return OffsetDateTime.ofInstant(Instant.ofEpochSecond(0, Long.parseLong(unixEpochNanosString)),
            ZoneId.of("Z"));
}

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

@Test
public void textShouldContainsBccWhenBcc() throws Exception {
    MailboxMessage mailboxMessage = mock(MailboxMessage.class);
    TestId mailboxId = TestId.of(1);//  w  ww  . j a v a2s .  co  m
    when(mailboxMessage.getMailboxId()).thenReturn(mailboxId);
    when(mailboxMessage.getFullContent()).thenReturn(new ByteArrayInputStream(
            "Bcc: First bcc <user@james.org>\nBcc: Second bcc <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("Second bcc user2@james.org First bcc user@james.org");
}

From source file:ox.softeng.burst.services.BurstService.java

public void generateStartupMessage() {
    Message message = new Message("burst-service", "Burst Service starting\n" + version(),
            SeverityEnum.INFORMATIONAL, OffsetDateTime.now(ZoneId.of("UTC")), "Burst Service Startup");
    message.addTopic("service");
    message.addTopic("startup");
    message.addTopic("burst");
    message.addMetadata("gmc", "gel");
    message.addMetadata("burst_service_version", version());

    try {//from  w  ww .j ava 2s.  c  o m
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.merge(message);
        entityManager.getTransaction().commit();
        entityManager.close();
    } catch (HibernateException he) {
        logger.error("Could not save startup message to database: " + he.getMessage(), he);
    } catch (Exception e) {
        logger.error("Unhandled exception trying to process startup message", e);
    }
}

From source file:com.amazonaws.services.kinesis.io.StringDataExtractor.java

/**
 * {@inheritDoc}/*w  w w .  j  av a  2s  .c o m*/
 */
@Override
public List<AggregateData> getData(InputEvent event) throws SerializationException {
    try {
        int summaryIndex = -1;
        String dateString;
        OffsetDateTime dateValue;
        List<AggregateData> data = new ArrayList<>();

        List<List<String>> content = serialiser.toClass(event);
        for (List<String> line : content) {
            if (line != null) {
                LabelSet labels = new LabelSet();
                labels.withAlias(this.labelAttributeAlias);

                for (Integer key : this.labelIndicies) {
                    labels.put("" + key, line.get(key));
                }

                // get the unique index
                String uniqueId = null;
                if (this.usePartitionKeyForUnique) {
                    uniqueId = event.getPartitionKey();
                } else if (this.useSequenceForUnique) {
                    uniqueId = event.getSequenceNumber();
                } else {
                    if (this.uniqueIdIndex != -1) {
                        uniqueId = line.get(this.uniqueIdIndex);
                    }
                }

                // get the date value from the line
                if (this.dateValueIndex != -1) {
                    dateString = line.get(dateValueIndex);
                    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",
                                    dateValueIndex));
                            throw new SerializationException(e);
                        }
                    }
                } else {
                    dateValue = OffsetDateTime.now(ZoneId.of("UTC"));
                }

                // get the summed values
                if (this.aggregatorType.equals(AggregatorType.SUM)) {
                    sumUpdates = new HashMap<>();

                    // get the positional sum items
                    for (int i = 0; i < summaryIndicies.size(); i++) {
                        summaryIndex = summaryIndicies.get(i);
                        try {
                            sumUpdates.put("" + summaryIndex, Double.parseDouble(line.get(summaryIndex)));
                        } catch (NumberFormatException nfe) {
                            LOG.error(String.format(
                                    "Unable to deserialise Summary '%s' due to NumberFormatException", i));
                            throw new SerializationException(nfe);
                        }
                    }
                }

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

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

}

From source file:org.caratarse.auth.model.dao.UserAttributesTest.java

@Test
public void lastUserAttribute() {
    User user = retrieveUserWithAttributes();
    Attribute attribute = user.getUserAttributes().get("last");
    assertTrue(attribute instanceof DateTimeAttribute);
    assertThat(attribute.getName(), is("last"));
    final Date value = new Date(((Date) attribute.getValue()).getTime());
    ZonedDateTime v = value.toInstant().atZone(ZoneId.of("UTC"));
    assertThat(v.getDayOfMonth(), is(20));
    assertThat(v.getMonthValue(), is(11));
    assertThat(v.getYear(), is(2015));//  ww  w.  ja va 2 s. c om
    assertThat(v.getHour(), is(12));
    assertThat(v.getMinute(), is(11));
    assertThat(v.getSecond(), is(10));
    assertThat(v.getNano(), is(999000000));
}

From source file:it.tidalwave.northernwind.frontend.filesystem.impl.ResourceFileNetBeansPlatform.java

@Override
@Nonnull/* w  w  w .ja va 2 s  . c  o m*/
public ZonedDateTime getLatestModificationTime() {
    // See NW-154
    final File file = toFile();

    final long millis = (file != null) ? file.lastModified() : delegate.lastModified().getTime();
    return Instant.ofEpochMilli(millis).atZone(ZoneId.of("GMT"));
}

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

@Test
public void pgpSignedEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage pgpSignedMail = new SimpleMailboxMessage(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);/* ww  w  .j a v  a  2s  .  c  om*/
    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")));
}