Search in sources :

Example 1 with HttpHeaders

use of com.linecorp.armeria.common.HttpHeaders in project curiostack by curioswitch.

the class StorageClient method createFile.

/**
 * Create a new file for uploading data to cloud storage.
 */
public ListenableFuture<FileWriter> createFile(String filename, Map<String, String> metadata, RequestContext ctx) {
    FileRequest request = ImmutableFileRequest.builder().name(filename).metadata(metadata).build();
    ByteBuf buf = ctx.alloc().buffer();
    try (ByteBufOutputStream os = new ByteBufOutputStream(buf)) {
        OBJECT_MAPPER.writeValue((DataOutput) os, request);
    } catch (IOException e) {
        buf.release();
        throw new UncheckedIOException("Could not serialize resource JSON to buffer.", e);
    }
    HttpData data = new ByteBufHttpData(buf, true);
    HttpHeaders headers = HttpHeaders.of(HttpMethod.POST, uploadUrl).contentType(MediaType.JSON_UTF_8);
    HttpResponse res = httpClient.execute(headers, data);
    return CompletableFuturesExtra.toListenableFuture(res.aggregate(ctx.contextAwareEventLoop()).handle((msg, t) -> {
        if (t != null) {
            throw new RuntimeException("Unexpected error creating new file.", t);
        }
        HttpHeaders responseHeaders = msg.headers();
        if (!responseHeaders.status().equals(HttpStatus.OK)) {
            throw new RuntimeException("Non-successful response when creating new file: " + responseHeaders + "\n" + msg.content().toStringUtf8());
        }
        String location = responseHeaders.get(HttpHeaderNames.LOCATION);
        String pathAndQuery = location.substring("https://www.googleapis.com/upload/storage/v1".length());
        return new FileWriter(pathAndQuery, ctx, httpClient);
    }));
}
Also used : ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ForStorage(org.curioswitch.curiostack.gcloud.storage.StorageModule.ForStorage) Singleton(javax.inject.Singleton) HttpHeaderNames(com.linecorp.armeria.common.HttpHeaderNames) MediaType(com.linecorp.armeria.common.MediaType) Inject(javax.inject.Inject) ByteBuf(io.netty.buffer.ByteBuf) HttpStatus(com.linecorp.armeria.common.HttpStatus) JsonSerialize(com.fasterxml.jackson.databind.annotation.JsonSerialize) Map(java.util.Map) HttpData(com.linecorp.armeria.common.HttpData) HttpResponse(com.linecorp.armeria.common.HttpResponse) DataOutput(java.io.DataOutput) CompletableFuturesExtra(com.spotify.futures.CompletableFuturesExtra) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) HttpMethod(com.linecorp.armeria.common.HttpMethod) Immutable(org.immutables.value.Value.Immutable) ByteBufHttpData(com.linecorp.armeria.unsafe.ByteBufHttpData) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) RequestContext(com.linecorp.armeria.common.RequestContext) UncheckedIOException(java.io.UncheckedIOException) HttpClient(com.linecorp.armeria.client.HttpClient) HttpHeaders(com.linecorp.armeria.common.HttpHeaders) JsonDeserialize(com.fasterxml.jackson.databind.annotation.JsonDeserialize) HttpHeaders(com.linecorp.armeria.common.HttpHeaders) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) HttpResponse(com.linecorp.armeria.common.HttpResponse) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ByteBuf(io.netty.buffer.ByteBuf) HttpData(com.linecorp.armeria.common.HttpData) ByteBufHttpData(com.linecorp.armeria.unsafe.ByteBufHttpData) ByteBufHttpData(com.linecorp.armeria.unsafe.ByteBufHttpData)

Example 2 with HttpHeaders

use of com.linecorp.armeria.common.HttpHeaders in project curiostack by curioswitch.

the class GooglePublicKeysManager method refresh.

private CompletableFuture<CachedPublicKeys> refresh() {
    return googleApisClient.get(CERTS_PATH).aggregate().handle((msg, t) -> {
        if (t != null) {
            throw new IllegalStateException("Failed to refresh Google public keys.", t);
        }
        if (!msg.status().equals(HttpStatus.OK)) {
            throw new IllegalStateException("Non-200 status code when fetching certificates.");
        }
        // Do the same simple header parsing as the upstream library.
        HttpHeaders headers = msg.headers();
        String cacheControl = headers.get(HttpHeaderNames.CACHE_CONTROL);
        long cacheTimeSecs = 0;
        if (cacheControl != null) {
            for (String arg : CACHE_CONTROL_SPLITTER.split(cacheControl)) {
                Matcher m = MAX_AGE_PATTERN.matcher(arg);
                if (m.matches()) {
                    cacheTimeSecs = Long.valueOf(m.group(1));
                    break;
                }
            }
        }
        cacheTimeSecs -= headers.getInt(HttpHeaderNames.AGE, 0);
        cacheTimeSecs = Math.max(0, cacheTimeSecs);
        Instant expirationTime = clock.instant().plusSeconds(cacheTimeSecs).minus(EXPIRATION_SKEW);
        final JsonNode tree;
        try {
            tree = OBJECT_MAPPER.readTree(msg.content().array());
        } catch (IOException e) {
            throw new UncheckedIOException("Could not parse certificates.", e);
        }
        List<PublicKey> keys = Streams.stream(tree.elements()).map(valueNode -> {
            try {
                return CERTIFICATE_FACTORY.generateCertificate(new ByteArrayInputStream(valueNode.textValue().getBytes(StandardCharsets.UTF_8))).getPublicKey();
            } catch (CertificateException e) {
                throw new IllegalArgumentException("Could not decode certificate.", e);
            }
        }).collect(toImmutableList());
        return ImmutableCachedPublicKeys.builder().expirationTime(expirationTime).addAllKeys(keys).build();
    });
}
Also used : CommonPools(com.linecorp.armeria.common.CommonPools) CertificateFactory(java.security.cert.CertificateFactory) Style(org.immutables.value.Value.Style) CompletableFuture(java.util.concurrent.CompletableFuture) Singleton(javax.inject.Singleton) HttpHeaderNames(com.linecorp.armeria.common.HttpHeaderNames) Inject(javax.inject.Inject) AsyncRefreshingValue(org.curioswitch.curiostack.gcloud.core.util.AsyncRefreshingValue) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpStatus(com.linecorp.armeria.common.HttpStatus) WebClient(com.linecorp.armeria.client.WebClient) Duration(java.time.Duration) JsonNode(com.fasterxml.jackson.databind.JsonNode) Splitter(com.google.common.base.Splitter) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) PublicKey(java.security.PublicKey) CertificateException(java.security.cert.CertificateException) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Immutable(org.immutables.value.Value.Immutable) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) HttpHeaders(com.linecorp.armeria.common.HttpHeaders) ImplementationVisibility(org.immutables.value.Value.Style.ImplementationVisibility) Clock(java.time.Clock) Pattern(java.util.regex.Pattern) BuilderVisibility(org.immutables.value.Value.Style.BuilderVisibility) RetryingGoogleApis(org.curioswitch.curiostack.gcloud.core.RetryingGoogleApis) HttpHeaders(com.linecorp.armeria.common.HttpHeaders) Matcher(java.util.regex.Matcher) PublicKey(java.security.PublicKey) Instant(java.time.Instant) JsonNode(com.fasterxml.jackson.databind.JsonNode) UncheckedIOException(java.io.UncheckedIOException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 3 with HttpHeaders

use of com.linecorp.armeria.common.HttpHeaders in project curiostack by curioswitch.

the class PublicKeysManager method refresh.

private CompletableFuture<CachedPublicKeys> refresh() {
    return httpClient.get(path).aggregate().handle((msg, t) -> {
        if (t != null) {
            throw new IllegalStateException("Failed to refresh Google public keys.", t);
        }
        if (!msg.status().equals(HttpStatus.OK)) {
            throw new IllegalStateException("Non-200 status code when fetching certificates.");
        }
        // Do the same simple header parsing as the upstream library.
        HttpHeaders headers = msg.headers();
        String cacheControl = headers.get(HttpHeaderNames.CACHE_CONTROL);
        long cacheTimeSecs = 0;
        if (cacheControl != null) {
            for (String arg : CACHE_CONTROL_SPLITTER.split(cacheControl)) {
                Matcher m = MAX_AGE_PATTERN.matcher(arg);
                if (m.matches()) {
                    cacheTimeSecs = Long.valueOf(m.group(1));
                    break;
                }
            }
        }
        cacheTimeSecs -= headers.getInt(HttpHeaderNames.AGE, 0);
        cacheTimeSecs = Math.max(0, cacheTimeSecs);
        Instant expirationTime = clock.instant().plusSeconds(cacheTimeSecs).minus(EXPIRATION_SKEW);
        final JsonNode tree;
        try {
            tree = OBJECT_MAPPER.readTree(msg.content().array());
        } catch (IOException e) {
            throw new UncheckedIOException("Could not parse certificates.", e);
        }
        Map<String, PublicKey> keys = Streams.stream(tree.fields()).map(entry -> {
            byte[] publicKeyPem = entry.getValue().textValue().getBytes(StandardCharsets.UTF_8);
            PublicKey publicKey = KeyUtil.loadPublicKey(publicKeyPem);
            return new SimpleImmutableEntry<>(entry.getKey(), publicKey);
        }).collect(toImmutableMap(Entry::getKey, Entry::getValue));
        return ImmutableCachedPublicKeys.builder().expirationTime(expirationTime).putAllKeys(keys).build();
    });
}
Also used : CommonPools(com.linecorp.armeria.common.CommonPools) CompletableFuture(java.util.concurrent.CompletableFuture) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) HttpHeaderNames(com.linecorp.armeria.common.HttpHeaderNames) Provided(com.google.auto.factory.Provided) KeyUtil(org.curioswitch.common.server.framework.crypto.KeyUtil) AsyncRefreshingValue(org.curioswitch.curiostack.gcloud.core.util.AsyncRefreshingValue) Matcher(java.util.regex.Matcher) HttpStatus(com.linecorp.armeria.common.HttpStatus) WebClient(com.linecorp.armeria.client.WebClient) Duration(java.time.Duration) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) URI(java.net.URI) RetryingClient(com.linecorp.armeria.client.retry.RetryingClient) Splitter(com.google.common.base.Splitter) AutoFactory(com.google.auto.factory.AutoFactory) RetryRule(com.linecorp.armeria.client.retry.RetryRule) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) PublicKey(java.security.PublicKey) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Immutable(org.immutables.value.Value.Immutable) LoggingClient(com.linecorp.armeria.client.logging.LoggingClient) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) Factory(org.curioswitch.common.server.framework.auth.jwt.PublicKeysManager.Factory) HttpHeaders(com.linecorp.armeria.common.HttpHeaders) CurioStyle(org.curioswitch.common.server.framework.immutables.CurioStyle) Entry(java.util.Map.Entry) Clock(java.time.Clock) Pattern(java.util.regex.Pattern) HttpHeaders(com.linecorp.armeria.common.HttpHeaders) Matcher(java.util.regex.Matcher) PublicKey(java.security.PublicKey) Instant(java.time.Instant) JsonNode(com.fasterxml.jackson.databind.JsonNode) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException)

Aggregations

ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 HttpHeaderNames (com.linecorp.armeria.common.HttpHeaderNames)3 HttpHeaders (com.linecorp.armeria.common.HttpHeaders)3 HttpStatus (com.linecorp.armeria.common.HttpStatus)3 IOException (java.io.IOException)3 UncheckedIOException (java.io.UncheckedIOException)3 Immutable (org.immutables.value.Value.Immutable)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Splitter (com.google.common.base.Splitter)2 Streams (com.google.common.collect.Streams)2 WebClient (com.linecorp.armeria.client.WebClient)2 CommonPools (com.linecorp.armeria.common.CommonPools)2 StandardCharsets (java.nio.charset.StandardCharsets)2 PublicKey (java.security.PublicKey)2 Clock (java.time.Clock)2 Duration (java.time.Duration)2 Instant (java.time.Instant)2 Map (java.util.Map)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Inject (javax.inject.Inject)2