ok2c commented on code in PR #681: URL: https://github.com/apache/httpcomponents-client/pull/681#discussion_r2240824434
########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/ContentCompressionAsyncExec.java: ########## @@ -0,0 +1,212 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * <http://www.apache.org/>. + * + */ +package org.apache.hc.client5.http.impl.async; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Optional; +import java.util.function.UnaryOperator; + +import org.apache.hc.client5.http.async.AsyncExecCallback; +import org.apache.hc.client5.http.async.AsyncExecChain; +import org.apache.hc.client5.http.async.AsyncExecChainHandler; +import org.apache.hc.client5.http.async.methods.InflatingAsyncEntityConsumer; +import org.apache.hc.client5.http.entity.compress.ContentCoding; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.Internal; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.EntityDetails; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HeaderElement; +import org.apache.hc.core5.http.HttpException; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.config.Lookup; +import org.apache.hc.core5.http.config.RegistryBuilder; +import org.apache.hc.core5.http.message.BasicHeaderValueParser; +import org.apache.hc.core5.http.message.MessageSupport; +import org.apache.hc.core5.http.message.ParserCursor; +import org.apache.hc.core5.http.nio.AsyncDataConsumer; +import org.apache.hc.core5.http.nio.AsyncEntityConsumer; +import org.apache.hc.core5.http.nio.AsyncEntityProducer; +import org.apache.hc.core5.util.Args; + +/** + * {@code AsyncExecChainHandler} that transparently decompresses HTTP responses + * according to the server-supplied {@code Content-Encoding} header. + * + * <p>The executor wraps the downstream {@link AsyncEntityConsumer} with a + * decoder <em>per response</em>. Supported codings and their factories are + * supplied through a {@link LinkedHashMap} whose insertion order is preserved + * when generating the {@code Accept-Encoding} request header.</p> + * + * <p>By default (zero-arg constructor) the handler enables the + * {@code deflate} coding and silently ignores unknown codings. + * Additional codecs can be registered at runtime via + * {@link org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder#setContentDecoderMap(java.util.LinkedHashMap)}.</p> + * + * @since 5.6 + */ +@Contract(threading = ThreadingBehavior.STATELESS) +@Internal +public final class ContentCompressionAsyncExec implements AsyncExecChainHandler { + + private final Header acceptEncoding; + private final Lookup<UnaryOperator<AsyncEntityConsumer<?>>> decoders; + private final boolean ignoreUnknown; + + /** + * Creates an executor that advertises and supports exactly the codings + * listed in {@code decoderMap}. + * + * @param decoderMap a {@link LinkedHashMap} whose keys are lower-case + * tokens (e.g. {@code "gzip"}) and whose values are + * functions that wrap a downstream + * {@link AsyncEntityConsumer}<br> + * <strong>Note:</strong> the map must be a + * {@code LinkedHashMap} so the insertion order—and + * thus the codec preference—is retained. + * @param ignoreUnknown if {@code true} unknown server codings are ignored; + * otherwise a {@link HttpException} is thrown. + */ + public ContentCompressionAsyncExec( + final LinkedHashMap<String, UnaryOperator<AsyncEntityConsumer<?>>> decoderMap, + final boolean ignoreUnknown) { + + Args.notEmpty(decoderMap, "Decoder map"); + + this.acceptEncoding = MessageSupport.headerOfTokens( + HttpHeaders.ACCEPT_ENCODING, new ArrayList<>(decoderMap.keySet())); + + final RegistryBuilder<UnaryOperator<AsyncEntityConsumer<?>>> rb = RegistryBuilder.create(); + decoderMap.forEach(rb::register); + this.decoders = rb.build(); + this.ignoreUnknown = ignoreUnknown; + } + + /** + * Convenience constructor equivalent to + * {@code new ContentCompressionAsyncExec(true)}. + */ + public ContentCompressionAsyncExec() { + final LinkedHashMap<String, UnaryOperator<AsyncEntityConsumer<?>>> defaultMap = + new LinkedHashMap<>(); + + defaultMap.put(ContentCoding.DEFLATE.token(), + d -> new InflatingAsyncEntityConsumer<>(d, null)); + + this.acceptEncoding = MessageSupport.headerOfTokens( + HttpHeaders.ACCEPT_ENCODING, Collections.singletonList(ContentCoding.DEFLATE.token())); + + this.decoders = RegistryBuilder.<UnaryOperator<AsyncEntityConsumer<?>>>create() + .register(ContentCoding.DEFLATE.token(), + defaultMap.get(ContentCoding.DEFLATE.token())) + .build(); + this.ignoreUnknown = true; + } + + + @Override + public void execute(final HttpRequest request, + final AsyncEntityProducer producer, + final AsyncExecChain.Scope scope, + final AsyncExecChain chain, + final AsyncExecCallback cb) + throws IOException, HttpException { + + final HttpClientContext ctx = scope != null ? scope.clientContext : HttpClientContext.create(); + final boolean enabled = ctx.getRequestConfigOrDefault().isContentCompressionEnabled(); + + if (enabled && !request.containsHeader(HttpHeaders.ACCEPT_ENCODING)) { + request.addHeader(acceptEncoding); + } + + chain.proceed(request, producer, scope, new AsyncExecCallback() { + + @Override + public AsyncDataConsumer handleResponse(final HttpResponse rsp, + final EntityDetails details) + throws HttpException, IOException { + + if (!enabled) { + return cb.handleResponse(rsp, details); + } + + final String raw = details != null && details.getContentEncoding() != null + ? details.getContentEncoding() + : Optional.ofNullable(rsp.getFirstHeader(HttpHeaders.CONTENT_ENCODING)) Review Comment: @arturobernalg This is unnecessary and can potentially produce unexpected results. The interceptor should rely on the properties of `EntityDetails` only. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: dev-unsubscr...@hc.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@hc.apache.org For additional commands, e-mail: dev-h...@hc.apache.org