Example usage for java.time Clock systemUTC

List of usage examples for java.time Clock systemUTC

Introduction

In this page you can find the example usage for java.time Clock systemUTC.

Prototype

public static Clock systemUTC() 

Source Link

Document

Obtains a clock that returns the current instant using the best available system clock, converting to date and time using the UTC time-zone.

Usage

From source file:com.hubrick.vertx.s3.client.S3Client.java

public S3Client(Vertx vertx, S3ClientOptions s3ClientOptions) {
    this(vertx, s3ClientOptions, Clock.systemUTC());
}

From source file:org.haiku.haikudepotserver.pkg.PkgIconServiceImpl.java

@Override
public PkgIcon storePkgIconImage(InputStream input, MediaType mediaType, Integer expectedSize,
        ObjectContext context, Pkg pkg) throws IOException, BadPkgIconException {

    Preconditions.checkArgument(null != context, "the context is not supplied");
    Preconditions.checkArgument(null != input, "the input must be provided");
    Preconditions.checkArgument(null != mediaType, "the mediaType must be provided");
    Preconditions.checkArgument(null != pkg, "the pkg must be provided");

    byte[] imageData = ByteStreams.toByteArray(new BoundedInputStream(input, ICON_SIZE_LIMIT));

    Optional<PkgIcon> pkgIconOptional;
    Integer size = null;/*from w ww . j  av a2 s  .c om*/

    switch (mediaType.getCode()) {

    case MediaType.MEDIATYPE_PNG:
        ImageHelper.Size pngSize = imageHelper.derivePngSize(imageData);

        if (null == pngSize) {
            LOGGER.warn(
                    "attempt to set the bitmap (png) package icon for package {}, but the size was invalid; it is not a valid png image",
                    pkg.getName());
            throw new BadPkgIconException("invalid png");
        }

        if (!pngSize.areSides(16) && !pngSize.areSides(32) && !pngSize.areSides(64)) {
            LOGGER.warn(
                    "attempt to set the bitmap (png) package icon for package {}, but the size was invalid; it must be either 32x32 or 16x16 px, but was {}",
                    pkg.getName(), pngSize.toString());
            throw new BadPkgIconException("non-square sizing or unexpected sizing");
        }

        if (null != expectedSize && !pngSize.areSides(expectedSize)) {
            LOGGER.warn(
                    "attempt to set the bitmap (png) package icon for package {}, but the size did not match the expected size",
                    pkg.getName());
            throw new BadPkgIconException("size of image was not as expected");
        }

        try {
            imageData = pngOptimizationService.optimize(imageData);
        } catch (IOException ioe) {
            throw new RuntimeException("the png optimization process has failed; ", ioe);
        }

        size = pngSize.width;
        pkgIconOptional = pkg.getPkgIcon(mediaType, pngSize.width);
        break;

    case MediaType.MEDIATYPE_HAIKUVECTORICONFILE:
        if (!imageHelper.looksLikeHaikuVectorIconFormat(imageData)) {
            LOGGER.warn(
                    "attempt to set the vector (hvif) package icon for package {}, but the data does not look like hvif",
                    pkg.getName());
            throw new BadPkgIconException();
        }
        pkgIconOptional = pkg.getPkgIcon(mediaType, null);
        break;

    default:
        throw new IllegalStateException("unhandled media type; " + mediaType.getCode());

    }

    PkgIconImage pkgIconImage;

    if (pkgIconOptional.isPresent()) {
        pkgIconImage = pkgIconOptional.get().getPkgIconImage();
    } else {
        PkgIcon pkgIcon = context.newObject(PkgIcon.class);
        pkg.addToManyTarget(Pkg.PKG_ICONS.getName(), pkgIcon, true);
        pkgIcon.setMediaType(mediaType);
        pkgIcon.setSize(size);
        pkgIconImage = context.newObject(PkgIconImage.class);
        pkgIcon.addToManyTarget(PkgIcon.PKG_ICON_IMAGES.getName(), pkgIconImage, true);
        pkgIconOptional = Optional.of(pkgIcon);
    }

    pkgIconImage.setData(imageData);
    pkg.setModifyTimestamp();
    pkg.setIconModifyTimestamp(new java.sql.Timestamp(Clock.systemUTC().millis()));
    renderedPkgIconRepository.evict(context, pkg);

    if (null != size) {
        LOGGER.info("the icon {}px for package {} has been updated", size, pkg.getName());
    } else {
        LOGGER.info("the icon for package {} has been updated", pkg.getName());
    }

    PkgIcon pkgIcon = pkgIconOptional.orElseThrow(IllegalStateException::new);

    for (Pkg subordinatePkg : pkgService.findSubordinatePkgsForMainPkg(context, pkg.getName())) {
        replicatePkgIcon(context, pkgIcon, subordinatePkg);
    }

    return pkgIcon;
}

From source file:org.openrepose.filters.custom.extractdeviceid.ExtractDeviceIdFilter.java

static String getRetryString(Header[] headers, int statusCode) {
    String rtn;/* w  ww. j a va2 s.  c  om*/
    Object[] retryHeaders = Arrays.stream(headers).filter(header -> header.getName().equals(RETRY_AFTER))
            .toArray();
    if (retryHeaders.length < 1) {
        LOG.info("Missing {} header on Auth Response status code: {}", RETRY_AFTER, statusCode);
        final ZonedDateTime zdt = ZonedDateTime.now(Clock.systemUTC());
        zdt.plusSeconds(5);
        rtn = zdt.format(RFC_1123_DATE_TIME);
    } else {
        rtn = ((Header) retryHeaders[0]).getValue();
    }
    return rtn;
}

From source file:net.morimekta.idltool.IdlUtils.java

public static String formatAgo(long timestamp) {
    Instant instant = Instant.ofEpochSecond(timestamp / 1000);
    LocalDateTime local = instant.atZone(Clock.systemUTC().getZone())
            .withZoneSameInstant(Clock.systemDefaultZone().getZone()).toLocalDateTime();
    return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(local).replaceAll("[T]", " ");
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

/**
 * Factory for SAML realm.//ww  w .j a  va  2 s  .  c  o m
 * This is not a constructor as it needs to initialise a number of components before delegating to
 * {@link #SamlRealm}
 */
public static SamlRealm create(RealmConfig config, SSLService sslService, ResourceWatcherService watcherService,
        UserRoleMapper roleMapper) throws Exception {
    final Logger logger = config.logger(SamlRealm.class);
    SamlUtils.initialize(logger);

    if (TokenService.isTokenServiceEnabled(config.globalSettings()) == false) {
        throw new IllegalStateException("SAML requires that the token service be enabled ("
                + XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey() + ")");
    }

    final Tuple<AbstractReloadingMetadataResolver, Supplier<EntityDescriptor>> tuple = initializeResolver(
            logger, config, sslService, watcherService);
    final AbstractReloadingMetadataResolver metadataResolver = tuple.v1();
    final Supplier<EntityDescriptor> idpDescriptor = tuple.v2();

    final SpConfiguration serviceProvider = getSpConfiguration(config);

    final Clock clock = Clock.systemUTC();
    final IdpConfiguration idpConfiguration = getIdpConfiguration(config, metadataResolver, idpDescriptor);
    final TimeValue maxSkew = CLOCK_SKEW.get(config.settings());
    final SamlAuthenticator authenticator = new SamlAuthenticator(config, clock, idpConfiguration,
            serviceProvider, maxSkew);
    final SamlLogoutRequestHandler logoutHandler = new SamlLogoutRequestHandler(config, clock, idpConfiguration,
            serviceProvider, maxSkew);

    final SamlRealm realm = new SamlRealm(config, roleMapper, authenticator, logoutHandler, idpDescriptor,
            serviceProvider);

    // the metadata resolver needs to be destroyed since it runs a timer task in the background and destroying stops it!
    realm.releasables.add(() -> metadataResolver.destroy());

    return realm;
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPObjectToRecordHandler.java

@VisibleForTesting
long getCurrentTime() {
    return Clock.systemUTC().millis();
}

From source file:alfio.manager.TicketReservationManager.java

private void reserveAdditionalServicesForReservation(int eventId, String transactionId,
        ASReservationWithOptionalCodeModification additionalServiceReservation, PromoCodeDiscount discount) {
    Optional.ofNullable(additionalServiceReservation.getAdditionalServiceId())
            .flatMap(id -> optionally(() -> additionalServiceRepository.getById(id, eventId)))
            .filter(as -> additionalServiceReservation.getQuantity() > 0
                    && (as.isFixPrice() || Optional.ofNullable(additionalServiceReservation.getAmount())
                            .filter(a -> a.compareTo(BigDecimal.ZERO) > 0).isPresent()))
            .map(as -> Pair.of(eventRepository.findById(eventId), as)).ifPresent(pair -> {
                Event e = pair.getKey();
                AdditionalService as = pair.getValue();
                IntStream.range(0, additionalServiceReservation.getQuantity()).forEach(i -> {
                    AdditionalServicePriceContainer pc = AdditionalServicePriceContainer
                            .from(additionalServiceReservation.getAmount(), as, e, discount);
                    additionalServiceItemRepository.insert(UUID.randomUUID().toString(),
                            ZonedDateTime.now(Clock.systemUTC()), transactionId, as.getId(),
                            AdditionalServiceItemStatus.PENDING, eventId, pc.getSrcPriceCts(),
                            unitToCents(pc.getFinalPrice()), unitToCents(pc.getVAT()),
                            unitToCents(pc.getAppliedDiscount()));
                });/*from w  w w .  j  a  va2s .c o m*/
            });

}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

public AuthnRequest buildAuthenticationRequest() {
    final AuthnRequest authnRequest = new SamlAuthnRequestBuilder(serviceProvider,
            SAMLConstants.SAML2_POST_BINDING_URI, idpDescriptor.get(), SAMLConstants.SAML2_REDIRECT_BINDING_URI,
            Clock.systemUTC()).nameIDPolicy(nameIdPolicy).forceAuthn(forceAuthn).build();
    if (logger.isTraceEnabled()) {
        logger.trace("Constructed SAML Authentication Request: {}", SamlUtils.samlObjectToString(authnRequest));
    }//from w w w .  j av  a  2  s. com
    return authnRequest;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

/**
 * Creates a SAML {@link LogoutRequest Single LogOut request} for the provided session, if the
 * realm and IdP configuration support SLO. Otherwise returns {@code null}
 *
 * @see SamlRealmSettings#IDP_SINGLE_LOGOUT
 *//*from ww  w  .j a  v  a 2 s .  c o m*/
public LogoutRequest buildLogoutRequest(NameID nameId, String session) {
    if (useSingleLogout) {
        final LogoutRequest logoutRequest = new SamlLogoutRequestMessageBuilder(Clock.systemUTC(),
                serviceProvider, idpDescriptor.get(), nameId, session).build();
        if (logoutRequest != null && logger.isTraceEnabled()) {
            logger.trace("Constructed SAML Logout Request: {}", SamlUtils.samlObjectToString(logoutRequest));
        }
        return logoutRequest;
    } else {
        return null;
    }

}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

/**
 * Creates a SAML {@link org.opensaml.saml.saml2.core.LogoutResponse} to the provided requestID
 *//*from  w ww .  ja va 2  s  . c  o  m*/
public LogoutResponse buildLogoutResponse(String inResponseTo) {
    final LogoutResponse logoutResponse = new SamlLogoutResponseBuilder(Clock.systemUTC(), serviceProvider,
            idpDescriptor.get(), inResponseTo, StatusCode.SUCCESS).build();
    if (logoutResponse != null && logger.isTraceEnabled()) {
        logger.trace("Constructed SAML Logout Response: {}", SamlUtils.samlObjectToString(logoutResponse));
    }
    return logoutResponse;
}