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:net.dv8tion.jda.core.handle.TypingStartHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long channelId = content.getLong("channel_id");
    MessageChannel channel = api.getTextChannelMap().get(channelId);
    if (channel == null)
        channel = api.getPrivateChannelMap().get(channelId);
    if (channel == null)
        channel = api.getFakePrivateChannelMap().get(channelId);
    if (channel == null && api.getAccountType() == AccountType.CLIENT)
        channel = api.asClient().getGroupById(channelId);
    if (channel == null)
        return null; //We don't have the channel cached yet. We chose not to cache this event
                     // because that happen very often and could easily fill up the EventCache if
                     // we, for some reason, never get the channel. Especially in an active channel.

    if (channel instanceof TextChannel) {
        final long guildId = ((TextChannel) channel).getGuild().getIdLong();
        if (api.getGuildLock().isLocked(guildId))
            return guildId;
    }/*from w w  w  .  j av a  2s  . c  o m*/

    final long userId = content.getLong("user_id");
    User user;
    if (channel instanceof PrivateChannel)
        user = ((PrivateChannel) channel).getUser();
    else if (channel instanceof Group)
        user = ((GroupImpl) channel).getUserMap().get(userId);
    else
        user = api.getUserMap().get(userId);

    if (user == null)
        return null; //Just like in the comment above, if for some reason we don't have the user for some reason
                     // then we will just throw the event away.

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

From source file:com.spotify.styx.model.WorkflowConfiguration.java

public Instant addOffset(Instant next) {
    final String offset = offset().orElseGet(this::defaultOffset);

    return TimeUtil.addOffset(next.atZone(ZoneOffset.UTC), offset).toInstant();
}

From source file:org.clebi.subscribers.daos.SubscribersIntegTestHelper.java

protected Map<String, Subscriber> indexTestSubscibers(String index) {
    final Map<String, Subscriber> subscribers = new HashMap<>();
    final String emailOptinActive = "optin_active_0@test.com";
    final String emailOptinNonActive = "optin_non-active_0@test.com";
    final String emailNonOptinActive = "non-optin-active_0@test.com";
    final String emailNonOptinNonActiv = "non-optin-non-active_0@test.com";
    subscribers.put(emailOptinActive, new Subscriber(true, true, new Email(emailOptinActive),
            ZonedDateTime.now(ZoneOffset.UTC), generateTestFields()));
    subscribers.put(emailOptinNonActive, new Subscriber(true, false, new Email(emailOptinNonActive),
            ZonedDateTime.now(ZoneOffset.UTC), generateTestFields()));
    subscribers.put(emailNonOptinActive, new Subscriber(false, true, new Email(emailNonOptinActive),
            ZonedDateTime.now(ZoneOffset.UTC), generateTestFields()));
    subscribers.put(emailNonOptinNonActiv, new Subscriber(false, false, new Email(emailNonOptinNonActiv),
            ZonedDateTime.now(ZoneOffset.UTC), generateTestFields()));
    for (Map.Entry<String, Subscriber> entry : subscribers.entrySet()) {
        indexSubsciber(index, entry.getValue());
    }/*from  www. j a  va2 s  .c o m*/
    return subscribers;
}

From source file:com.example.geomesa.kafka.KafkaQuickStart.java

public static void addSimpleFeatures(SimpleFeatureType sft, FeatureStore producerFS, String visibility)
        throws InterruptedException, IOException {
    final int MIN_X = -180;
    final int MAX_X = 180;
    final int MIN_Y = -90;
    final int MAX_Y = 90;
    final int DX = 2;
    final int DY = 1;
    final String[] PEOPLE_NAMES = { "James", "John", "Peter", "Hannah", "Claire", "Gabriel" };
    final long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L;
    final Random random = new Random();
    final ZonedDateTime MIN_DATE = ZonedDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);

    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    // creates and updates two SimpleFeatures.
    // the first time this for loop runs the two SimpleFeatures are created.
    // in the subsequent iterations of the for loop, the two SimpleFeatures are updated.
    int numFeatures = (MAX_X - MIN_X) / DX;
    for (int i = 1; i <= numFeatures; i++) {
        builder.add(PEOPLE_NAMES[i % PEOPLE_NAMES.length]); // name
        builder.add((int) Math.round(random.nextDouble() * 110)); // age
        builder.add(Date.from(//from  www .  j a v  a  2  s  .  c o  m
                MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR)).toInstant())); // dtg
        builder.add(WKTUtils$.MODULE$.read("POINT(" + (MIN_X + DX * i) + " " + (MIN_Y + DY * i) + ")")); // geom
        SimpleFeature feature1 = builder.buildFeature("1");
        feature1.getUserData().put(Hints.USE_PROVIDED_FID, Boolean.TRUE);

        builder.add(PEOPLE_NAMES[(i + 1) % PEOPLE_NAMES.length]); // name
        builder.add((int) Math.round(random.nextDouble() * 110)); // age
        builder.add(Date.from(
                MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR)).toInstant())); // dtg
        builder.add(WKTUtils$.MODULE$.read("POINT(" + (MIN_X + DX * i) + " " + (MAX_Y - DY * i) + ")")); // geom
        SimpleFeature feature2 = builder.buildFeature("2");
        feature2.getUserData().put(Hints.USE_PROVIDED_FID, Boolean.TRUE);

        if (visibility != null) {
            feature1.getUserData().put("geomesa.feature.visibility", visibility);
            feature2.getUserData().put("geomesa.feature.visibility", visibility);
        }

        // write the SimpleFeatures to Kafka
        featureCollection.add(feature1);
        featureCollection.add(feature2);
        producerFS.addFeatures(featureCollection);
        featureCollection.clear();

        // wait 100 ms in between updating SimpleFeatures to simulate a stream of data
        Thread.sleep(100);
    }
}

From source file:org.finra.herd.dao.JestClientFactory.java

/**
 * Builds and returns a JEST client.// w  ww. j a  va 2 s. c  o m
 *
 * @return the configured JEST client
 */
public JestClient getJestClient() {
    // Retrieve the configuration values used for setting up an Elasticsearch JEST client.
    final String esRegionName = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_AWS_REGION_NAME);
    final String hostname = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_HOSTNAME);
    final int port = configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_PORT,
            Integer.class);
    final String scheme = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_SCHEME);
    final String serverUri = String.format("%s://%s:%d", scheme, hostname, port);
    final int connectionTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_CONNECTION_TIMEOUT, Integer.class);
    final int readTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_READ_TIMEOUT, Integer.class);

    LOGGER.info("Elasticsearch REST Client Settings:  scheme={}, hostname={}, port={}, serverUri={}", scheme,
            hostname, port, serverUri);

    DefaultAWSCredentialsProviderChain awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();
    final AWSSigner awsSigner = new AWSSigner(awsCredentialsProvider, esRegionName, "es",
            () -> LocalDateTime.now(ZoneOffset.UTC));

    final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner);

    JestClientFactoryStaticInner jestClientFactory = new JestClientFactoryStaticInner(requestInterceptor);

    if (StringUtils.equalsIgnoreCase(scheme, "https")) {
        SSLConnectionSocketFactory sslSocketFactory;
        try {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }

        jestClientFactory.setHttpClientConfig(
                new HttpClientConfig.Builder(serverUri).connTimeout(connectionTimeout).readTimeout(readTimeout)
                        .sslSocketFactory(sslSocketFactory).multiThreaded(true).build());
    } else {
        jestClientFactory.setHttpClientConfig(new HttpClientConfig.Builder(serverUri)
                .connTimeout(connectionTimeout).readTimeout(readTimeout).multiThreaded(true).build());
    }

    return jestClientFactory.getObject();
}

From source file:com.teslagov.joan.example.ArcPortalApiTest.java

@Before
public void setup() {
    //Setup our ArcConfiguration and Api
    Properties properties = ArcPropertiesFactory.createArcProperties();

    arcConfiguration = arcConfig().arcPortalConfiguration(portalConfig()
            .portalAdminUsername(properties.getString(ArcProperties.PORTAL_ADMIN_USERNAME))
            .portalAdminPassword(properties.getString(ArcProperties.PORTAL_ADMIN_PASSWORD))
            .portalUrl(properties.getString(ArcProperties.PORTAL_URL))
            .portalPort(properties.getInteger(ArcProperties.PORTAL_PORT))
            .portalContextPath(properties.getString(ArcProperties.PORTAL_CONTEXT_PATH))
            .portalIsUsingWebAdaptor(properties.getBoolean(ArcProperties.PORTAL_IS_USING_WEB_ADAPTOR)).build())
            .build();/*w w  w .j a  v a 2 s  . co  m*/

    ArcPortalConfiguration arcPortalConfiguration = arcConfiguration.getArcPortalConfiguration();

    cookieStore = new BasicCookieStore();

    httpClient = TrustingHttpClientFactory.createVeryUnsafePortalHttpClient(arcConfiguration, cookieStore);

    arcPortalApi = new ArcPortalApi(httpClient, arcPortalConfiguration, ZoneOffset.UTC, new TokenManager(
            new TokenRefresher(new PortalTokenFetcher(httpClient, arcPortalConfiguration), ZoneOffset.UTC)));
}

From source file:com.github.jrh3k5.habitat4j.rest.CachingAccessTokenProvider.java

/**
 * Determines whether or not the given access token is in need of being refreshed and evicted from the cache.
 * /*from  w w w  . j av a  2s  .c  o m*/
 * @param accessToken
 *            The {@link AccessToken} to be evaluated for eviction from the cache.
 * @return {@code true} if the given access token requires a refresh; {@code false} if not.
 */
private boolean needsRefresh(AccessToken accessToken) {
    final long expirationDiff = accessToken.getExpiration().toEpochSecond(ZoneOffset.UTC)
            - LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
    return expirationDiff <= EXPIRATION_WINDOW;
}

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.sastix.cms.server.utils.MultipartFileSender.java

public void serveResource() throws Exception {
    if (response == null || request == null) {
        return;//from ww w . j a v  a 2s .c o  m
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = Range.sublong(part, 0, part.indexOf("-"));
                long end = Range.sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }
    LOG.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    LOG.debug("Content-Disposition : {}", disposition);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            LOG.debug("Return full file");
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            Range.copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            LOG.debug("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            Range.copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                LOG.debug("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Creates a new self-signed X509 certificate
 *
 * @param pair the public/private keypair- the pubkey will be added to the cert and the private
 * key will be used to sign the certificate
 * @param subject the distinguished name of the subject
 * @param isAuthority true to make the cert a CA cert, false otherwise
 * @return//from   w w  w .j  a  va2s  .  c  o m
 */
public static X509Certificate newSelfSignedCertificate(KeyPair pair, X500Name subject, boolean isAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(subject,
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), subject, pair.getPublic());
    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(isAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        X509CertificateHolder bcCert = b.build(
                new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(pair.getPrivate()));
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(bcCert);
    } catch (CertificateException | OperatorCreationException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}