jdk/src/java.httpclient/share/classes/java/net/http/Http1Response.java
changeset 42483 3850c235c3fb
parent 42482 15297dde0d55
parent 42479 a80dbf731cbe
child 42489 a9e4de33da2e
equal deleted inserted replaced
42482:15297dde0d55 42483:3850c235c3fb
     1 /*
       
     2  * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package java.net.http;
       
    27 
       
    28 import java.io.IOException;
       
    29 import java.nio.ByteBuffer;
       
    30 import java.util.List;
       
    31 import java.util.Map;
       
    32 import java.util.Set;
       
    33 import java.util.function.LongConsumer;
       
    34 import static java.net.http.HttpClient.Version.HTTP_1_1;
       
    35 
       
    36 /**
       
    37  * Handles a HTTP/1.1 response in two blocking calls. readHeaders() and
       
    38  * readBody(). There can be more than one of these per Http exchange.
       
    39  */
       
    40 class Http1Response {
       
    41 
       
    42     private ResponseContent content;
       
    43     private final HttpRequestImpl request;
       
    44     HttpResponseImpl response;
       
    45     private final HttpConnection connection;
       
    46     private ResponseHeaders headers;
       
    47     private int responseCode;
       
    48     private ByteBuffer buffer; // same buffer used for reading status line and headers
       
    49     private final Http1Exchange exchange;
       
    50     private final boolean redirecting; // redirecting
       
    51     private boolean return2Cache; // return connection to cache when finished
       
    52 
       
    53     Http1Response(HttpConnection conn, Http1Exchange exchange) {
       
    54         this.request = exchange.request();
       
    55         this.exchange = exchange;
       
    56         this.connection = conn;
       
    57         this.redirecting = false;
       
    58         buffer = connection.getRemaining();
       
    59     }
       
    60 
       
    61     // called when the initial read should come from a buffer left
       
    62     // over from a previous response.
       
    63     void setBuffer(ByteBuffer buffer) {
       
    64         this.buffer = buffer;
       
    65     }
       
    66 
       
    67     @SuppressWarnings("unchecked")
       
    68     public void readHeaders() throws IOException {
       
    69         String statusline = readStatusLine();
       
    70         if (statusline == null) {
       
    71             if (Log.errors()) {
       
    72                 Log.logError("Connection closed. Retry");
       
    73             }
       
    74             connection.close();
       
    75             // connection was closed
       
    76             throw new IOException("Connection closed");
       
    77         }
       
    78         if (!statusline.startsWith("HTTP/1.")) {
       
    79             throw new IOException("Invalid status line: " + statusline);
       
    80         }
       
    81         char c = statusline.charAt(7);
       
    82         responseCode = Integer.parseInt(statusline.substring(9, 12));
       
    83 
       
    84         headers = new ResponseHeaders(connection, buffer);
       
    85         headers.initHeaders();
       
    86         if (Log.headers()) {
       
    87             logHeaders(headers);
       
    88         }
       
    89         response = new HttpResponseImpl(responseCode,
       
    90                                         exchange.exchange,
       
    91                                         headers,
       
    92                                         null,
       
    93                                         connection.sslParameters(),
       
    94                                         HTTP_1_1,
       
    95                                         connection);
       
    96     }
       
    97 
       
    98     private boolean finished;
       
    99 
       
   100     synchronized void completed() {
       
   101         finished = true;
       
   102     }
       
   103 
       
   104     synchronized boolean finished() {
       
   105         return finished;
       
   106     }
       
   107 
       
   108     // Blocking flow controller implementation. Only works when a
       
   109     // thread is dedicated to reading response body
       
   110 
       
   111     static class FlowController implements LongConsumer {
       
   112         long window ;
       
   113 
       
   114         @Override
       
   115         public synchronized void accept(long value) {
       
   116             window += value;
       
   117             notifyAll();
       
   118         }
       
   119 
       
   120         public synchronized void request(long value) throws InterruptedException {
       
   121             while (window < value) {
       
   122                 wait();
       
   123             }
       
   124             window -= value;
       
   125         }
       
   126     }
       
   127 
       
   128     FlowController flowController;
       
   129 
       
   130     int fixupContentLen(int clen) {
       
   131         if (request.method().equalsIgnoreCase("HEAD")) {
       
   132             return 0;
       
   133         }
       
   134         if (clen == -1) {
       
   135             if (headers.firstValue("Transfer-encoding").orElse("")
       
   136                        .equalsIgnoreCase("chunked")) {
       
   137                 return -1;
       
   138             }
       
   139             return 0;
       
   140         }
       
   141         return clen;
       
   142     }
       
   143 
       
   144     private void returnBuffer(ByteBuffer buf) {
       
   145         // not currently used, but will be when we change SSL to use fixed
       
   146         // sized buffers and a single buffer pool for HttpClientImpl
       
   147     }
       
   148 
       
   149     @SuppressWarnings("unchecked")
       
   150     public <T> T readBody(java.net.http.HttpResponse.BodyProcessor<T> p,
       
   151                           boolean return2Cache)
       
   152         throws IOException
       
   153     {
       
   154         T body = null; // TODO: check null case below
       
   155         this.return2Cache = return2Cache;
       
   156         final java.net.http.HttpResponse.BodyProcessor<T> pusher = p;
       
   157 
       
   158         int clen0 = headers.getContentLength();
       
   159         final int clen = fixupContentLen(clen0);
       
   160 
       
   161         flowController = new FlowController();
       
   162 
       
   163         body = pusher.onResponseBodyStart(clen, headers, flowController);
       
   164 
       
   165         ExecutorWrapper executor;
       
   166         if (body == null) {
       
   167             executor = ExecutorWrapper.callingThread();
       
   168         } else {
       
   169             executor = request.client().executorWrapper();
       
   170         }
       
   171 
       
   172         final ResponseHeaders h = headers;
       
   173         if (body == null) {
       
   174             content = new ResponseContent(connection,
       
   175                                           clen,
       
   176                                           h,
       
   177                                           pusher,
       
   178                                           flowController);
       
   179             content.pushBody(headers.getResidue());
       
   180             body = pusher.onResponseComplete();
       
   181             completed();
       
   182             onFinished();
       
   183             return body;
       
   184         } else {
       
   185             executor.execute(() -> {
       
   186                     try {
       
   187                         content = new ResponseContent(connection,
       
   188                                                       clen,
       
   189                                                       h,
       
   190                                                       pusher,
       
   191                                                       flowController);
       
   192                         content.pushBody(headers.getResidue());
       
   193                         pusher.onResponseComplete();
       
   194                         completed();
       
   195                         onFinished();
       
   196                     } catch (Throwable e) {
       
   197                         pusher.onResponseError(e);
       
   198                     }
       
   199                 },
       
   200                 () -> response.getAccessControlContext());
       
   201         }
       
   202         return body;
       
   203     }
       
   204 
       
   205     private void onFinished() {
       
   206         connection.buffer = content.getResidue();
       
   207         if (return2Cache) {
       
   208             connection.returnToCache(headers);
       
   209         }
       
   210     }
       
   211 
       
   212     private void logHeaders(ResponseHeaders headers) {
       
   213         Map<String, List<String>> h = headers.mapInternal();
       
   214         Set<String> keys = h.keySet();
       
   215         Set<Map.Entry<String, List<String>>> entries = h.entrySet();
       
   216         for (Map.Entry<String, List<String>> entry : entries) {
       
   217             String key = entry.getKey();
       
   218             StringBuilder sb = new StringBuilder();
       
   219             sb.append(key).append(": ");
       
   220             List<String> values = entry.getValue();
       
   221             if (values != null) {
       
   222                 for (String value : values) {
       
   223                     sb.append(value).append(' ');
       
   224                 }
       
   225             }
       
   226             Log.logHeaders(sb.toString());
       
   227         }
       
   228     }
       
   229 
       
   230     HttpResponseImpl response() {
       
   231         return response;
       
   232     }
       
   233 
       
   234     boolean redirecting() {
       
   235         return redirecting;
       
   236     }
       
   237 
       
   238     HttpHeaders responseHeaders() {
       
   239         return headers;
       
   240     }
       
   241 
       
   242     int responseCode() {
       
   243         return responseCode;
       
   244     }
       
   245 
       
   246     static final char CR = '\r';
       
   247     static final char LF = '\n';
       
   248 
       
   249     private ByteBuffer getBuffer() throws IOException {
       
   250         if (buffer == null || !buffer.hasRemaining()) {
       
   251             buffer = connection.read();
       
   252         }
       
   253         return buffer;
       
   254     }
       
   255 
       
   256     ByteBuffer buffer() {
       
   257         return buffer;
       
   258     }
       
   259 
       
   260     String readStatusLine() throws IOException {
       
   261         boolean cr = false;
       
   262         StringBuilder statusLine = new StringBuilder(128);
       
   263         ByteBuffer b;
       
   264         while ((b = getBuffer()) != null) {
       
   265             byte[] buf = b.array();
       
   266             int offset = b.position();
       
   267             int len = b.limit() - offset;
       
   268 
       
   269             for (int i = 0; i < len; i++) {
       
   270                 char c = (char) buf[i+offset];
       
   271 
       
   272                 if (cr) {
       
   273                     if (c == LF) {
       
   274                         b.position(i + 1 + offset);
       
   275                         return statusLine.toString();
       
   276                     } else {
       
   277                         throw new IOException("invalid status line");
       
   278                     }
       
   279                 }
       
   280                 if (c == CR) {
       
   281                     cr = true;
       
   282                 } else {
       
   283                     statusLine.append(c);
       
   284                 }
       
   285             }
       
   286             // unlikely, but possible, that multiple reads required
       
   287             b.position(b.limit());
       
   288         }
       
   289         return null;
       
   290     }
       
   291 }