Search in sources :

Example 6 with HttpResponse

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

the class StorageClient method sendMutationRequest.

private CompletableFuture<Void> sendMutationRequest(HttpMethod method, Object request, String url, EventLoop eventLoop, ByteBufAllocator alloc) {
    HttpData data = serializeRequest(request, alloc);
    RequestHeaders headers = RequestHeaders.builder(HttpMethod.POST, url).contentType(MediaType.JSON_UTF_8).build();
    HttpResponse res = httpClient.execute(headers, data);
    return res.aggregateWithPooledObjects(eventLoop, alloc).handle((msg, t) -> {
        if (t != null) {
            throw new RuntimeException("Unexpected error composing file.", t);
        }
        try {
            if (msg.status().equals(HttpStatus.OK)) {
                return null;
            } else {
                throw new IllegalStateException("Could not compose file at " + url + ": " + msg.content().toStringUtf8());
            }
        } finally {
            ReferenceCountUtil.safeRelease(msg.content());
        }
    });
}
Also used : HttpData(com.linecorp.armeria.common.HttpData) HttpResponse(com.linecorp.armeria.common.HttpResponse) RequestHeaders(com.linecorp.armeria.common.RequestHeaders)

Example 7 with HttpResponse

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

the class StorageClient method createFile.

/**
 * Create a new file for uploading data to cloud storage.
 */
public CompletableFuture<FileWriter> createFile(FileRequest request, EventLoop eventLoop, ByteBufAllocator alloc) {
    HttpData data = serializeRequest(request, alloc);
    RequestHeaders headers = RequestHeaders.builder(HttpMethod.POST, uploadUrl).contentType(MediaType.JSON_UTF_8).build();
    HttpResponse res = httpClient.execute(headers, data);
    return res.aggregate(eventLoop).handle((msg, t) -> {
        if (t != null) {
            throw new RuntimeException("Unexpected error creating new file.", t);
        }
        ResponseHeaders responseHeaders = msg.headers();
        if (!responseHeaders.status().equals(HttpStatus.OK)) {
            throw new RuntimeException("Non-successful response when creating new file at " + uploadUrl + ": " + responseHeaders + "\n" + msg.content().toStringUtf8());
        }
        String location = responseHeaders.get(HttpHeaderNames.LOCATION);
        String pathAndQuery = location.substring("https://www.googleapis.com".length());
        return new FileWriter(pathAndQuery, alloc, eventLoop, httpClient);
    });
}
Also used : HttpData(com.linecorp.armeria.common.HttpData) HttpResponse(com.linecorp.armeria.common.HttpResponse) RequestHeaders(com.linecorp.armeria.common.RequestHeaders) ResponseHeaders(com.linecorp.armeria.common.ResponseHeaders)

Example 8 with HttpResponse

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

the class GoogleCredentialsDecoratingClient method execute.

@Override
@SuppressWarnings("FutureReturnValueIgnored")
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) {
    CompletableFuture<HttpResponse> resFuture = new CompletableFuture<>();
    credentials.getRequestMetadata(URI.create(req.path()), authExecutor, new RequestMetadataCallback() {

        @Override
        public void onSuccess(Map<String, List<String>> metadata) {
            metadata.forEach((key, values) -> {
                for (String value : values) {
                    req.headers().add(HttpHeaderNames.of(key), value);
                }
            });
            try {
                ctx.contextAwareEventLoop().submit(() -> resFuture.complete(delegate().execute(ctx, req)));
            } catch (Exception e) {
                resFuture.completeExceptionally(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            resFuture.completeExceptionally(t);
        }
    });
    return HttpResponse.from(resFuture);
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) HttpResponse(com.linecorp.armeria.common.HttpResponse) Executor(java.util.concurrent.Executor) Credentials(com.google.auth.Credentials) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) ClientRequestContext(com.linecorp.armeria.client.ClientRequestContext) HttpHeaderNames(com.linecorp.armeria.common.HttpHeaderNames) Executors(java.util.concurrent.Executors) RequestMetadataCallback(com.google.auth.RequestMetadataCallback) Inject(javax.inject.Inject) HttpRequest(com.linecorp.armeria.common.HttpRequest) List(java.util.List) Map(java.util.Map) Client(com.linecorp.armeria.client.Client) SimpleDecoratingClient(com.linecorp.armeria.client.SimpleDecoratingClient) URI(java.net.URI) CompletableFuture(java.util.concurrent.CompletableFuture) HttpResponse(com.linecorp.armeria.common.HttpResponse) List(java.util.List) RequestMetadataCallback(com.google.auth.RequestMetadataCallback)

Example 9 with HttpResponse

use of com.linecorp.armeria.common.HttpResponse in project zipkin by openzipkin.

the class ElasticsearchExtension method computeStorageBuilder.

Builder computeStorageBuilder() {
    WebClientBuilder builder = WebClient.builder(baseUrl()).factory(ClientFactory.builder().useHttp2Preface(false).build());
    builder.decorator((delegate, ctx, req) -> {
        final HttpResponse response = delegate.execute(ctx, req);
        return HttpResponse.from(response.aggregate().thenApply(r -> {
            // ES will return a 'warning' response header when using deprecated api, detect this and
            // fail early so we can do something about it.
            // Example usage: https://github.com/elastic/elasticsearch/blob/3049e55f093487bb582a7e49ad624961415ba31c/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/integration/IndexPrivilegeIntegTests.java#L559
            final String warningHeader = r.headers().get("warning");
            if (warningHeader != null) {
                if (IGNORE_THESE_WARNINGS.stream().noneMatch(p -> p.matcher(warningHeader).find())) {
                    throw new IllegalArgumentException("Detected usage of deprecated API for request " + req.toString() + ":\n" + warningHeader);
                }
            }
            // Convert AggregatedHttpResponse back to HttpResponse.
            return r.toHttpResponse();
        }));
    });
    // com.linecorp.armeria.client.logging
    if (Boolean.parseBoolean(System.getenv("ES_DEBUG"))) {
        ClientOptionsBuilder options = ClientOptions.builder();
        LoggingClientBuilder loggingBuilder = LoggingClient.builder().requestLogLevel(LogLevel.INFO).successfulResponseLogLevel(LogLevel.INFO);
        options.decorator(loggingBuilder.newDecorator());
        options.decorator(ContentPreviewingClient.newDecorator(Integer.MAX_VALUE));
        builder.options(options.build());
    }
    WebClient client = builder.build();
    return ElasticsearchStorage.newBuilder(new ElasticsearchStorage.LazyHttpClient() {

        @Override
        public WebClient get() {
            return client;
        }

        @Override
        public void close() {
            client.endpointGroup().close();
        }

        @Override
        public String toString() {
            return client.uri().toString();
        }
    }).index("zipkin-test").flushOnWrites(true);
}
Also used : Wait(org.testcontainers.containers.wait.strategy.Wait) WebClientBuilder(com.linecorp.armeria.client.WebClientBuilder) Builder(zipkin2.elasticsearch.ElasticsearchStorage.Builder) ClientFactory(com.linecorp.armeria.client.ClientFactory) HttpResponse(com.linecorp.armeria.common.HttpResponse) LogLevel(com.linecorp.armeria.common.logging.LogLevel) Logger(org.slf4j.Logger) ContentPreviewingClient(com.linecorp.armeria.client.logging.ContentPreviewingClient) TestAbortedException(org.opentest4j.TestAbortedException) LoggerFactory(org.slf4j.LoggerFactory) ClientOptions(com.linecorp.armeria.client.ClientOptions) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) LoggingClient(com.linecorp.armeria.client.logging.LoggingClient) TestInfo(org.junit.jupiter.api.TestInfo) ElasticsearchStorage(zipkin2.elasticsearch.ElasticsearchStorage) LoggingClientBuilder(com.linecorp.armeria.client.logging.LoggingClientBuilder) IGNORE_THESE_WARNINGS(zipkin2.elasticsearch.integration.IgnoredDeprecationWarnings.IGNORE_THESE_WARNINGS) ClientOptionsBuilder(com.linecorp.armeria.client.ClientOptionsBuilder) BeforeAllCallback(org.junit.jupiter.api.extension.BeforeAllCallback) Slf4jLogConsumer(org.testcontainers.containers.output.Slf4jLogConsumer) AfterAllCallback(org.junit.jupiter.api.extension.AfterAllCallback) WebClient(com.linecorp.armeria.client.WebClient) GenericContainer(org.testcontainers.containers.GenericContainer) DockerImageName.parse(org.testcontainers.utility.DockerImageName.parse) WebClientBuilder(com.linecorp.armeria.client.WebClientBuilder) ElasticsearchStorage(zipkin2.elasticsearch.ElasticsearchStorage) HttpResponse(com.linecorp.armeria.common.HttpResponse) ClientOptionsBuilder(com.linecorp.armeria.client.ClientOptionsBuilder) WebClient(com.linecorp.armeria.client.WebClient) LoggingClientBuilder(com.linecorp.armeria.client.logging.LoggingClientBuilder)

Aggregations

HttpResponse (com.linecorp.armeria.common.HttpResponse)9 HttpData (com.linecorp.armeria.common.HttpData)7 HttpRequest (com.linecorp.armeria.common.HttpRequest)5 WebClient (com.linecorp.armeria.client.WebClient)4 HttpHeaderNames (com.linecorp.armeria.common.HttpHeaderNames)4 RequestHeaders (com.linecorp.armeria.common.RequestHeaders)4 HttpHeaders (com.linecorp.armeria.common.HttpHeaders)3 HttpStatus (com.linecorp.armeria.common.HttpStatus)3 ResponseHeaders (com.linecorp.armeria.common.ResponseHeaders)3 List (java.util.List)3 Map (java.util.Map)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 ClientOptions (com.linecorp.armeria.client.ClientOptions)2 AggregatedHttpRequest (com.linecorp.armeria.common.AggregatedHttpRequest)2 HttpMethod (com.linecorp.armeria.common.HttpMethod)2 RequestContext (com.linecorp.armeria.common.RequestContext)2 SafeCloseable (com.linecorp.armeria.common.util.SafeCloseable)2 ByteBuf (io.netty.buffer.ByteBuf)2 Unpooled (io.netty.buffer.Unpooled)2 IOException (java.io.IOException)2