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:fr.javatic.mongo.jacksonCodec.javaTime.deserializers.OffsetDateTimeDeserializer.java

@Override
public OffsetDateTime deserialize(BsonParser bsonParser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    if (bsonParser.getCurrentToken() != JsonToken.VALUE_EMBEDDED_OBJECT
            || bsonParser.getCurrentBsonType() != BsonConstants.TYPE_DATETIME) {
        throw ctxt.mappingException(Date.class);
    }//from   w w w .  j  a  v a2  s .  c o  m

    Object obj = bsonParser.getEmbeddedObject();
    if (obj == null) {
        return null;
    }

    Date dt = (Date) obj;
    return Instant.ofEpochMilli(dt.getTime()).atOffset(ZoneOffset.UTC);
}

From source file:stroom.util.test.StroomTestUtil.java

public static File createUniqueTestDir(final File parentDir) throws IOException {
    if (!parentDir.isDirectory()) {
        throw new IOException(
                "The parent directory '" + FileUtil.getCanonicalPath(parentDir) + "' does not exist");
    }/*from   w  w  w .j av a 2 s .  c  o  m*/

    File dir = null;
    for (int i = 0; i < 100; i++) {
        dir = new File(parentDir, FORMAT.format(ZonedDateTime.now(ZoneOffset.UTC)));
        if (dir.mkdir()) {
            break;
        } else {
            dir = null;
            ThreadUtil.sleep(100);
        }
    }

    if (dir == null) {
        throw new IOException("Unable to create unique test dir in: " + FileUtil.getCanonicalPath(parentDir));
    }

    return dir;
}

From source file:net.dv8tion.jda.handle.UserTypingHandler.java

@Override
protected String handleInternally(JSONObject content) {
    MessageChannel channel = api.getChannelMap().get(content.getString("channel_id"));

    if (channel == null) {
        channel = api.getPmChannelMap().get(content.getString("channel_id"));
    } else if (GuildLock.get(api).isLocked(((TextChannel) channel).getGuild().getId())) {
        return ((TextChannel) channel).getGuild().getId();
    }/*from   w w w  .  j  a va2s  .  co  m*/

    User user = api.getUserMap().get(content.getString("user_id"));
    if (user == null)
        return null;

    OffsetDateTime timestamp = Instant.ofEpochSecond(content.getInt("timestamp")).atOffset(ZoneOffset.UTC);
    api.getEventManager().handle(new UserTypingEvent(api, responseNumber, user, channel, timestamp));
    api.getEventManager().handle(new GenericUserEvent(api, responseNumber, user));
    return null;
}

From source file:org.ligoj.app.plugin.prov.aws.auth.AWS4SignerForAuthorizationHeaderTest.java

/**
 * Test method for/*from   w w  w  . j  a v  a2  s  .c  om*/
 * {@link org.ligoj.app.plugin.prov.aws.auth.AWS4SignerForAuthorizationHeader#computeSignature(org.ligoj.app.plugin.prov.aws.auth.AWS4SignatureQuery)}.
 */
@Test
public void testComputeSignatureWithBody() {
    ReflectionTestUtils.setField(signer, "clock", Clock.fixed(
            LocalDateTime.of(2017, 5, 29, 22, 15).toInstant(ZoneOffset.UTC), ZoneOffset.UTC.normalized()));
    final AWS4SignatureQuery signatureQuery = AWS4SignatureQuery.builder().accessKey("awsAccessKey")
            .secretKey("awsSecretKey").region("eu-west-1").method("GET").service("s3").path("path").body("body")
            .build();
    Assertions.assertEquals(
            "AWS4-HMAC-SHA256 Credential=awsAccessKey/20170529/eu-west-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=704a07b30cf11a27123ea3b430680a37ffe311a858496440ab519d0cc5adaa8f",
            signer.computeSignature(signatureQuery));
}

From source file:com.inversoft.json.ZonedDateTimeDeserializer.java

@Override
public ZonedDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonToken t = jp.getCurrentToken();/*from   ww w .ja  v a  2  s .co  m*/
    long value;
    if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) {
        value = jp.getLongValue();
    } else if (t == JsonToken.VALUE_STRING) {
        String str = jp.getText().trim();
        if (str.length() == 0) {
            return null;
        }

        try {
            value = Long.parseLong(str);
        } catch (NumberFormatException e) {
            throw ctxt.mappingException(handledType());
        }
    } else {
        throw ctxt.mappingException(handledType());
    }

    return ZonedDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneOffset.UTC);
}

From source file:edu.usu.sdl.openstorefront.common.util.TimeUtil.java

/**
 * Get the end of the day passed in/* w  w  w.j  a  va 2 s . co  m*/
 *
 * @param date
 * @return end of the day or null if date was null
 */
public static Date endOfDay(Date date) {
    if (date != null) {
        Instant instant = Instant.ofEpochMilli(date.getTime());
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        localDateTime = localDateTime.withHour(23).withMinute(59).withSecond(59)
                .with(ChronoField.MILLI_OF_SECOND, 999);
        return new Date(localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli());
    }
    return date;

}

From source file:org.primeframework.mvc.parameter.convert.converters.ZonedDateTimeConverter.java

protected Object stringToObject(String value, Type convertTo, Map<String, String> attributes, String expression)
        throws ConversionException, ConverterStateException {
    if (emptyIsNull && StringUtils.isBlank(value)) {
        return null;
    }/*www. jav  a 2s  .  c  om*/

    String format = attributes.get("dateTimeFormat");
    if (format == null) {
        // Try checking if this is an instant
        try {
            long instant = Long.parseLong(value);
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli(instant), ZoneOffset.UTC);
        } catch (NumberFormatException e) {
            throw new ConverterStateException("You must provide the dateTimeFormat dynamic attribute for "
                    + "the form fields [" + expression + "] that maps to DateTime properties in the action. "
                    + "If you are using a text field it will look like this: [@jc.text _dateTimeFormat=\"MM/dd/yyyy hh:mm:ss aa Z\"]\n\n"
                    + "NOTE: The format must include the time and a timezone. Otherwise, it will be unparseable");
        }
    }

    return toDateTime(value, format);
}

From source file:de.bytefish.fcmjava.client.http.apache.utils.RetryHeaderUtils.java

private static boolean tryGetFromDate(String dateAsString, OutParameter<Duration> result) {

    // Try to convert the String to a RFC1123-compliant Zoned DateTime
    OutParameter<ZonedDateTime> resultDate = new OutParameter<>();

    if (!tryToConvertToDate(dateAsString, resultDate)) {
        return false;
    }/*  w ww  . j  a v a 2  s.  c o  m*/

    // Get the UTC Now DateTime and the Retry DateTime in UTC Time Zone:
    ZonedDateTime utcNowDateTime = DateUtils.getUtcNow();
    ZonedDateTime nextRetryDateTime = resultDate.get().withZoneSameInstant(ZoneOffset.UTC);

    // Calculate Duration between both as the Retry Delay:
    Duration durationToNextRetryTime = Duration.between(utcNowDateTime, nextRetryDateTime);

    // Negative Retry Delays should not be allowed:
    if (durationToNextRetryTime.getSeconds() < 0) {
        durationToNextRetryTime = Duration.ofSeconds(0);
    }

    // Set it as Result:
    result.set(durationToNextRetryTime);

    // And return success:
    return true;
}

From source file:com.oembedler.moon.graphql.engine.type.GraphQLLocalDateTimeType.java

public GraphQLLocalDateTimeType(String name, String description, String dateFormat) {
    super(name, description, new Coercing() {
        private final TimeZone timeZone = TimeZone.getTimeZone("UTC");

        @Override//from w w  w. j  a v a 2 s  . c  o m
        public Object serialize(Object input) {
            if (input instanceof String) {
                return parse((String) input);
            } else if (input instanceof LocalDateTime) {
                return format((LocalDateTime) input);
            } else if (input instanceof Long) {
                return LocalDateTime.ofEpochSecond((Long) input, 0, ZoneOffset.UTC);
            } else if (input instanceof Integer) {
                return LocalDateTime.ofEpochSecond((((Integer) input).longValue()), 0, ZoneOffset.UTC);
            } else {
                throw new GraphQLException("Wrong timestamp value");
            }
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (!(input instanceof StringValue))
                return null;
            return parse(((StringValue) input).getValue());
        }

        private String format(LocalDateTime input) {
            return getDateTimeFormatter().format(input);
        }

        private LocalDateTime parse(String input) {
            LocalDateTime date = null;
            try {
                date = LocalDateTime.parse(input, getDateTimeFormatter());
            } catch (Exception e) {
                throw new GraphQLException("Can not parse input date", e);
            }
            return date;
        }

        private DateTimeFormatter getDateTimeFormatter() {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            return formatter;
        }
    });
    Assert.notNull(dateFormat, "Date format must not be null");
}

From source file:de.bytefish.fcmjava.client.interceptors.response.utils.RetryHeaderUtils.java

private static boolean tryGetFromDate(String dateAsString, OutParameter<Duration> result) {

    // Try to convert the String to a RFC1123-compliant Zoned DateTime
    OutParameter<ZonedDateTime> resultDate = new OutParameter<ZonedDateTime>();

    if (!tryToConvertToDate(dateAsString, resultDate)) {
        return false;
    }//from  w  ww  . ja  v a  2 s  . c o m

    // Get the UTC Now DateTime and the Retry DateTime in UTC Time Zone:
    ZonedDateTime utcNowDateTime = DateUtils.getUtcNow();
    ZonedDateTime nextRetryDateTime = resultDate.get().withZoneSameInstant(ZoneOffset.UTC);

    // Calculate Duration between both as the Retry Delay:
    Duration durationToNextRetryTime = Duration.between(utcNowDateTime, nextRetryDateTime);

    // Negative Retry Delays should not be allowed:
    if (durationToNextRetryTime.getSeconds() < 0) {
        durationToNextRetryTime = Duration.ofSeconds(0);
    }

    // Set it as Result:
    result.set(durationToNextRetryTime);

    // And return success:
    return true;
}