Example usage for java.time ZonedDateTime of

List of usage examples for java.time ZonedDateTime of

Introduction

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

Prototype

public static ZonedDateTime of(LocalDateTime localDateTime, ZoneId zone) 

Source Link

Document

Obtains an instance of ZonedDateTime from a local date-time.

Usage

From source file:org.openmhealth.shim.withings.mapper.WithingsDailyCaloriesBurnedDataPointMapper.java

/**
 * Maps an individual list node from the array in the Withings activity measure endpoint response into a {@link
 * CaloriesBurned} data point./*from   ww w  .  j  a  v  a 2 s .c o  m*/
 * <p>
 * <p>Note: the start datetime and end datetime values for the mapped {@link CaloriesBurned} {@link DataPoint}
 * assume that
 * the start timezone and end time zone are the same, both equal to the "timezone" property in the Withings
 * response
 * datapoints. However, according to Withings, the property value they provide is specifically the end datetime
 * timezone.</p>
 *
 * @param node activity node from the array "activites" contained in the "body" of the endpoint response
 * @return a {@link DataPoint} object containing a {@link CaloriesBurned} measure with the appropriate values from
 * the JSON node parameter, wrapped as an {@link Optional}
 */
@Override
Optional<DataPoint<CaloriesBurned>> asDataPoint(JsonNode node) {

    long caloriesBurnedValue = asRequiredLong(node, "calories");
    CaloriesBurned.Builder caloriesBurnedBuilder = new CaloriesBurned.Builder(
            new KcalUnitValue(KcalUnit.KILOCALORIE, caloriesBurnedValue));

    Optional<String> dateString = asOptionalString(node, "date");
    Optional<String> timeZoneFullName = asOptionalString(node, "timezone");
    // We assume that timezone is the same for both the startdate and enddate timestamps, even though Withings only
    // provides the enddate timezone as the "timezone" property.
    // TODO: Revisit once Withings can provide start_timezone and end_timezone
    if (dateString.isPresent() && timeZoneFullName.isPresent()) {
        LocalDateTime localStartDateTime = LocalDate.parse(dateString.get()).atStartOfDay();
        ZoneId zoneId = ZoneId.of(timeZoneFullName.get());
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localStartDateTime, zoneId);
        ZoneOffset offset = zonedDateTime.getOffset();
        OffsetDateTime offsetStartDateTime = OffsetDateTime.of(localStartDateTime, offset);
        LocalDateTime localEndDateTime = LocalDate.parse(dateString.get()).atStartOfDay().plusDays(1);

        OffsetDateTime offsetEndDateTime = OffsetDateTime.of(localEndDateTime, offset);
        caloriesBurnedBuilder.setEffectiveTimeFrame(
                TimeInterval.ofStartDateTimeAndEndDateTime(offsetStartDateTime, offsetEndDateTime));
    }

    Optional<String> userComment = asOptionalString(node, "comment");
    if (userComment.isPresent()) {
        caloriesBurnedBuilder.setUserNotes(userComment.get());
    }

    CaloriesBurned caloriesBurned = caloriesBurnedBuilder.build();
    DataPoint<CaloriesBurned> caloriesBurnedDataPoint = newDataPoint(caloriesBurned, null, true, null);

    return Optional.of(caloriesBurnedDataPoint);

}

From source file:eu.hansolo.tilesfx.weather.Sun.java

private static ZonedDateTime[] parseJsonData(final String JSON_DATA, final ZoneId ZONE_ID) {
    Object obj = JSONValue.parse(JSON_DATA);
    JSONObject jsonObj = (JSONObject) obj;

    // Results/*from  w w w  . ja  va2s . c  o m*/
    JSONObject results = (JSONObject) jsonObj.get("results");

    LocalDateTime sunrise = LocalDateTime.parse(results.get("sunrise").toString(),
            DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime sunset = LocalDateTime.parse(results.get("sunset").toString(),
            DateTimeFormatter.ISO_DATE_TIME);
    /*
    LocalDateTime solarNoon                 = LocalDateTime.parse(results.get("solar_noon").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime dayLength                 = LocalDateTime.parse(results.get("day_length").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime civilTwilightBegin        = LocalDateTime.parse(results.get("civil_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime nauticalTwilightBegin     = LocalDateTime.parse(results.get("nautical_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime nauticalTwilightEnd       = LocalDateTime.parse(results.get("nautical_twilight_end").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime astronomicalTwilightBegin = LocalDateTime.parse(results.get("astronomical_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME);
    LocalDateTime astronomicalTwilightEnd   = LocalDateTime.parse(results.get("astronomical_twilight_end").toString(), DateTimeFormatter.ISO_DATE_TIME);
    */

    return new ZonedDateTime[] { ZonedDateTime.of(sunrise, ZONE_ID), ZonedDateTime.of(sunset, ZONE_ID) };
}

From source file:alfio.controller.api.AttendeeApiController.java

@RequestMapping(value = "/{eventKey}/sponsor-scan/mine", method = RequestMethod.GET)
public ResponseEntity<List<SponsorAttendeeData>> getScannedBadges(
        @PathVariable("eventKey") String eventShortName,
        @RequestParam(value = "from", required = false) String from, Principal principal) {

    ZonedDateTime start = Optional.ofNullable(StringUtils.trimToNull(from))
            .map(EventUtil.JSON_DATETIME_FORMATTER::parse)
            .flatMap(d -> Wrappers.safeSupplier(() -> ZonedDateTime.of(LocalDateTime.from(d), ZoneOffset.UTC)))
            .orElse(SponsorScanRepository.DEFAULT_TIMESTAMP);
    return attendeeManager.retrieveScannedAttendees(eventShortName, principal.getName(), start)
            .map(ResponseEntity::ok).orElse(notFound());
}

From source file:com.buffalokiwi.api.APIDate.java

/**
 * Attempt to take some value and turn it into a valid APIDate.
 * If it isn't valid, then this returns null.
 * //  www  .  j a v a  2 s.  c  o m
 * @param value Jet value 
 * @return date or null
 */
public static APIDate fromStringOrNull(String value) {
    if (value == null || value.isEmpty())
        return null;

    for (final DateTimeFormatter fmt : FORMATS) {
        try {
            final TemporalAccessor t = fmt.parse(value);

            try {
                return new APIDate(ZonedDateTime.from(t));
            } catch (DateTimeException e) {
                APILog.warn(LOG, e, "Failed to determine timezone.  Defaulting to local offset");
                final LocalDateTime local = LocalDateTime.from(t);
                final ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
                return new APIDate(ZonedDateTime.of(local, offset));
            }
        } catch (DateTimeParseException e) {
            //..do nothing, yet.
        }
    }

    //..Not found.  Log it and return null
    APILog.error(LOG, "Failed to parse date string:", value);
    return null;
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static Date toDate(LocalDateTime ldt) {
    ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
    GregorianCalendar cal = GregorianCalendar.from(zdt);
    return cal.getTime();
}

From source file:org.edgexfoundry.scheduling.ScheduleContext.java

public void reset(Schedule schedule) {
    if ((this.schedule != null) && (this.schedule.getName() != schedule.getName())) {
        scheduleEvents.clear();//from   w w w  .  j av a  2 s  .c  o m
    }
    this.schedule = schedule;
    // update this if/when iterations are added to the schedule
    this.maxIterations = (schedule.getRunOnce()) ? 1 : 0;
    this.iterations = 0;

    String start = schedule.getStart();
    String end = schedule.getEnd();
    // if start is empty, then use now (need to think about ever-spawning tasks)
    if (start == null || start.isEmpty()) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
                .withZone(ZoneId.systemDefault());
        start = formatter.format(Instant.now());
    }
    this.startTime = parseTime(start);

    // if end is empty, then use max
    if (end == null || end.isEmpty()) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
                .withZone(ZoneId.systemDefault());
        end = formatter.format(ZonedDateTime.of(LocalDateTime.MAX, ZoneId.systemDefault()));
    }
    this.endTime = parseTime(end);

    // get the period and duration from the frequency string
    parsePeriodAndDuration(schedule.getFrequency());

    // setup the next time the schedule will run
    this.nextTime = initNextTime(startTime, ZonedDateTime.now(), period, duration);

    // clear any schedule events as required

    logger.debug("reset() " + this.toString());
}

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);
    }//ww w. j a  v  a 2  s.  c  om
    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:org.dbflute.solr.cbean.SolrQueryBuilder.java

public static String queryBuilderForRangeSearch(String solrFieldName, LocalDateTime from, LocalDateTime to) {
    Date fromDate = from == null ? null : Date.from(ZonedDateTime.of(from, ZoneId.systemDefault()).toInstant());
    Date toDate = to == null ? null : Date.from(ZonedDateTime.of(to, ZoneId.systemDefault()).toInstant());
    return queryBuilderForRangeSearch(solrFieldName, fromDate, toDate);
}

From source file:com.teradata.benchto.service.BenchmarkService.java

public Duration getSuccessfulExecutionAge(String uniqueName) {
    Timestamp ended = benchmarkRunRepo.findTimeOfLatestSuccessfulExecution(uniqueName);
    if (ended == null) {
        return Duration.ofDays(Integer.MAX_VALUE);
    }/*w  w  w .j a  va  2s  . co  m*/
    ZonedDateTime endedAsZDT = ZonedDateTime.of(ended.toLocalDateTime(), ZoneId.systemDefault());
    return Duration.between(endedAsZDT, currentDateTime());
}