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.
   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  * @bug 8087112
  27  * @modules jdk.incubator.httpclient
  28  *          java.logging
  29  *          jdk.httpserver
  30  * @library /lib/testlibrary/
  31  * @build jdk.testlibrary.SimpleSSLContext ProxyServer
  32  * @build TestKit
  33  * @compile ../../../com/sun/net/httpserver/LogFilter.java
  34  * @compile ../../../com/sun/net/httpserver/FileServerHandler.java
  35  * @run main/othervm APIErrors
  36  * @summary  Basic checks for appropriate errors/exceptions thrown from the API
  37  */
  38 
  39 import com.sun.net.httpserver.HttpContext;
  40 import com.sun.net.httpserver.HttpHandler;
  41 import com.sun.net.httpserver.HttpServer;
  42 import com.sun.net.httpserver.HttpsServer;
  43 import java.io.IOException;
  44 import java.net.InetSocketAddress;
  45 import java.net.PasswordAuthentication;
  46 import java.net.ProxySelector;
  47 import java.net.URI;
  48 import jdk.incubator.http.HttpClient;
  49 import jdk.incubator.http.HttpRequest;
  50 import jdk.incubator.http.HttpResponse;
  51 import java.util.LinkedList;
  52 import java.util.List;
  53 import java.util.concurrent.ExecutionException;
  54 import java.util.concurrent.Executors;
  55 import java.util.concurrent.ExecutorService;
  56 import java.util.function.Supplier;
  57 import static jdk.incubator.http.HttpResponse.BodyHandler.discard;
  58 
  59 public class APIErrors {
  60 
  61     static ExecutorService serverExecutor = Executors.newCachedThreadPool();
  62     static String httproot, fileuri;
  63     static List<HttpClient> clients = new LinkedList<>();
  64 
  65     public static void main(String[] args) throws Exception {
  66         HttpServer server = createServer();
  67 
  68         int port = server.getAddress().getPort();
  69         System.out.println("HTTP server port = " + port);
  70 
  71         httproot = "http://127.0.0.1:" + port + "/files/";
  72         fileuri = httproot + "foo.txt";
  73 
  74         HttpClient client = HttpClient.newHttpClient();
  75 
  76         try {
  77             test1();
  78             test2();
  79             //test3();
  80         } finally {
  81             server.stop(0);
  82             serverExecutor.shutdownNow();
  83             for (HttpClient c : clients)
  84                 ((ExecutorService)c.executor()).shutdownNow();
  85         }
  86     }
  87 
  88     static void checkNonNull(Supplier<?> r) {
  89         if (r.get() == null)
  90             throw new RuntimeException("Unexpected null return:");
  91     }
  92 
  93     static void assertTrue(Supplier<Boolean> r) {
  94         if (r.get() == false)
  95             throw new RuntimeException("Assertion failure:");
  96     }
  97 
  98     // HttpClient.Builder
  99     static void test1() throws Exception {
 100         System.out.println("Test 1");
 101         HttpClient.Builder cb = HttpClient.newBuilder();
 102         TestKit.assertThrows(IllegalArgumentException.class, () -> cb.priority(-1));
 103         TestKit.assertThrows(IllegalArgumentException.class, () -> cb.priority(0));
 104         TestKit.assertThrows(IllegalArgumentException.class, () -> cb.priority(257));
 105         TestKit.assertThrows(IllegalArgumentException.class, () -> cb.priority(500));
 106         TestKit.assertNotThrows(() -> cb.priority(1));
 107         TestKit.assertNotThrows(() -> cb.priority(256));
 108         TestKit.assertNotThrows(() -> {
 109             clients.add(cb.build());
 110             clients.add(cb.build());
 111         });
 112     }
 113 
 114     static void test2() throws Exception {
 115         System.out.println("Test 2");
 116         HttpClient.Builder cb = HttpClient.newBuilder();
 117         InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 5000);
 118         cb.proxy(ProxySelector.of(addr));
 119         HttpClient c = cb.build();
 120         clients.add(c);
 121         checkNonNull(()-> c.executor());
 122         assertTrue(()-> c.followRedirects() == HttpClient.Redirect.NEVER);
 123         assertTrue(()-> !c.authenticator().isPresent());
 124     }
 125 
 126     static URI accessibleURI() {
 127         return URI.create(fileuri);
 128     }
 129 
 130     static HttpRequest request() {
 131         return HttpRequest.newBuilder(accessibleURI()).GET().build();
 132     }
 133 
 134 //    static void test3() throws Exception {
 135 //        System.out.println("Test 3");
 136 //        TestKit.assertThrows(IllegalStateException.class, ()-> {
 137 //            try {
 138 //                HttpRequest r1 = request();
 139 //                HttpResponse<Object> resp = r1.response(discard(null));
 140 //                HttpResponse<Object> resp1 = r1.response(discard(null));
 141 //            } catch (IOException |InterruptedException e) {
 142 //                throw new RuntimeException(e);
 143 //            }
 144 //        });
 145 //
 146 //        TestKit.assertThrows(IllegalStateException.class, ()-> {
 147 //            try {
 148 //                HttpRequest r1 = request();
 149 //                HttpResponse<Object> resp = r1.response(discard(null));
 150 //                HttpResponse<Object> resp1 = r1.responseAsync(discard(null)).get();
 151 //            } catch (IOException |InterruptedException | ExecutionException e) {
 152 //                throw new RuntimeException(e);
 153 //            }
 154 //        });
 155 //        TestKit.assertThrows(IllegalStateException.class, ()-> {
 156 //            try {
 157 //                HttpRequest r1 = request();
 158 //                HttpResponse<Object> resp1 = r1.responseAsync(discard(null)).get();
 159 //                HttpResponse<Object> resp = r1.response(discard(null));
 160 //            } catch (IOException |InterruptedException | ExecutionException e) {
 161 //                throw new RuntimeException(e);
 162 //            }
 163 //        });
 164 //    }
 165 
 166     static class Auth extends java.net.Authenticator {
 167         int count = 0;
 168         @Override
 169         protected PasswordAuthentication getPasswordAuthentication() {
 170             if (count++ == 0) {
 171                 return new PasswordAuthentication("user", "passwd".toCharArray());
 172             } else {
 173                 return new PasswordAuthentication("user", "goober".toCharArray());
 174             }
 175         }
 176         int count() {
 177             return count;
 178         }
 179     }
 180 
 181     static HttpServer createServer() throws Exception {
 182         HttpServer s = HttpServer.create(new InetSocketAddress(0), 0);
 183         if (s instanceof HttpsServer)
 184             throw new RuntimeException ("should not be httpsserver");
 185 
 186         String root = System.getProperty("test.src") + "/docs";
 187         s.createContext("/files", new FileServerHandler(root));
 188         s.setExecutor(serverExecutor);
 189         s.start();
 190 
 191         return s;
 192     }
 193 }