Example usage for java.time ZonedDateTime ofInstant

List of usage examples for java.time ZonedDateTime ofInstant

Introduction

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

Prototype

public static ZonedDateTime ofInstant(Instant instant, ZoneId zone) 

Source Link

Document

Obtains an instance of ZonedDateTime from an Instant .

Usage

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Formats ISO date.//from ww w.j av  a 2  s. c  om
 * @param date date to format
 * @return ISO date
 */
private static String formatIsoDate(Date date) {
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zonedDateTime);
}

From source file:com.epam.dlab.backendapi.service.impl.SchedulerJobServiceImpl.java

/**
 * Checks if scheduler's time data satisfies existing time parameters.
 *
 * @param dto           scheduler job data.
 * @param dateTime      existing time data.
 * @param desiredStatus target exploratory status which has influence for time/date checking ('running' status
 *                      requires for checking start time, 'stopped' - for end time, 'terminated' - for
 *                      'terminatedDateTime').
 * @return true/false.//from  w ww . j a v  a2  s .c o m
 */
private boolean isSchedulerJobDtoSatisfyCondition(SchedulerJobDTO dto, OffsetDateTime dateTime,
        UserInstanceStatus desiredStatus) {
    ZoneOffset zOffset = dto.getTimeZoneOffset();
    OffsetDateTime roundedDateTime = OffsetDateTime.of(dateTime.toLocalDate(),
            LocalTime.of(dateTime.toLocalTime().getHour(), dateTime.toLocalTime().getMinute()),
            dateTime.getOffset());

    LocalDateTime convertedDateTime = ZonedDateTime
            .ofInstant(roundedDateTime.toInstant(), ZoneId.ofOffset(TIMEZONE_PREFIX, zOffset))
            .toLocalDateTime();

    return desiredStatus == TERMINATED
            ? Objects.nonNull(dto.getTerminateDateTime())
                    && convertedDateTime.toLocalDate().equals(dto.getTerminateDateTime().toLocalDate())
                    && convertedDateTime.toLocalTime().equals(getDesiredTime(dto, desiredStatus))
            : !convertedDateTime.toLocalDate().isBefore(dto.getBeginDate())
                    && isFinishDateMatchesCondition(dto, convertedDateTime)
                    && getDaysRepeat(dto, desiredStatus)
                            .contains(convertedDateTime.toLocalDate().getDayOfWeek())
                    && convertedDateTime.toLocalTime().equals(getDesiredTime(dto, desiredStatus));
}

From source file:org.eclipse.smarthome.binding.wemo.handler.WemoCoffeeHandler.java

public State getDateTimeState(String attributeValue) {
    if (attributeValue != null) {
        long value = 0;
        try {/*from  w  w w  .j a va  2  s  . c o m*/
            value = Long.parseLong(attributeValue) * 1000; // convert s to ms
        } catch (NumberFormatException e) {
            logger.error("Unable to parse attributeValue '{}' for device '{}'; expected long", attributeValue,
                    getThing().getUID());
            return null;
        }
        ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(value),
                TimeZone.getDefault().toZoneId());
        State dateTimeState = new DateTimeType(zoned);
        if (dateTimeState != null) {
            logger.trace("New attribute brewed '{}' received", dateTimeState);
            return dateTimeState;
        }
    }
    return null;
}

From source file:bamboo.trove.rule.RuleChangeUpdateManager.java

@VisibleForTesting
public SolrQuery convertRuleToSearch(CdxRule rule, String notLastIndexed) {
    // URL complexity first
    List<String> urlQueries = new ArrayList<>();
    for (String url : rule.getUrlPatterns()) {
        if (!url.trim().isEmpty()) {
            urlQueries.add(urlSearch(url));
        }/*from  ww  w .  ja v  a 2s.  c  om*/
    }
    if (urlQueries.isEmpty()) {
        urlQueries.add("*:*");
    }
    SolrQuery query = createQuery("(" + StringUtils.join(urlQueries, ") OR (") + ")");

    // Filter out stuff we have touched already this run
    query.addFilterQuery(notLastIndexed);
    // Filter for Embargo
    if (rule.getPeriod() != null && !rule.getPeriod().isZero()) {
        // TODAY +/- embargo period
        ZonedDateTime today = ZonedDateTime.ofInstant(CdxRestrictionService.TODAY.toInstant(), TZ);
        Date embargoStart = Date.from(today.minus(rule.getPeriod()).toInstant());
        query.addFilterQuery(SolrEnum.DATE + ":[" + format.format(embargoStart) + " TO *]");
    }
    // Filter for Capture date
    if (rule.getCaptured() != null && rule.getCaptured().hasData()) {
        query.addFilterQuery(SolrEnum.DATE + ":[" + format.format(rule.getCaptured().start) + " TO "
                + format.format(rule.getCaptured().end) + "]");
    }
    // Worth noting we don't filter for access date because it is one of the
    // deciding data points in whether or not to run this query at all.
    return query;
}

From source file:ru.anr.base.BaseParent.java

/**
 * Transforms the given calendar value to a zoned date from the default
 * (UTC) time zone.// w  w w .ja va 2s  . com
 * 
 * @param calendar
 *            Some calendar value
 * @return A zoned date-time
 */
public static ZonedDateTime date(Calendar calendar) {

    return ZonedDateTime.ofInstant(calendar.toInstant(), DEFAULT_TIMEZONE);
}

From source file:ru.anr.base.BaseParent.java

/**
 * Transforms an old date object to a zoned date using the default (UTC)
 * time zone//ww w. ja  v a2  s  .co  m
 * 
 * @param oldDate
 *            Some old date
 * @return A zoned object
 */
public static ZonedDateTime date(Date oldDate) {

    return ZonedDateTime.ofInstant(Instant.ofEpochMilli(oldDate.getTime()), DEFAULT_TIMEZONE);
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/waitingPayment", method = RequestMethod.GET)
public String showWaitingPaymentPage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId, Model model, Locale locale) {

    Optional<Event> event = eventRepository.findOptionalByShortName(eventName);
    if (!event.isPresent()) {
        return "redirect:/";
    }//from   w ww  . jav a 2 s .  c om

    Optional<TicketReservation> reservation = ticketReservationManager.findById(reservationId);
    TicketReservationStatus status = reservation.map(TicketReservation::getStatus)
            .orElse(TicketReservationStatus.PENDING);
    if (reservation.isPresent() && status == TicketReservationStatus.OFFLINE_PAYMENT) {
        Event ev = event.get();
        TicketReservation ticketReservation = reservation.get();
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, ev,
                locale);
        model.addAttribute("totalPrice", orderSummary.getTotalPrice());
        model.addAttribute("emailAddress", organizationRepository.getById(ev.getOrganizationId()).getEmail());
        model.addAttribute("reservation", ticketReservation);
        model.addAttribute("paymentReason",
                ev.getShortName() + " " + ticketReservationManager.getShortReservationID(ev, reservationId));
        model.addAttribute("pageTitle", "reservation-page-waiting.header.title");
        model.addAttribute("bankAccount",
                configurationManager
                        .getStringConfigValue(
                                Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_NR))
                        .orElse(""));

        Optional<String> maybeAccountOwner = configurationManager.getStringConfigValue(
                Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_OWNER));
        model.addAttribute("hasBankAccountOwnerSet", maybeAccountOwner.isPresent());
        model.addAttribute("bankAccountOwner", Arrays.asList(maybeAccountOwner.orElse("").split("\n")));

        model.addAttribute("expires",
                ZonedDateTime.ofInstant(ticketReservation.getValidity().toInstant(), ev.getZoneId()));
        model.addAttribute("event", ev);
        return "/event/reservation-waiting-for-payment";
    }

    return redirectReservation(reservation, eventName, reservationId);
}

From source file:com.example.app.support.AppUtil.java

/**
 * Convert the given Date to a ZonedDateTime at the given TimeZone
 *
 * @param date the Date//  www  .j  a  v  a2s .co m
 * @param zone the TimeZone to convert to
 *
 * @return a ZonedDateTime that represents the same instant as the Date, at the TimeZone specified.
 */
@Nullable
public static ZonedDateTime toZonedDateTime(@Nullable Date date, @Nullable TimeZone zone) {
    if (date == null || zone == null)
        return null;
    return ZonedDateTime.ofInstant(date.toInstant(), zone.toZoneId());
}

From source file:com.inqool.dcap.office.indexer.indexer.SolrBulkIndexer.java

protected SolrInputDocument modelToSolrInputDoc(ZdoModel model) {
    logger.debug("Constructing new SolrInputDocument...");

    final Map<String, SolrInputField> fields = new HashMap<>();

    //Add all Dublin Core terms
    for (String property : DCTools.getDcTermList()) {
        SolrInputField field = new SolrInputField(property);
        List<String> values = model.getAll(new PropertyImpl("http://purl.org/dc/terms/" + property));
        if (values.isEmpty())
            continue;
        //Skip fields that were not ticked to be published
        String visible = model.get(new PropertyImpl("http://purl.org/dc/terms/" + property + "_visibility"));
        if ("false".equals(visible) || "0".equals(visible)) { //0 should not occur any more
            continue;
        }/*  w w  w . j  av  a  2s.c om*/
        if ("isPartOf".equals(property)) { //remove ip address from isPartOf
            values.set(0, store.getOnlyIdFromUrl(values.get(0)));
        }
        if ("".equals(values.get(0))) {
            values.set(0, "unknown");
        }

        field.addValue(values, INDEX_TIME_BOOST);
        fields.put(property, field);

        //Suggester data
        if ("title".equals(property) || "creator".equals(property)) {
            SolrInputDocument suggesterDoc = new SolrInputDocument();
            String suggestVal = values.get(0).trim();
            if (!suggestVal.isEmpty() && !suggestVal.equals("unknown")) {
                suggesterDoc.addField("suggesterData", values.get(0).trim());
                dataForSuggester.add(suggesterDoc);
            }
        }
    }

    //Add system fields
    SolrInputField field = new SolrInputField("id");
    field.addValue(store.getOnlyIdFromUrl(model.getUrl()), INDEX_TIME_BOOST);
    fields.put("id", field);

    addSolrFieldFromFedoraProperty("inventoryId", ZdoTerms.inventoryId, model, fields);

    addSolrFieldFromFedoraProperty("zdoType", ZdoTerms.zdoType, model, fields);
    addSolrFieldFromFedoraProperty("zdoGroup", ZdoTerms.group, model, fields);
    addSolrFieldFromFedoraProperty("orgIdmId", ZdoTerms.organization, model, fields);
    addSolrFieldFromFedoraProperty("allowContentPublicly", ZdoTerms.allowContentPublicly, model, fields);
    addSolrFieldFromFedoraProperty("allowPdfExport", ZdoTerms.allowPdfExport, model, fields);
    addSolrFieldFromFedoraProperty("allowEpubExport", ZdoTerms.allowEpubExport, model, fields);
    addSolrFieldFromFedoraProperty("watermark", ZdoTerms.watermark, model, fields);
    addSolrFieldFromFedoraProperty("watermarkPosition", ZdoTerms.watermarkPosition, model, fields);
    addSolrFieldFromFedoraProperty("imgThumb", ZdoTerms.imgThumb, model, fields);
    addSolrFieldFromFedoraProperty("imgNormal", ZdoTerms.imgNormal, model, fields);

    String publishFromStr = model.get(ZdoTerms.publishFrom);
    if (publishFromStr != null) {
        String publishFromUtc = ZonedDateTime
                .ofInstant(Instant.ofEpochSecond(Long.valueOf(publishFromStr)), ZoneId.systemDefault())
                .withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        addSolrField("publishFrom", publishFromUtc, fields);
    }
    String publishToStr = model.get(ZdoTerms.publishTo);
    if (publishToStr != null) {
        String publishToUtc = ZonedDateTime
                .ofInstant(Instant.ofEpochSecond(Long.valueOf(publishToStr)), ZoneId.systemDefault())
                .withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        addSolrField("publishTo", publishToUtc, fields);
    }

    String created = model.get(DCTerms.created);
    if (created != null) {
        AtomicInteger yearStart = new AtomicInteger();
        AtomicInteger yearEnd = new AtomicInteger();
        AtomicBoolean startValid = new AtomicBoolean();
        AtomicBoolean endValid = new AtomicBoolean();
        YearNormalizer.normalizeCreatedYear(created, yearStart, startValid, yearEnd, endValid);
        if (startValid.get()) {
            addSolrField("yearStart", yearStart.get(), fields);
        } else {
            logger.warn("Year could not be normalized for input string " + created);
        }
        if (endValid.get()) {
            addSolrField("yearEnd", yearEnd.get(), fields);
        }
    }

    String orgName = orgNameMapping.get(model.get(ZdoTerms.organization));
    if (orgName == null) {
        orgName = "Neznm";
    }
    addSolrField("organization", orgName, fields);

    String documentTypeId = model.get(ZdoTerms.documentType); //type and subtype names must be found for id
    String documentSubTypeId = model.get(ZdoTerms.documentSubType);
    if (documentTypeId != null) {
        addSolrField("documentType", documentTypeAccess.getTypeNameForId(Integer.valueOf(documentTypeId)),
                fields);
    }
    if (documentSubTypeId != null) {
        addSolrField("documentSubType",
                documentTypeAccess.getSubTypeNameForId(Integer.valueOf(documentSubTypeId)), fields);
    }

    //Add customFields
    int fieldIndex = 0; //we actually start from 1
    do {
        fieldIndex++;
        String fieldName = model
                .get(new PropertyImpl("http://inqool.cz/zdo/1.0/customField_" + fieldIndex + "_name"));
        if (fieldName == null)
            break;
        fieldName = "customField_" + fieldName;
        String visible = model
                .get(new PropertyImpl("http://inqool.cz/zdo/1.0/customField_" + fieldIndex + "_visibility"));
        if ("false".equals(visible) || "0".equals(visible))
            continue;
        List<String> fieldValues = model
                .getAll(new PropertyImpl("http://inqool.cz/zdo/1.0/customField_" + fieldIndex));
        if ("".equals(fieldValues.get(0))) {
            fieldValues.set(0, "unknown");
        }
        SolrInputField customField = new SolrInputField(fieldName);
        customField.addValue(fieldValues, INDEX_TIME_BOOST);
        fields.put(fieldName, customField);
    } while (true);

    SolrInputDocument solrInputDocument = new SolrInputDocument(fields);
    return solrInputDocument;
}

From source file:com.example.app.support.service.AppUtil.java

/**
 * Convert the given Date to a ZonedDateTime at the given TimeZone
 *
 * @param date the Date//from  w w w  . j  a  va 2s  .c o m
 * @param zone the TimeZone to convert to
 *
 * @return a ZonedDateTime that represents the same instant as the Date, at the TimeZone specified.
 */
@Nullable
public ZonedDateTime toZonedDateTime(@Nullable Date date, @Nullable TimeZone zone) {
    if (date == null || zone == null)
        return null;
    return ZonedDateTime.ofInstant(date.toInstant(), zone.toZoneId());
}