test/jdk/java/net/httpclient/RetryPost.java
branchhttp-client-branch
changeset 56652 8e00f02b7dfc
equal deleted inserted replaced
56644:23241a815199 56652:8e00f02b7dfc
       
     1 /*
       
     2  * Copyright (c) 2018, 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.
       
     8  *
       
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    12  * version 2 for more details (a copy is included in the LICENSE file that
       
    13  * accompanied this code).
       
    14  *
       
    15  * You should have received a copy of the GNU General Public License version
       
    16  * 2 along with this work; if not, write to the Free Software Foundation,
       
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    18  *
       
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    20  * or visit www.oracle.com if you need additional information or have any
       
    21  * questions.
       
    22  */
       
    23 
       
    24 /*
       
    25  * @test
       
    26  * @summary Ensure that the POST method is retied when the property is set.
       
    27  * @run testng/othervm -Djdk.httpclient.enableAllMethodRetry RetryPost
       
    28  * @run testng/othervm -Djdk.httpclient.enableAllMethodRetry=true RetryPost
       
    29  */
       
    30 
       
    31 import java.io.IOException;
       
    32 import java.io.InputStream;
       
    33 import java.io.OutputStream;
       
    34 import java.io.UncheckedIOException;
       
    35 import java.net.InetAddress;
       
    36 import java.net.InetSocketAddress;
       
    37 import java.net.ServerSocket;
       
    38 import java.net.Socket;
       
    39 import java.net.URI;
       
    40 import java.net.http.HttpClient;
       
    41 import java.net.http.HttpRequest;
       
    42 import java.net.http.HttpRequest.BodyPublishers;
       
    43 import java.net.http.HttpResponse;
       
    44 import org.testng.annotations.AfterTest;
       
    45 import org.testng.annotations.BeforeTest;
       
    46 import org.testng.annotations.DataProvider;
       
    47 import org.testng.annotations.Test;
       
    48 import static java.lang.System.out;
       
    49 import static java.net.http.HttpClient.Builder.NO_PROXY;
       
    50 import static java.net.http.HttpResponse.BodyHandlers.ofString;
       
    51 import static java.nio.charset.StandardCharsets.US_ASCII;
       
    52 import static org.testng.Assert.assertEquals;
       
    53 
       
    54 public class RetryPost {
       
    55 
       
    56     FixedLengthServer fixedLengthServer;
       
    57     String httpURIFixLen;
       
    58 
       
    59     static final String RESPONSE_BODY =
       
    60             "You use a glass mirror to see your face: you use works of art to see your soul.";
       
    61 
       
    62     @DataProvider(name = "uris")
       
    63     public Object[][] variants() {
       
    64         return new Object[][] {
       
    65                 { httpURIFixLen, true  },
       
    66                 { httpURIFixLen, false },
       
    67         };
       
    68     }
       
    69 
       
    70     static final int ITERATION_COUNT = 3;
       
    71 
       
    72     static final String REQUEST_BODY = "Body";
       
    73 
       
    74     @Test(dataProvider = "uris")
       
    75     void testSynchronousPOST(String url, boolean sameClient) throws Exception  {
       
    76         out.print("---\n");
       
    77         HttpClient client = null;
       
    78         for (int i=0; i< ITERATION_COUNT; i++) {
       
    79             if (!sameClient || client == null)
       
    80                 client = HttpClient.newBuilder().proxy(NO_PROXY).build();
       
    81             HttpRequest request = HttpRequest.newBuilder(URI.create(url))
       
    82                     .POST(BodyPublishers.ofString(REQUEST_BODY))
       
    83                     .build();
       
    84             HttpResponse<String> response = client.send(request, ofString());
       
    85             String body = response.body();
       
    86             out.println(response + ": " + body);
       
    87             assertEquals(response.statusCode(), 200);
       
    88             assertEquals(body, RESPONSE_BODY);
       
    89         }
       
    90     }
       
    91 
       
    92     @Test(dataProvider = "uris")
       
    93     void testAsynchronousPOST(String url, boolean sameClient) {
       
    94         out.print("---\n");
       
    95         HttpClient client = null;
       
    96         for (int i=0; i< ITERATION_COUNT; i++) {
       
    97             if (!sameClient || client == null)
       
    98                 client = HttpClient.newBuilder().proxy(NO_PROXY).build();
       
    99             HttpRequest request = HttpRequest.newBuilder(URI.create(url))
       
   100                     .POST(BodyPublishers.ofString(REQUEST_BODY))
       
   101                     .build();
       
   102             client.sendAsync(request, ofString())
       
   103                     .thenApply(r -> { out.println(r + ": " + r.body()); return r; })
       
   104                     .thenApply(r -> { assertEquals(r.statusCode(), 200); return r; })
       
   105                     .thenApply(HttpResponse::body)
       
   106                     .thenAccept(b -> assertEquals(b, RESPONSE_BODY))
       
   107                     .join();
       
   108         }
       
   109     }
       
   110 
       
   111 
       
   112     /**
       
   113      * A server that issues a valid fixed-length reply on even requests, and
       
   114      * immediately closes the connection on odd requests ( tick-tock ).
       
   115      */
       
   116     static class FixedLengthServer extends Thread implements AutoCloseable {
       
   117 
       
   118         static final String RESPONSE_HEADERS =
       
   119                 "HTTP/1.1 200 OK\r\n" +
       
   120                 "Content-Type: text/html; charset=utf-8\r\n" +
       
   121                 "Content-Length: " + RESPONSE_BODY.length() + "\r\n" +
       
   122                 "Connection: close\r\n\r\n";
       
   123 
       
   124         static final String RESPONSE = RESPONSE_HEADERS + RESPONSE_BODY;
       
   125 
       
   126         private final ServerSocket ss;
       
   127         private volatile boolean closed;
       
   128         private int invocationTimes;
       
   129 
       
   130         FixedLengthServer() throws IOException {
       
   131             super("FixedLengthServer");
       
   132             ss = new ServerSocket();
       
   133             ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
       
   134             this.start();
       
   135         }
       
   136 
       
   137         public int getPort() { return ss.getLocalPort(); }
       
   138 
       
   139         @Override
       
   140         public void run() {
       
   141             while (!closed) {
       
   142                 try (Socket s = ss.accept()) {
       
   143                     invocationTimes++;
       
   144                     out.print("FixedLengthServer: got connection ");
       
   145                     if ((invocationTimes & 0x1) == 0x1) {
       
   146                         out.println(" closing immediately");
       
   147                         s.close();
       
   148                         continue;
       
   149                     }
       
   150                     InputStream is = s.getInputStream();
       
   151                     URI requestMethod = readRequestMethod(is);
       
   152                     out.print(requestMethod + " ");
       
   153                     URI uriPath = readRequestPath(is);
       
   154                     out.println(uriPath);
       
   155                     readRequestHeaders(is);
       
   156                     byte[] body = is.readNBytes(4);
       
   157                     assert body.length == REQUEST_BODY.length() :
       
   158                             "Unexpected request body " + body.length;
       
   159 
       
   160                     OutputStream os = s.getOutputStream();
       
   161                     out.println("Server: writing response bytes");
       
   162                     byte[] responseBytes = RESPONSE.getBytes(US_ASCII);
       
   163                     os.write(responseBytes);
       
   164                 } catch (IOException e) {
       
   165                     if (!closed)
       
   166                         throw new UncheckedIOException("Unexpected", e);
       
   167                 }
       
   168             }
       
   169         }
       
   170 
       
   171         @Override
       
   172         public void close() {
       
   173             if (closed)
       
   174                 return;
       
   175             closed = true;
       
   176             try {
       
   177                 ss.close();
       
   178             } catch (IOException e) {
       
   179                 throw new UncheckedIOException("Unexpected", e);
       
   180             }
       
   181         }
       
   182 
       
   183         static final byte[] requestEnd = new byte[] { '\r', '\n', '\r', '\n' };
       
   184 
       
   185         // Read the request method
       
   186         static URI readRequestMethod(InputStream is) throws IOException {
       
   187             StringBuilder sb = new StringBuilder();
       
   188             int r;
       
   189             while ((r = is.read()) != -1 && r != 0x20) {
       
   190                 sb.append((char)r);
       
   191             }
       
   192             return URI.create(sb.toString());
       
   193         }
       
   194 
       
   195         // Read the request URI path
       
   196         static URI readRequestPath(InputStream is) throws IOException {
       
   197             StringBuilder sb = new StringBuilder();
       
   198             int r;
       
   199             while ((r = is.read()) != -1 && r != 0x20) {
       
   200                 sb.append((char)r);
       
   201             }
       
   202             return URI.create(sb.toString());
       
   203         }
       
   204 
       
   205         // Read until the end of a HTTP request headers
       
   206         static void readRequestHeaders(InputStream is) throws IOException {
       
   207             int requestEndCount = 0, r;
       
   208             while ((r = is.read()) != -1) {
       
   209                 if (r == requestEnd[requestEndCount]) {
       
   210                     requestEndCount++;
       
   211                     if (requestEndCount == 4) {
       
   212                         break;
       
   213                     }
       
   214                 } else {
       
   215                     requestEndCount = 0;
       
   216                 }
       
   217             }
       
   218         }
       
   219     }
       
   220 
       
   221     static String serverAuthority(FixedLengthServer server) {
       
   222         return InetAddress.getLoopbackAddress().getHostName() + ":"
       
   223                 + server.getPort();
       
   224     }
       
   225 
       
   226     @BeforeTest
       
   227     public void setup() throws Exception {
       
   228         fixedLengthServer = new FixedLengthServer();
       
   229         httpURIFixLen = "http://" + serverAuthority(fixedLengthServer)
       
   230                 + "/http1/fixed/baz";
       
   231     }
       
   232 
       
   233     @AfterTest
       
   234     public void teardown() throws Exception {
       
   235         fixedLengthServer.close();
       
   236     }
       
   237 }