Example usage for java.time ZonedDateTime parse

List of usage examples for java.time ZonedDateTime parse

Introduction

In this page you can find the example usage for java.time ZonedDateTime parse.

Prototype

public static ZonedDateTime parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of ZonedDateTime from a text string using a specific formatter.

Usage

From source file:io.stallion.dataAccess.file.TextFilePersister.java

protected void setProperty(TextItem item, String key, Object value) {
    if (key.equals("slug")) {
        item.setSlug(value.toString());/*  w w  w .  j  av  a2 s .c  o m*/
    } else if (key.equals("title")) {
        item.setTitle(value.toString());
    } else if (key.equals("publishDate")) {
        for (DateTimeFormatter formatter : localDateFormats) {
            if (item.getSlug().equals("/future-dated")) {
                Log.info("future");
            }
            try {
                LocalDateTime dt = LocalDateTime.parse(value.toString(), formatter);
                ZoneId zoneId = ZoneId.systemDefault();
                if (Context.getSettings() != null && Context.getSettings().getTimeZoneId() != null) {
                    zoneId = Context.getSettings().getTimeZoneId();
                }
                item.setPublishDate(ZonedDateTime.of(dt, zoneId));
                return;
            } catch (DateTimeParseException e) {

            }
        }
        for (DateTimeFormatter formatter : zonedDateFormats) {
            try {
                ZonedDateTime dt = ZonedDateTime.parse(value.toString(), formatter);
                item.setPublishDate(dt);
                return;
            } catch (DateTimeParseException e) {

            }
        }

    } else if (key.equals("draft")) {
        item.setDraft(value.equals("true"));
    } else if (key.equals("template")) {
        item.setTemplate(value.toString());
    } else if (key.equals("author")) {
        item.setAuthor(value.toString());
    } else if (key.equals("tags")) {
        if (value instanceof List) {
            item.setTags((List<String>) value);
        } else {
            ArrayList<String> tags = new ArrayList<String>();
            for (String tag : value.toString().split("(;|,)")) {
                tags.add(tag.trim());
            }
            item.setTags(tags);

        }
    } else if (key.equals("contentType")) {
        item.setContentType(value.toString());
    } else {
        item.put(key, value);
    }

}

From source file:org.wso2.carbon.uuf.internal.io.StaticResolver.java

private ZonedDateTime getIfModifiedSinceDate(HttpRequest request) {
    // If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
    String ifModifiedSinceHeader = request.getHeaders().get("If-Modified-Since");
    if (ifModifiedSinceHeader == null) {
        return null; // 'If-Modified-Since' does not exists in HTTP headres.
    }/* w  w  w  . ja  v a2  s  .com*/
    try {
        return ZonedDateTime.parse(ifModifiedSinceHeader, HTTP_DATE_FORMATTER);
    } catch (DateTimeParseException e) {
        log.error("Cannot parse 'If-Modified-Since' HTTP header value '" + ifModifiedSinceHeader + "'.", e);
        return null;
    }
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java

public long parseTimestamp(String timestamp) {
    String definedPattern = properties.get(TIMESTAMP_PATTERN);
    if (definedPattern != null) {
        DateTimeFormatter formatter = null;
        try {//from   ww  w. j  av  a 2s.co m
            formatter = DateTimeFormatter.ofPattern(definedPattern);
            return ZonedDateTime.parse(timestamp, formatter).toInstant().toEpochMilli();
        } catch (Exception e) {
            log.debugf("Not able to parse [%s] with format [%s]", timestamp, formatter);
        }
    }
    for (DateTimeFormatter formatter : DEFAULT_DATE_FORMATS) {
        try {
            return ZonedDateTime.parse(timestamp, formatter).toInstant().toEpochMilli();
        } catch (Exception e) {
            log.debugf("Not able to parse [%s] with format [%s]", timestamp, formatter);
        }
    }
    try {
        return new Long(timestamp).longValue();
    } catch (Exception e) {
        log.debugf("Not able to parse [%s] as plain timestamp", timestamp);
    }
    return System.currentTimeMillis();
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

/**
 * Set jcr:data property to a temporary binary for a rendition resource.
 *
 * @param resource Resource/*ww w. j  a  va 2s. com*/
 * @param rawResponseLastModified String
 * @throws RepositoryException exception
 */
private void setNodeJcrDataProperty(final ResourceResolver remoteAssetsResolver, final Resource resource,
        final String rawResponseLastModified) throws RepositoryException {
    ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
    // first checking to make sure existing resource has lastModified and jcr:data properties then seeing if binaries
    // should be updated based off of whether the resource's lastModified matches the JSON's lastModified
    if (resourceProperties.get(JcrConstants.JCR_LASTMODIFIED) != null
            && resourceProperties.get(JcrConstants.JCR_DATA) != null
            && StringUtils.isNotEmpty(rawResponseLastModified)) {

        String resourceLastModified = resourceProperties.get(JcrConstants.JCR_LASTMODIFIED, String.class);
        Calendar remoteLastModified = GregorianCalendar
                .from(ZonedDateTime.parse(rawResponseLastModified, DATE_TIME_FORMATTER));

        ValueFactory valueFactory = remoteAssetsResolver.adaptTo(Session.class).getValueFactory();
        if (resourceLastModified.equals(valueFactory.createValue(remoteLastModified).getString())) {
            LOG.debug("Not creating binary for resource '{}' because binary has not been updated.",
                    resource.getPath());
            return;
        }
    }

    InputStream inputStream = getRemoteAssetPlaceholder(resource);
    try {
        resourceProperties.put(JcrConstants.JCR_DATA, inputStream);
        LOG.debug("Binary added for resource '{}'.", resource.getPath());
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ie) {
            LOG.error("IOException thrown {}", ie);
        }
    }
}

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

private void assertFormat(String initialDate, String formatPattern) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern);

    final ZonedDateTime date;
    date = ZonedDateTime.parse(initialDate, formatter);

    String formattedDate = formatter.format(date);

    assertEquals(initialDate, formattedDate);
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

/**
 * Set a simple resource property from the fetched JSON.
 *
 * @param value Object/*  w  w  w .j a v  a  2 s  .  c  o m*/
 * @param key String
 * @param resource Resource
 * @throws RepositoryException exception
 */
private void setNodeSimpleProperty(final JsonPrimitive value, final String key, final Resource resource)
        throws RepositoryException {
    ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
    if (value.isString() && DATE_REGEX.matcher(value.getAsString()).matches()) {
        try {
            resourceProperties.put(key,
                    GregorianCalendar.from(ZonedDateTime.parse(value.getAsString(), DATE_TIME_FORMATTER)));
        } catch (DateTimeParseException e) {
            LOG.warn("Unable to parse date '{}' for property:resource '{}'.", value,
                    key + ":" + resource.getPath());
        }
    } else if (value.isString() && DECIMAL_REGEX.matcher(value.getAsString()).matches()) {
        resourceProperties.put(key, value.getAsBigDecimal());
    } else if (value.isBoolean()) {
        resourceProperties.put(key, value.getAsBoolean());
    } else if (value.isNumber()) {
        if (DECIMAL_REGEX.matcher(value.getAsString()).matches()) {
            resourceProperties.put(key, value.getAsBigDecimal());
        } else {
            resourceProperties.put(key, value.getAsLong());
        }
    } else if (value.isJsonNull()) {
        resourceProperties.remove(key);
    } else {
        resourceProperties.put(key, value.getAsString());
    }

    LOG.trace("Property '{}' added for resource '{}'.", key, resource.getPath());
}

From source file:io.stallion.dataAccess.filtering.FilterChain.java

/**
 * Hydrate the FilterOperation.typedValue based on gueessing or reflecting
 * on the type of the property as passed in.
 *
 * @param op//ww w  .  ja v  a2s  .  co  m
 * @param propValue
 */
private void hydrateTypedValue(FilterOperation op, Object propValue) {
    if (op.getTypedValue() != null) {
        return;
    }
    if (op.getOriginalValue() == null) {
        return;
    }
    if (op.getOriginalValue().getClass().equals(propValue.getClass())) {
        op.setTypedValue(op.getOriginalValue());
        return;
    }
    if (op.getOriginalValue().getClass().equals(String.class)) {
        String val = (String) op.getOriginalValue();
        if (propValue != null) {
            if (propValue instanceof Enum) {
                op.setTypedValue(Enum.valueOf((Class<? extends Enum>) propValue.getClass(), val));
            } else if (propValue instanceof ZonedDateTime) {
                if (((String) op.getOriginalValue()).length() == 16) {
                    op.setTypedValue(ZonedDateTime.parse((String) op.getOriginalValue() + ":00 UTC",
                            DateUtils.SQL_FORMAT_ZONED));
                } else if (((String) op.getOriginalValue()).length() == 19) {
                    op.setTypedValue(ZonedDateTime.parse((String) op.getOriginalValue() + " UTC",
                            DateUtils.SQL_FORMAT_ZONED));
                } else {
                    op.setTypedValue(ZonedDateTime.parse((String) op.getOriginalValue(), DateUtils.ISO_FORMAT));
                }
            } else if (propValue.getClass().equals(Integer.class)) {
                op.setTypedValue(Integer.parseInt(val));
            } else if (propValue.getClass().equals(Long.class)) {
                op.setTypedValue(Long.parseLong(val));
            } else if (propValue.getClass().equals(Boolean.class)) {
                op.setTypedValue(Boolean.parseBoolean(val));

            } else {
                op.setTypedValue(op.getOriginalValue());
            }
        } else {
            op.setTypedValue(op.getOriginalValue());
        }
    } else if (op.getOriginalValue() instanceof BigInteger) {
        op.setTypedValue(((BigInteger) op.getOriginalValue()).longValue());

    } else if (op.getOriginalValue() instanceof Integer && propValue instanceof Long) {
        op.setTypedValue(new Long((Integer) op.getOriginalValue()));
    } else if (op.getOriginalValue() instanceof Integer && propValue instanceof Float) {
        op.setTypedValue(((Integer) op.getOriginalValue()).floatValue());
    } else if (op.getOriginalValue() instanceof Integer && propValue instanceof Double) {
        op.setTypedValue(((Integer) op.getOriginalValue()).doubleValue());
    } else if (op.getOriginalValue() instanceof Long && propValue instanceof Double) {
        op.setTypedValue(((Long) op.getOriginalValue()).doubleValue());
    } else if (op.getOriginalValue() instanceof Long && propValue instanceof Float) {
        op.setTypedValue(((Long) op.getOriginalValue()).floatValue());
    } else if (propValue instanceof Boolean) {
        if (op.getOriginalValue() instanceof Integer || op.getOriginalValue() instanceof Long) {
            if ((Integer) op.getOriginalValue() == 0) {
                op.setTypedValue(false);
            } else if ((Integer) op.getOriginalValue() == 1) {
                op.setTypedValue(true);
            }
        }
    }
    if (op.getTypedValue() == null) {
        op.setTypedValue(op.getOriginalValue());
    }
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

@Override
protected void doViewRequestImpl(final Page.Request pageRequest, final ViewResponse viewResponse)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = doProxyRequest(pageRequest, Mode.VIEW);

    final @NonNull HttpResponse proxyResponse = proxyContext.getResponse();
    final URL proxiedFileURL = HttpUtil.getRequestTargetURL(proxyContext);

    try (final CloseableHttpClient proxyClient = Objects
            .requireNonNull((CloseableHttpClient) proxyContext.getAttribute(HTTP_CLIENT_CONTEXT_ID))) {

        final MimeType responseContentType = getProxyResponseHeader(pageRequest, proxyResponse, "Content-Type",
                IOUtil::newMimeType);//from  w ww.ja  v  a 2s .co  m
        viewResponse.setContentType(
                (responseContentType != null) ? RESTUtil.getMediaType(responseContentType) : null);

        viewResponse.setLastModified(getProxyResponseHeader(pageRequest, proxyResponse, "Last-Modified",
                (s) -> ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()));
        viewResponse.setCacheControl(mergeCacheControl(viewResponse.getCacheControl(),
                getProxyResponseHeader(pageRequest, proxyResponse, "Cache-Control", CacheControl::valueOf)));
        viewResponse.setExpires(getProxyResponseHeader(pageRequest, proxyResponse, "Expires",
                (s) -> ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()));
        viewResponse
                .setEntityTag(getProxyResponseHeader(pageRequest, proxyResponse, "ETag", EntityTag::valueOf));
        viewResponse.setLocale(getProxyResponseHeader(pageRequest, proxyResponse, "Content-Language",
                (h) -> Locale.forLanguageTag(
                        CollUtil.first(Arrays.asList(StringUtil.COMMA_SEPARATED_PATTERN.split(h))).get())));

        if (isRenderedUsingXMLView(pageRequest, proxyResponse, responseContentType)) {
            renderXMLView(pageRequest, viewResponse, proxyResponse, proxiedFileURL, responseContentType);
        } else if (isRenderedUsingTextView(pageRequest, proxyResponse, responseContentType)) {
            renderTextView(pageRequest, viewResponse, proxyResponse, proxiedFileURL, responseContentType);
        } else {
            renderResourceReferenceView(pageRequest, viewResponse, proxiedFileURL, responseContentType);
        }

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
        LogAnnotation.annotate(wpe, "ProxiedFileURL", proxiedFileURL, null, false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        throw wpe;
    } catch (IOException ioe) {
        throw new WWWEEEPortal.OperationalException(ioe);
    }

    return;
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

@Override
protected Response doResourceRequestImpl(final Page.Request pageRequest)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = doProxyRequest(pageRequest, Mode.RESOURCE);
    @SuppressWarnings("resource")
    final CloseableHttpClient proxyClient = Objects
            .requireNonNull((CloseableHttpClient) proxyContext.getAttribute(HTTP_CLIENT_CONTEXT_ID));

    final @NonNull HttpResponse proxyResponse = proxyContext.getResponse();

    try {//w  w  w.  j  a  va2s.  c  o m

        final Response.ResponseBuilder responseBuilder = Response.ok();

        responseBuilder.lastModified(getProxyResponseHeader(pageRequest, proxyResponse, "Last-Modified",
                (s) -> Date.from(ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant())));
        final MimeType responseContentType = getProxyResponseHeader(pageRequest, proxyResponse, "Content-Type",
                IOUtil::newMimeType);
        responseBuilder.type((responseContentType != null) ? RESTUtil.getMediaType(responseContentType) : null);
        responseBuilder.cacheControl(mergeCacheControl(getCacheControlDefault().orElse(null),
                getProxyResponseHeader(pageRequest, proxyResponse, "Cache-Control", CacheControl::valueOf)));
        responseBuilder.expires(getProxyResponseHeader(pageRequest, proxyResponse, "Expires",
                (s) -> Date.from(ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant())));
        responseBuilder.tag(getProxyResponseHeader(pageRequest, proxyResponse, "ETag", EntityTag::valueOf));
        responseBuilder.language(getProxyResponseHeader(pageRequest, proxyResponse, "Content-Language",
                (h) -> Locale.forLanguageTag(StringUtil.COMMA_SEPARATED_PATTERN.split("")[0]).toString()));

        final HttpEntity proxyResponseEntity = proxyResponse.getEntity();
        final Long contentLength = (proxyResponseEntity != null)
                ? Long.valueOf(proxyResponseEntity.getContentLength())
                : null;
        responseBuilder.header("Content-Length", contentLength);

        if (proxyResponseEntity != null) {
            responseBuilder.entity(HttpUtil.getDataSource(proxyResponseEntity, proxyClient));
        } else {
            try {
                proxyClient.close();
            } catch (IOException ioe) {
                throw new WWWEEEPortal.OperationalException(ioe);
            }
        }

        return responseBuilder.build();

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        } catch (Exception e) {
        }
        throw wpe;
    }
}