test/jdk/java/net/httpclient/AsFileDownloadTest.java
branchhttp-client-branch
changeset 56132 c8a1eccbc719
child 56166 56c52d6417d1
equal deleted inserted replaced
56131:99f144742013 56132:c8a1eccbc719
       
     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 Basic test for asFileDownload
       
    27  * @bug 8196965
       
    28  * @modules java.base/sun.net.www.http
       
    29  *          java.net.http/jdk.internal.net.http.common
       
    30  *          java.net.http/jdk.internal.net.http.frame
       
    31  *          java.net.http/jdk.internal.net.http.hpack
       
    32  *          java.logging
       
    33  *          jdk.httpserver
       
    34  * @library /lib/testlibrary /test/lib http2/server
       
    35  * @build Http2TestServer
       
    36  * @build jdk.testlibrary.SimpleSSLContext
       
    37  * @build jdk.test.lib.Platform
       
    38  * @build jdk.test.lib.util.FileUtils
       
    39  * @run testng/othervm AsFileDownloadTest
       
    40  */
       
    41 
       
    42 import com.sun.net.httpserver.HttpExchange;
       
    43 import com.sun.net.httpserver.HttpHandler;
       
    44 import com.sun.net.httpserver.HttpServer;
       
    45 import com.sun.net.httpserver.HttpsConfigurator;
       
    46 import com.sun.net.httpserver.HttpsServer;
       
    47 import java.io.IOException;
       
    48 import java.io.InputStream;
       
    49 import java.io.OutputStream;
       
    50 import java.io.UncheckedIOException;
       
    51 import java.net.InetSocketAddress;
       
    52 import java.net.URI;
       
    53 import java.nio.file.Files;
       
    54 import java.nio.file.Path;
       
    55 import java.nio.file.Paths;
       
    56 import java.util.ArrayList;
       
    57 import java.util.Arrays;
       
    58 import java.util.List;
       
    59 import javax.net.ssl.SSLContext;
       
    60 import java.net.http.HttpClient;
       
    61 import java.net.http.HttpRequest;
       
    62 import java.net.http.HttpResponse;
       
    63 import java.net.http.HttpResponse.BodyHandler;
       
    64 import jdk.testlibrary.SimpleSSLContext;
       
    65 import jdk.test.lib.util.FileUtils;
       
    66 import org.testng.annotations.AfterTest;
       
    67 import org.testng.annotations.BeforeTest;
       
    68 import org.testng.annotations.DataProvider;
       
    69 import org.testng.annotations.Test;
       
    70 import static java.lang.System.out;
       
    71 import static java.net.http.HttpRequest.BodyPublisher.fromString;
       
    72 import static java.net.http.HttpResponse.BodyHandler.asFileDownload;
       
    73 import static java.nio.charset.StandardCharsets.UTF_8;
       
    74 import static java.nio.file.StandardOpenOption.*;
       
    75 import static org.testng.Assert.assertEquals;
       
    76 import static org.testng.Assert.assertTrue;
       
    77 import static org.testng.Assert.fail;
       
    78 
       
    79 public class AsFileDownloadTest {
       
    80 
       
    81     SSLContext sslContext;
       
    82     HttpServer httpTestServer;         // HTTP/1.1    [ 4 servers ]
       
    83     HttpsServer httpsTestServer;       // HTTPS/1.1
       
    84     Http2TestServer http2TestServer;   // HTTP/2 ( h2c )
       
    85     Http2TestServer https2TestServer;  // HTTP/2 ( h2  )
       
    86     String httpURI;
       
    87     String httpsURI;
       
    88     String http2URI;
       
    89     String https2URI;
       
    90 
       
    91     Path tempDir;
       
    92 
       
    93     static final String[][] contentDispositionValues = new String[][] {
       
    94           // URI query     Content-Type header value         Expected filename
       
    95             { "001", "Attachment; filename=example001.html", "example001.html" },
       
    96             { "002", "attachment; filename=example002.html", "example002.html" },
       
    97             { "003", "ATTACHMENT; filename=example003.html", "example003.html" },
       
    98             { "004", "attAChment; filename=example004.html", "example004.html" },
       
    99             { "005", "attachmeNt; filename=example005.html", "example005.html" },
       
   100 
       
   101             { "006", "attachment; Filename=example006.html", "example006.html" },
       
   102             { "007", "attachment; FILENAME=example007.html", "example007.html" },
       
   103             { "008", "attachment; fileName=example008.html", "example008.html" },
       
   104             { "009", "attachment; fIlEnAMe=example009.html", "example009.html" },
       
   105 
       
   106             { "010", "attachment; filename=Example010.html", "Example010.html" },
       
   107             { "011", "attachment; filename=EXAMPLE011.html", "EXAMPLE011.html" },
       
   108             { "012", "attachment; filename=eXample012.html", "eXample012.html" },
       
   109             { "013", "attachment; filename=example013.HTML", "example013.HTML" },
       
   110             { "014", "attachment; filename  =eXaMpLe014.HtMl", "eXaMpLe014.HtMl"},
       
   111 
       
   112             { "015", "attachment; filename=a",               "a"               },
       
   113             { "016", "attachment; filename= b",              "b"               },
       
   114             { "017", "attachment; filename=  c",             "c"               },
       
   115             { "018", "attachment; filename=    d",           "d"               },
       
   116             { "019", "attachment; filename=e  ; filename*=utf-8''eee.txt",  "e"},
       
   117             { "020", "attachment; filename*=utf-8''fff.txt; filename=f",    "f"},
       
   118             { "021", "attachment;  filename=g",              "g"               },
       
   119             { "022", "attachment;   filename= h",            "h"               },
       
   120 
       
   121             { "023", "attachment; filename=\"space name\"",                       "space name" },
       
   122             { "024", "attachment; filename=me.txt; filename*=utf-8''you.txt",     "me.txt"     },
       
   123             { "025", "attachment; filename=\"m y.txt\"; filename*=utf-8''you.txt", "m y.txt"   },
       
   124 
       
   125             { "030", "attachment; filename=foo/file1.txt",        "file1.txt" },
       
   126             { "031", "attachment; filename=foo/bar/file2.txt",    "file2.txt" },
       
   127             { "032", "attachment; filename=baz\\file3.txt",       "file3.txt" },
       
   128             { "033", "attachment; filename=baz\\bar\\file4.txt",  "file4.txt" },
       
   129             { "034", "attachment; filename=x/y\\file5.txt",       "file5.txt" },
       
   130             { "035", "attachment; filename=x/y\\file6.txt",       "file6.txt" },
       
   131             { "036", "attachment; filename=x/y\\z/file7.txt",     "file7.txt" },
       
   132             { "037", "attachment; filename=x/y\\z/\\x/file8.txt", "file8.txt" },
       
   133             { "038", "attachment; filename=/root/file9.txt",      "file9.txt" },
       
   134             { "039", "attachment; filename=../file10.txt",        "file10.txt" },
       
   135             { "040", "attachment; filename=..\\file11.txt",       "file11.txt" },
       
   136             { "041", "attachment; filename=foo/../../file12.txt", "file12.txt" },
       
   137     };
       
   138 
       
   139     @DataProvider(name = "positive")
       
   140     public Object[][] positive() {
       
   141         List<Object[]> list = new ArrayList<>();
       
   142 
       
   143         Arrays.asList(contentDispositionValues).stream()
       
   144                 .map(e -> new Object[] {httpURI +  "?" + e[0], e[1], e[2]})
       
   145                 .forEach(list::add);
       
   146         Arrays.asList(contentDispositionValues).stream()
       
   147                 .map(e -> new Object[] {httpsURI +  "?" + e[0], e[1], e[2]})
       
   148                 .forEach(list::add);
       
   149         Arrays.asList(contentDispositionValues).stream()
       
   150                 .map(e -> new Object[] {http2URI +  "?" + e[0], e[1], e[2]})
       
   151                 .forEach(list::add);
       
   152         Arrays.asList(contentDispositionValues).stream()
       
   153                 .map(e -> new Object[] {https2URI +  "?" + e[0], e[1], e[2]})
       
   154                 .forEach(list::add);
       
   155 
       
   156         return list.stream().toArray(Object[][]::new);
       
   157     }
       
   158 
       
   159     @Test(dataProvider = "positive")
       
   160     void test(String uriString, String contentDispositionValue, String expectedFilename)
       
   161         throws Exception
       
   162     {
       
   163         HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
       
   164 
       
   165         URI uri = URI.create(uriString);
       
   166         HttpRequest request = HttpRequest.newBuilder(uri)
       
   167                 .POST(fromString("May the luck of the Irish be with you!"))
       
   168                 .build();
       
   169 
       
   170         BodyHandler bh = asFileDownload(tempDir.resolve(uri.getPath().substring(1)),
       
   171                                         CREATE, TRUNCATE_EXISTING, WRITE);
       
   172         HttpResponse<Path> response = client.send(request, bh);
       
   173 
       
   174         out.println("Got response: " + response);
       
   175         out.println("Got body Path: " + response.body());
       
   176         String fileContents = new String(Files.readAllBytes(response.body()), UTF_8);
       
   177         out.println("Got body: " + fileContents);
       
   178 
       
   179         assertEquals(response.statusCode(),200);
       
   180         assertEquals(response.body().getFileName().toString(), expectedFilename);
       
   181         assertTrue(response.headers().firstValue("Content-Disposition").isPresent());
       
   182         assertEquals(response.headers().firstValue("Content-Disposition").get(),
       
   183                      contentDispositionValue);
       
   184         assertEquals(fileContents, "May the luck of the Irish be with you!");
       
   185     }
       
   186 
       
   187     // --- Negative
       
   188 
       
   189     static final String[][] contentDispositionBADValues = new String[][] {
       
   190             // URI query     Content-Type header value
       
   191             { "100", ""                                    },  // empty
       
   192             { "101", "filename=example.html"               },  // no attachment
       
   193             { "102", "attachment; filename=space name"     },  // unquoted with space
       
   194             { "103", "attachment; filename="               },  // empty filename param
       
   195             { "104", "attachment; filename=\""             },  // single quote
       
   196             { "105", "attachment; filename=\"\""           },  // empty quoted
       
   197             { "106", "attachment; filename=."              },  // dot
       
   198             { "107", "attachment; filename=.."             },  // dot dot
       
   199             { "108", "attachment; filename=\".."           },  // badly quoted dot dot
       
   200             { "109", "attachment; filename=\"..\""         },  // quoted dot dot
       
   201             { "110", "attachment; filename=\"bad"          },  // badly quoted
       
   202             { "111", "attachment; filename=\"bad;"         },  // badly quoted with ';'
       
   203             { "112", "attachment; filename=\"bad ;"        },  // badly quoted with ' ;'
       
   204             { "113", "attachment; filename*=utf-8''xx.txt "},  // no "filename" param
       
   205     };
       
   206 
       
   207     @DataProvider(name = "negative")
       
   208     public Object[][] negative() {
       
   209         List<Object[]> list = new ArrayList<>();
       
   210 
       
   211         Arrays.asList(contentDispositionBADValues).stream()
       
   212                 .map(e -> new Object[] {httpURI +  "?" + e[0], e[1]})
       
   213                 .forEach(list::add);
       
   214         Arrays.asList(contentDispositionBADValues).stream()
       
   215                 .map(e -> new Object[] {httpsURI +  "?" + e[0], e[1]})
       
   216                 .forEach(list::add);
       
   217         Arrays.asList(contentDispositionBADValues).stream()
       
   218                 .map(e -> new Object[] {http2URI +  "?" + e[0], e[1]})
       
   219                 .forEach(list::add);
       
   220         Arrays.asList(contentDispositionBADValues).stream()
       
   221                 .map(e -> new Object[] {https2URI +  "?" + e[0], e[1]})
       
   222                 .forEach(list::add);
       
   223 
       
   224         return list.stream().toArray(Object[][]::new);
       
   225     }
       
   226 
       
   227     @Test(dataProvider = "negative")
       
   228     void negativeTest(String uriString, String contentDispositionValue)
       
   229             throws Exception
       
   230     {
       
   231         HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
       
   232 
       
   233         URI uri = URI.create(uriString);
       
   234         HttpRequest request = HttpRequest.newBuilder(uri)
       
   235                 .POST(fromString("Does not matter"))
       
   236                 .build();
       
   237 
       
   238         BodyHandler bh = asFileDownload(tempDir, CREATE, TRUNCATE_EXISTING, WRITE);
       
   239         try {
       
   240             HttpResponse<Path> response = client.send(request, bh);
       
   241             fail("UNEXPECTED response: " + response + ", path:" + response.body());
       
   242         } catch (UncheckedIOException | IOException ioe) {
       
   243             System.out.println("Caught expected: " + ioe);
       
   244         }
       
   245     }
       
   246 
       
   247     // -- Infrastructure
       
   248 
       
   249     @BeforeTest
       
   250     public void setup() throws Exception {
       
   251         tempDir = Paths.get("asFileDownloadTest.tmp.dir");
       
   252         FileUtils.deleteFileIfExistsWithRetry(tempDir);
       
   253         Files.createDirectory(tempDir);
       
   254         // Unique dirs per test run, based on the URI path
       
   255         Files.createDirectories(tempDir.resolve("http1/afdt/"));
       
   256         Files.createDirectories(tempDir.resolve("https1/afdt/"));
       
   257         Files.createDirectories(tempDir.resolve("http2/afdt/"));
       
   258         Files.createDirectories(tempDir.resolve("https2/afdt/"));
       
   259 
       
   260         sslContext = new SimpleSSLContext().get();
       
   261         if (sslContext == null)
       
   262             throw new AssertionError("Unexpected null sslContext");
       
   263 
       
   264         InetSocketAddress sa = new InetSocketAddress(0);
       
   265         httpTestServer = HttpServer.create(sa, 0);
       
   266         httpTestServer.createContext("/http1/afdt", new Http1FileDispoHandler());
       
   267         httpURI = "http://127.0.0.1:" + httpTestServer.getAddress().getPort() + "/http1/afdt";
       
   268 
       
   269         httpsTestServer = HttpsServer.create(sa, 0);
       
   270         httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
       
   271         httpsTestServer.createContext("/https1/afdt", new Http1FileDispoHandler());
       
   272         httpsURI = "https://127.0.0.1:" + httpsTestServer.getAddress().getPort() + "/https1/afdt";
       
   273 
       
   274         http2TestServer = new Http2TestServer("127.0.0.1", false, 0);
       
   275         http2TestServer.addHandler(new Http2FileDispoHandler(), "/http2/afdt");
       
   276         int port = http2TestServer.getAddress().getPort();
       
   277         http2URI = "http://127.0.0.1:" + port + "/http2/afdt";
       
   278 
       
   279         https2TestServer = new Http2TestServer("127.0.0.1", true, 0);
       
   280         https2TestServer.addHandler(new Http2FileDispoHandler(), "/https2/afdt");
       
   281         port = https2TestServer.getAddress().getPort();
       
   282         https2URI = "https://127.0.0.1:" + port + "/https2/afdt";
       
   283 
       
   284         httpTestServer.start();
       
   285         httpsTestServer.start();
       
   286         http2TestServer.start();
       
   287         https2TestServer.start();
       
   288     }
       
   289 
       
   290     @AfterTest
       
   291     public void teardown() throws Exception {
       
   292         httpTestServer.stop(0);
       
   293         httpsTestServer.stop(0);
       
   294         http2TestServer.stop();
       
   295         https2TestServer.stop();
       
   296     }
       
   297 
       
   298     static String contentDispositionValueFromURI(URI uri) {
       
   299         String queryIndex = uri.getQuery();
       
   300         String[][] values;
       
   301         if (queryIndex.startsWith("0"))  // positive tests start with '0'
       
   302             values = contentDispositionValues;
       
   303         else if (queryIndex.startsWith("1"))  // negative tests start with '1'
       
   304             values = contentDispositionBADValues;
       
   305         else
       
   306             throw new AssertionError("SERVER: UNEXPECTED query:" + queryIndex);
       
   307 
       
   308         return Arrays.asList(values).stream()
       
   309                 .filter(e -> e[0].equals(queryIndex))
       
   310                 .map(e -> e[1])
       
   311                 .findFirst()
       
   312                 .orElseThrow();
       
   313     }
       
   314 
       
   315     static class Http1FileDispoHandler implements HttpHandler {
       
   316         @Override
       
   317         public void handle(HttpExchange t) throws IOException {
       
   318             try (InputStream is = t.getRequestBody();
       
   319                  OutputStream os = t.getResponseBody()) {
       
   320                 byte[] bytes = is.readAllBytes();
       
   321 
       
   322                 t.getResponseHeaders().set("Content-Disposition",
       
   323                         contentDispositionValueFromURI(t.getRequestURI()));
       
   324 
       
   325                 t.sendResponseHeaders(200, bytes.length);
       
   326                 os.write(bytes);
       
   327             }
       
   328         }
       
   329     }
       
   330 
       
   331     static class Http2FileDispoHandler implements Http2Handler {
       
   332         @Override
       
   333         public void handle(Http2TestExchange t) throws IOException {
       
   334             try (InputStream is = t.getRequestBody();
       
   335                  OutputStream os = t.getResponseBody()) {
       
   336                 byte[] bytes = is.readAllBytes();
       
   337 
       
   338                 t.getResponseHeaders().addHeader("Content-Disposition",
       
   339                         contentDispositionValueFromURI(t.getRequestURI()));
       
   340 
       
   341                 t.sendResponseHeaders(200, bytes.length);
       
   342                 os.write(bytes);
       
   343             }
       
   344         }
       
   345     }
       
   346 }