Example usage for java.time ZoneOffset UTC

List of usage examples for java.time ZoneOffset UTC

Introduction

In this page you can find the example usage for java.time ZoneOffset UTC.

Prototype

ZoneOffset UTC

To view the source code for java.time ZoneOffset UTC.

Click Source Link

Document

The time-zone offset for UTC, with an ID of 'Z'.

Usage

From source file:com.blackducksoftware.integration.hub.detect.workflow.project.ProjectNameVersionDecider.java

public NameVersion decideProjectNameVersion(String preferredDetectTools,
        final List<DetectToolProjectInfo> detectToolProjectInfo) throws DetectUserFriendlyException {

    Optional<String> decidedProjectName = Optional.empty();
    Optional<String> decidedProjectVersion = Optional.empty();

    if (StringUtils.isNotBlank(projectVersionOptions.overrideProjectName)) {
        decidedProjectName = Optional.of(projectVersionOptions.overrideProjectName);
    }/* www.  j  a  va  2  s  . c o m*/

    if (StringUtils.isNotBlank(projectVersionOptions.overrideProjectVersionName)) {
        decidedProjectVersion = Optional.of(projectVersionOptions.overrideProjectVersionName);
    }

    Optional<DetectToolProjectInfo> chosenTool = decideToolProjectInfo(preferredDetectTools,
            detectToolProjectInfo);
    if (chosenTool.isPresent()) {
        if (!decidedProjectName.isPresent()) {
            String suggestedName = chosenTool.get().getSuggestedNameVersion().getName();
            if (StringUtils.isNotBlank(suggestedName)) {
                decidedProjectName = Optional.of(suggestedName);
            }
        }
        if (!decidedProjectVersion.isPresent()) {
            String suggestedVersion = chosenTool.get().getSuggestedNameVersion().getVersion();
            if (StringUtils.isNotBlank(suggestedVersion)) {
                decidedProjectVersion = Optional.of(suggestedVersion);
            }
        }
    }

    if (!decidedProjectName.isPresent()) {
        logger.info("A project name could not be decided. Using the name of the source path.");
        decidedProjectName = Optional.of(projectVersionOptions.sourcePathName);
    }

    if (!decidedProjectVersion.isPresent()) {
        if ("timestamp".equals(projectVersionOptions.defaultProjectVersionScheme)) {
            logger.info("A project version name could not be decided. Using the current timestamp.");
            final String timeformat = projectVersionOptions.defaultProjectVersionFormat;
            final String timeString = DateTimeFormatter.ofPattern(timeformat).withZone(ZoneOffset.UTC)
                    .format(Instant.now().atZone(ZoneOffset.UTC));
            decidedProjectVersion = Optional.of(timeString);
        } else {
            logger.info("A project version name could not be decided. Using the default version text.");
            decidedProjectVersion = Optional.of(projectVersionOptions.defaultProjectVersionText);
        }
    }

    return new NameVersion(decidedProjectName.get(), decidedProjectVersion.get());
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitDataPointMapper.java

/**
 * TODO rewrite this, the names don't make sense
 * @param node a JSON node containing <code>date</code> and <code>time</code> properties
 * @return the equivalent OffsetDateTime
 *///from   w w w  .j a v a 2  s. c o m
protected Optional<OffsetDateTime> combineDateTimeAndTimezone(JsonNode node) {

    Optional<LocalDateTime> dateTime = asOptionalLocalDateTime(node, "date", "time");
    Optional<OffsetDateTime> offsetDateTime = null;

    if (dateTime.isPresent()) {
        // FIXME fix the time zone offset to use the correct offset for the data point once it is fixed by Fitbit
        offsetDateTime = Optional.of(OffsetDateTime.of(dateTime.get(), ZoneOffset.UTC));
    }

    return offsetDateTime;
}

From source file:com.intuit.wasabi.api.pagination.filters.FilterUtil.java

/**
 * Parses a UI date of the format {@code M/d/yZ} (See {@link DateTimeFormatter}) as it is allowed to be
 * entered in advanced search fields in the UI. Throws a {@link PaginationException} on failure, notifying the user.
 *
 * @param dateString     the string as received from the UI
 * @param timeZoneOffset the user's timezone offset
 * @return a parsed date// w w w  . j  a  va2s .co m
 */
public static OffsetDateTime parseUIDate(String dateString, String timeZoneOffset) {
    try {
        TemporalAccessor tempAccessor = DateTimeFormatter.ofPattern("M/d/yyyyZ")
                .parse(dateString + timeZoneOffset);
        return OffsetDateTime.of(java.time.LocalDate.from(tempAccessor), LocalTime.MIDNIGHT, ZoneOffset.UTC);
    } catch (DateTimeParseException parseException) {
        throw new PaginationException(
                ErrorCode.FILTER_KEY_UNPROCESSABLE, "Wrong format: Can not parse date (" + dateString
                        + ") , must be of " + "format MM/dd/yyyy , e.g. 05/23/2014 or 4/7/2013",
                parseException);
    }
}

From source file:org.silverpeas.core.date.Period.java

/**
 * Creates a new period of time between the two non null specified dates. The period is spreading
 * over all the day(s) between the specified inclusive start day and the exclusive end day; the
 * period is expressed in days. For example, a period between 2016-12-15 and 2016-12-17 means the
 * period is spreading over two days (2016-12-15 and 2016-12-16).
 * @param startDay the start day of the period. It defines the inclusive date at which the
 * period starts.//w  ww.ja v  a2  s  .com
 * @param endDay the end day of the period. It defines the exclusive date at which the period
 * ends. The end date must be the same or after the start date. An end date equal to the start
 * date means the period is spanning all the day of the start date; it is equivalent to an end
 * date being one day after the start date.
 * @return the period of days between the two specified dates.
 */
public static Period between(LocalDate startDay, LocalDate endDay) {
    checkPeriod(startDay, endDay);
    Period period = new Period();
    period.startDateTime = startDay == LocalDate.MIN ? OffsetDateTime.MIN
            : startDay.atStartOfDay(ZoneOffset.UTC).toOffsetDateTime();
    period.endDateTime = endDay == LocalDate.MAX ? OffsetDateTime.MAX
            : endDay.atStartOfDay(ZoneOffset.UTC).toOffsetDateTime();
    if (startDay.isEqual(endDay)) {
        period.endDateTime = period.endDateTime.plusDays(1);
    }
    period.inDays = true;
    return period;
}

From source file:de.ks.flatadocdb.defaults.ReflectionLuceneDocumentExtractor.java

private DocField createLocalDateTimeDocField(Field f, MethodHandle getter) {
    return new DocField(f, getter, (id, value) -> {
        LocalDateTime localDateTime = (LocalDateTime) value;
        long utcTime = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
        return new LongField(id, utcTime, org.apache.lucene.document.Field.Store.YES);
    });//from   w w w . j av a 2 s.  c  o m
}

From source file:rjc.jplanner.model.DateTime.java

/****************************************** toString *******************************************/
public String toString(String format) {
    // convert to string in specified format
    LocalDateTime ldt = LocalDateTime.ofEpochSecond(m_milliseconds / 1000L,
            (int) (m_milliseconds % 1000 * 1000000), ZoneOffset.UTC);

    // to support half-of-year using Bs, quote any unquoted Bs in format
    StringBuilder newFormat = new StringBuilder();
    boolean inQuote = false;
    boolean inB = false;
    char here;// w  w w  . j  a  v a2 s . c  o  m
    for (int i = 0; i < format.length(); i++) {
        here = format.charAt(i);

        // are we in quoted text?
        if (here == QUOTE)
            inQuote = !inQuote;

        // replace unquoted Bs with special code
        if (inB && here == CHARB) {
            newFormat.append(CODE);
            continue;
        }

        // come to end of unquoted Bs
        if (inB && here != CHARB) {
            newFormat.append(QUOTE);
            inB = false;
            inQuote = false;
        }

        // start of unquoted Bs, start quote with special code
        if (!inQuote && here == CHARB) {
            // avoid creating double quotes
            if (newFormat.length() > 0 && newFormat.charAt(newFormat.length() - 1) == QUOTE) {
                newFormat.deleteCharAt(newFormat.length() - 1);
                newFormat.append(CODE);
            } else
                newFormat.append("'" + CODE);
            inQuote = true;
            inB = true;
        } else {
            newFormat.append(here);
        }
    }

    // close quote if quote still open
    if (inQuote)
        newFormat.append(QUOTE);

    String str = ldt.format(DateTimeFormatter.ofPattern(newFormat.toString()));

    // no special code so can return string immediately
    if (!str.contains(CODE))
        return str;

    // determine half-of-year
    String yearHalf;
    if (month() < 7)
        yearHalf = "1";
    else
        yearHalf = "2";

    // four or more Bs is not allowed
    String Bs = StringUtils.repeat(CODE, 4);
    if (str.contains(Bs))
        throw new IllegalArgumentException("Too many pattern letters: B");

    // replace three Bs
    Bs = StringUtils.repeat(CODE, 3);
    if (yearHalf.equals("1"))
        str = str.replace(Bs, yearHalf + "st half");
    else
        str = str.replace(Bs, yearHalf + "nd half");

    // replace two Bs
    Bs = StringUtils.repeat(CODE, 2);
    str = str.replace(Bs, "H" + yearHalf);

    // replace one Bs
    Bs = StringUtils.repeat(CODE, 1);
    str = str.replace(Bs, yearHalf);

    return str;
}

From source file:org.haiku.haikudepotserver.job.controller.JobController.java

/**
 * <p>This is helper-code that can be used to check to see if the data is stale and
 * will then enqueue the job, run it and then redirect the user to the data
 * download.</p>/* ww w  .  j a  v a 2 s  .c  o  m*/
 * @param response is the HTTP response to send the redirect to.
 * @param ifModifiedSinceHeader is the inbound header from the client.
 * @param lastModifyTimestamp is the actual last modified date for the data.
 * @param jobSpecification is the job that would be run if the data is newer than in the
 *                         inbound header.
 */

public static void handleRedirectToJobData(HttpServletResponse response, JobService jobService,
        String ifModifiedSinceHeader, Date lastModifyTimestamp, JobSpecification jobSpecification)
        throws IOException {

    if (!Strings.isNullOrEmpty(ifModifiedSinceHeader)) {
        try {
            Date requestModifyTimestamp = new Date(Instant
                    .from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(ifModifiedSinceHeader)).toEpochMilli());

            if (requestModifyTimestamp.getTime() >= lastModifyTimestamp.getTime()) {
                response.setStatus(HttpStatus.NOT_MODIFIED.value());
                return;
            }
        } catch (DateTimeParseException dtpe) {
            LOGGER.warn("bad [{}] header on request; [{}] -- will ignore", HttpHeaders.IF_MODIFIED_SINCE,
                    StringUtils.abbreviate(ifModifiedSinceHeader, 128));
        }
    }

    // what happens here is that we get the report and if it is too old, delete it and try again.

    JobSnapshot jobSnapshot = getJobSnapshotStartedAfter(jobService, lastModifyTimestamp, jobSpecification);
    Set<String> jobDataGuids = jobSnapshot.getDataGuids();

    if (1 != jobDataGuids.size()) {
        throw new IllegalStateException("found [" + jobDataGuids.size()
                + "] job data guids related to the job [" + jobSnapshot.getGuid() + "] - was expecting 1");
    }

    String lastModifiedValue = DateTimeFormatter.RFC_1123_DATE_TIME
            .format(ZonedDateTime.ofInstant(lastModifyTimestamp.toInstant(), ZoneOffset.UTC));
    String destinationLocationUrl = UriComponentsBuilder.newInstance()
            .pathSegment(AuthenticationFilter.SEGMENT_SECURED).pathSegment(JobController.SEGMENT_JOBDATA)
            .pathSegment(jobDataGuids.iterator().next()).pathSegment(JobController.SEGMENT_DOWNLOAD)
            .toUriString();

    response.addHeader(HttpHeaders.LAST_MODIFIED, lastModifiedValue);
    response.sendRedirect(destinationLocationUrl);
}

From source file:org.talend.dataprep.transformation.actions.date.TimestampToDate.java

protected String getTimeStamp(String from, DateTimeFormatter dateTimeFormatter) {
    if (!NumericHelper.isBigDecimal(from)) {
        // empty value if the date cannot be parsed
        return StringUtils.EMPTY;
    }//www  .j  a v a  2 s.c om
    LocalDateTime date = LocalDateTime.ofEpochSecond(Long.parseLong(from), 0, ZoneOffset.UTC);
    return dateTimeFormatter.format(date);
}

From source file:org.springframework.session.web.http.DefaultCookieSerializer.java

@Override
public void writeCookieValue(CookieValue cookieValue) {
    HttpServletRequest request = cookieValue.getRequest();
    HttpServletResponse response = cookieValue.getResponse();

    StringBuilder sb = new StringBuilder();
    sb.append(this.cookieName).append('=');
    String value = getValue(cookieValue);
    if (value != null && value.length() > 0) {
        validateValue(value);//from www.  j a v a2 s . co  m
        sb.append(value);
    }
    int maxAge = getMaxAge(cookieValue);
    if (maxAge > -1) {
        sb.append("; Max-Age=").append(cookieValue.getCookieMaxAge());
        OffsetDateTime expires = (maxAge != 0) ? OffsetDateTime.now().plusSeconds(maxAge)
                : Instant.EPOCH.atOffset(ZoneOffset.UTC);
        sb.append("; Expires=").append(expires.format(DateTimeFormatter.RFC_1123_DATE_TIME));
    }
    String domain = getDomainName(request);
    if (domain != null && domain.length() > 0) {
        validateDomain(domain);
        sb.append("; Domain=").append(domain);
    }
    String path = getCookiePath(request);
    if (path != null && path.length() > 0) {
        validatePath(path);
        sb.append("; Path=").append(path);
    }
    if (isSecureCookie(request)) {
        sb.append("; Secure");
    }
    if (this.useHttpOnlyCookie) {
        sb.append("; HttpOnly");
    }
    if (this.sameSite != null) {
        sb.append("; SameSite=").append(this.sameSite);
    }

    response.addHeader("Set-Cookie", sb.toString());
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitDataPointMapper.java

/**
 * Transforms a {@link LocalDateTime} object into an {@link OffsetDateTime} object with a UTC time zone
 *
 * @param dateTime local date and time for the Fitbit response JSON node
 * @return the date and time based on the input dateTime parameter
 *//*from  w ww  . j  av a2 s .  co m*/
protected OffsetDateTime combineDateTimeAndTimezone(LocalDateTime dateTime) {

    // FIXME fix the time zone offset to use the appropriate offset for the data point once it is fixed by Fitbit
    return OffsetDateTime.of(dateTime, ZoneOffset.UTC);
}