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:org.edgexfoundry.scheduling.ScheduleContext.java

private ZonedDateTime parseTime(String time) {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
            .withZone(ZoneId.systemDefault());
    ZonedDateTime zdt = null;/*from   w  ww  . j  av a 2 s. co  m*/
    try {
        zdt = ZonedDateTime.parse(time, dtf);
    } catch (DateTimeParseException e) {
        logger.error("parseTime() failed to parse '" + time + "'");
    }
    return zdt;
}

From source file:net.straylightlabs.archivo.net.MindCommandRecordingSearch.java

private LocalDateTime parseUTCDateTime(String utcDateTime) {
    ZonedDateTime utc = ZonedDateTime.parse(utcDateTime + " +0000",
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss ZZ"));
    return utc.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}

From source file:org.apache.metron.parsers.snort.BasicSnortParser.java

/**
 * Parses Snort's default date-time representation and
 * converts to epoch.//from  www  .  j av a2  s .c  om
 * @param snortDatetime Snort's default date-time as String '01/27-16:01:04.877970'
 * @return epoch time
 * @throws java.text.ParseException
 */
private long toEpoch(String snortDatetime) throws ParseException {
    ZonedDateTime zonedDateTime = ZonedDateTime.parse(snortDatetime.trim(), dateTimeFormatter);
    return zonedDateTime.toInstant().toEpochMilli();
}

From source file:lumbermill.internal.influxdb.InfluxDBClient.java

/**
 * Creates  Points based on the event and config
 *//* w  w  w . j a  va 2s. c om*/
private static Observable<Point> buildPoint(MapWrap config, StringTemplate measurementTemplate,
        JsonEvent jsonEvent) {

    final MapWrap fieldsConfig = MapWrap.of(config.getObject("fields"));
    final List<String> excludeTags = config.getObject("excludeTags", DEFAULT_EXCLUDED_TAGS);

    // One field is required, otherwise the point will not be created
    boolean addedAtLeastOneField = false;
    Optional<String> measurementOptional = measurementTemplate.format(jsonEvent);
    if (!measurementOptional.isPresent()) {
        LOGGER.debug("Failed to extract measurement using {}, not points will be created",
                measurementTemplate.original());
        return Observable.empty();
    }
    Point.Builder pointBuilder = Point.measurement(measurementOptional.get());

    for (Object entry1 : fieldsConfig.toMap().entrySet()) {
        Map.Entry<String, String> entry = (Map.Entry) entry1;
        StringTemplate fieldName = StringTemplate.compile(entry.getKey());
        String valueField = entry.getValue();

        JsonNode node = jsonEvent.unsafe().get(valueField);
        if (node == null) {
            LOGGER.debug("Failed to extract any field for {}", valueField);
            continue;
        }

        Optional<String> formattedFieldNameOptional = fieldName.format(jsonEvent);
        if (!formattedFieldNameOptional.isPresent()) {
            LOGGER.debug("Failed to extract any field for {}", fieldName.original());
            continue;
        }

        addedAtLeastOneField = true;

        if (node.isNumber()) {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asDouble());
        } else if (node.isBoolean()) {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asBoolean());
        } else {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asText());
        }
    }

    Iterator<String> stringIterator = jsonEvent.unsafe().fieldNames();
    while (stringIterator.hasNext()) {
        String next = stringIterator.next();
        if (!excludeTags.contains(next)) {
            pointBuilder.tag(next, jsonEvent.valueAsString(next));
        }
    }

    Optional<String> timeField = config.exists("time") ? Optional.of(config.asString("time"))
            : Optional.empty();
    TimeUnit precision = config.getObject("precision", TimeUnit.MILLISECONDS);

    // Override @timestamp with a ISO_8601 String or a numerical value
    if (timeField.isPresent() && jsonEvent.has(config.asString("time"))) {

        if (jsonEvent.unsafe().get(timeField.get()).isTextual()) {
            pointBuilder.time(ZonedDateTime
                    .parse(jsonEvent.valueAsString("@timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                    .toInstant().toEpochMilli(), precision);
        } else {
            pointBuilder.time(jsonEvent.asLong(timeField.get()), precision);
        }
    } else {
        // If not overriden, check if timestamp exists and use that
        if (jsonEvent.has("@timestamp")) {
            pointBuilder.time(ZonedDateTime
                    .parse(jsonEvent.valueAsString("@timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                    .toInstant().toEpochMilli(), precision);
        }
    }

    if (!addedAtLeastOneField) {
        LOGGER.debug("Could not create a point since no fields where added");
        return Observable.empty();
    }

    Point point = pointBuilder.build();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Point to be stored {}", point.toString());
    }
    return Observable.just(point);
}

From source file:com.netflix.spinnaker.front50.model.SwiftStorageService.java

@Override
public long getLastModified(ObjectType objectType) {
    List<? extends SwiftObject> objects = getSwift().objects().list(containerName,
            ObjectListOptions.create().path(objectType.group));
    ZonedDateTime lastModified = Instant.now().atZone(ZoneOffset.UTC);
    for (SwiftObject o : objects) {
        ZonedDateTime timestamp = ZonedDateTime.parse(
                getSwift().objects().getMetadata(containerName, o.getName()).get("Last-Modified"),
                DateTimeFormatter.RFC_1123_DATE_TIME);
        if (timestamp.isBefore(lastModified)) {
            lastModified = timestamp;/*from   w w w  .  j  av  a  2  s . co  m*/
        }
    }
    return lastModified.toEpochSecond();
}

From source file:it.tidalwave.northernwind.frontend.ui.component.sitemap.DefaultSitemapViewController.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
@Nonnull//from   w ww.  java 2s  . c o  m
private ZonedDateTime getSiteNodeDateTime(final @Nonnull ResourceProperties properties) {
    try {
        final String string = properties.getProperty(Properties.PROPERTY_LATEST_MODIFICATION_DATE);
        return ZonedDateTime.parse(string, DateTimeFormatter.ISO_DATE_TIME);
    } catch (NotFoundException e) {
    } catch (IOException e) {
        log.warn("", e);
    }

    return Instant.ofEpochMilli(0).atZone(ZoneId.of("GMT"));
}

From source file:eu.fthevenet.binjr.sources.jrds.adapters.JrdsDataAdapter.java

@Override
public CsvDecoder<Double> getDecoder() {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            .withZone(getTimeZoneId());/*from w  w  w.j a  v a 2  s. c  o m*/
    return new CsvDecoder<>(getEncoding(), DELIMITER, DoubleTimeSeriesProcessor::new, s -> {
        Double val = Double.parseDouble(s);
        return val.isNaN() ? 0 : val;
    }, s -> ZonedDateTime.parse(s, formatter));
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Extracts from a {@link JSONObject} the value of the field referenced by the provided path. The received content is treated as
 * {@link String} value which must be parsed into a {@link ZonedDateTime} representation. If the value is a plain {@link ZonedDateTime} value 
 * it is returned right away. {@link ZonedDateTime} values contained inside {@link String} instances are parsed out by {@link SimpleDateFormat#parse(String)}. 
 * If parsing fails or the type is not of the referenced ones the method throws a {@link ParseException}
 * @param jsonObject//  w ww . j a va  2  s  . c o m
 *          The {@link JSONObject} to read the value from (null is not permitted as input)
 * @param fieldPath
 *          Path inside the {@link JSONObject} pointing towards the value of interest (null is not permitted as input)
 * @param formatString
 *          The expected format (eg. YYYY-mm-DD)
 * @return
 *          Value found at the end of the provided path. An empty path simply returns the input
 * @throws JSONException
 *          Thrown in case extracting values from the {@link JSONObject} fails for any reason
 * @throws IllegalArgumentException
 *          Thrown in case a provided parameter does not comply with the restrictions
 * @throws NoSuchElementException
 *          Thrown in case an element referenced inside the path does not exist at the expected location inside the {@link JSONObject}
 * @throws ParseException
 *          Thrown in case parsing out an {@link ZonedDateTime} from the retrieved field value fails for any format related reason 
 */
public ZonedDateTime getZonedDateTimeFieldValue(final JSONObject jsonObject, final String[] fieldPath,
        final String formatString)
        throws JSONException, IllegalArgumentException, NoSuchElementException, ParseException {

    Object value = getFieldValue(jsonObject, fieldPath);
    if (value instanceof ZonedDateTime)
        return (ZonedDateTime) value;
    else if (value instanceof String)
        return (StringUtils.isNotBlank(formatString)
                ? ZonedDateTime.parse((String) value, DateTimeFormatter.ofPattern(formatString))
                : ZonedDateTime.parse((String) value));

    throw new ParseException("Types of " + (value != null ? value.getClass().getName() : "null")
            + " cannot be parsed into a valid zoned date & time representation", 0);
}

From source file:arxiv.xml.XMLParser.java

/**
 * Parse the date of an article version.
 * @throws ParseException if there is a parsing error
 */// ww w .  j ava2  s .c om
private ZonedDateTime parseSubmissionTime(String value) {
    ZonedDateTime submissionTime;
    try {
        submissionTime = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME);
    } catch (DateTimeParseException e) {
        throw new ParseException("Could not parse version date '" + value + "' in RFC_1123_DATE_TIME format",
                e);
    }

    return submissionTime;
}

From source file:io.github.mikesaelim.arxivoaiharvester.xml.XMLParser.java

/**
 * Parse the date of an article version.
 * @throws ParseException if there is a parsing error
 *//* ww  w. j a  v a  2  s  .c o  m*/
@VisibleForTesting
ZonedDateTime parseSubmissionTime(String value) {
    ZonedDateTime submissionTime;
    try {
        submissionTime = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME);
    } catch (DateTimeParseException e) {
        throw new ParseException("Could not parse version date '" + value + "' in RFC_1123_DATE_TIME format",
                e);
    }

    return submissionTime;
}