JDK-8219213 : Unable to use BodySubscribers.mapping with InputStream as mentioned in the doc
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.net
  • Affected Version: 11,12
  • Priority: P4
  • Status: Resolved
  • Resolution: Duplicate
  • Submitted: 2019-02-18
  • Updated: 2019-04-01
  • Resolved: 2019-04-01
Related Reports
Blocks :  
Description
I'm trying to convert the InputStream to GZIPInputStream using BodySubscribers.mapping as below.

Java Doc says "The mapping function is executed using the client's executor, and can therefore be used to map any response body type, including blocking InputStream, as shown in the following example which uses a well-known JSON parser to convert an InputStream into any annotated Java type."

But it doesn't work as described in the doc. It seems to be it gone into deadlock.

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodySubscriber;
import static java.net.http.HttpResponse.BodySubscribers;
import java.net.URI;
import java.io.InputStream;
import java.io.IOException;

import java.util.zip.GZIPInputStream;

public class GZip {

    public static void main(String args[]) throws Exception {
        HttpClient httpClient = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(args[0])).build();
        BodySubscriber<InputStream> upstream = BodySubscribers.ofInputStream();
        BodySubscriber<InputStream> downstream = BodySubscribers.mapping(upstream, is -> {
           try (is) {
               return new GZIPInputStream(is);
           } catch (IOException e) {}
           return null;
        });

        BodyHandler<InputStream> bh0 = rsp -> {
            return downstream;
        };
        var response = httpClient.sendAsync(request, bh0);
        var res = response.join();
        System.err.println("res:" + res.body());
    }
}

Comments
Note that although that should be working with 13 - it is not recommended to do that as it blocks an executor thread. We have ammended the API documentation in 13 to suggest alternatives: https://download.java.net/java/early_access/jdk13/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#mapping(java.net.http.HttpResponse.BodySubscriber,java.util.function.Function)
01-04-2019

Thanks [~chegar], I tested only with 12-ea releases. Will do a quick test using 13 builds.
25-02-2019

Looks like this may already be resolved by JDK-8217627 & JDK-8217264. [~arajkumar] can you please confirm?
25-02-2019