< prev index next >
   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  * library /lib/testlibrary/ /
  26  * build jdk.testlibrary.SimpleSSLContext ProxyServer EchoHandler
  27  * compile ../../../com/sun/net/httpserver/LogFilter.java
  28  * compile ../../../com/sun/net/httpserver/FileServerHandler.java
  29  */
  30 import com.sun.net.httpserver.Headers;
  31 import com.sun.net.httpserver.HttpContext;
  32 import com.sun.net.httpserver.HttpExchange;
  33 import com.sun.net.httpserver.HttpHandler;
  34 import com.sun.net.httpserver.HttpServer;
  35 import com.sun.net.httpserver.HttpsConfigurator;
  36 import com.sun.net.httpserver.HttpsServer;
  37 import java.io.IOException;
  38 import java.io.InputStream;
  39 import java.io.OutputStream;
  40 import java.net.InetSocketAddress;
  41 import java.nio.file.Path;
  42 import java.util.HashSet;
  43 import java.util.concurrent.BrokenBarrierException;
  44 import java.util.concurrent.CyclicBarrier;
  45 import java.util.concurrent.ExecutorService;
  46 import java.util.concurrent.Executors;
  47 import java.util.logging.ConsoleHandler;
  48 import java.util.logging.Level;
  49 import java.util.logging.Logger;
  50 import javax.net.ssl.SSLContext;
  51 import jdk.testlibrary.SimpleSSLContext;
  52 
  53 public class LightWeightHttpServer {
  54 
  55     static SSLContext ctx;
  56     static HttpServer httpServer;
  57     static HttpsServer httpsServer;
  58     static ExecutorService executor;
  59     static int port;
  60     static int httpsport;
  61     static String httproot;
  62     static String httpsroot;
  63     static ProxyServer proxy;
  64     static int proxyPort;
  65     static RedirectErrorHandler redirectErrorHandler, redirectErrorHandlerSecure;
  66     static RedirectHandler redirectHandler, redirectHandlerSecure;
  67     static DelayHandler delayHandler;
  68     static final String midSizedFilename = "/files/notsobigfile.txt";
  69     static final String smallFilename = "/files/smallfile.txt";
  70     static Path midSizedFile;
  71     static Path smallFile;
  72     static String fileroot;
  73 
  74     public static void initServer() throws IOException {
  75 
  76         Logger logger = Logger.getLogger("com.sun.net.httpserver");
  77         ConsoleHandler ch = new ConsoleHandler();
  78         logger.setLevel(Level.ALL);
  79         ch.setLevel(Level.ALL);
  80         logger.addHandler(ch);
  81 
  82         String root = System.getProperty("test.src") + "/docs";
  83         InetSocketAddress addr = new InetSocketAddress(0);
  84         httpServer = HttpServer.create(addr, 0);
  85         if (httpServer instanceof HttpsServer) {
  86             throw new RuntimeException("should not be httpsserver");
  87         }
  88         httpsServer = HttpsServer.create(addr, 0);
  89         HttpHandler h = new FileServerHandler(root);
  90 
  91         HttpContext c1 = httpServer.createContext("/files", h);
  92         HttpContext c2 = httpsServer.createContext("/files", h);
  93         HttpContext c3 = httpServer.createContext("/echo", new EchoHandler());
  94         redirectHandler = new RedirectHandler("/redirect");
  95         redirectHandlerSecure = new RedirectHandler("/redirect");
  96         HttpContext c4 = httpServer.createContext("/redirect", redirectHandler);
  97         HttpContext c41 = httpsServer.createContext("/redirect", redirectHandlerSecure);
  98         HttpContext c5 = httpsServer.createContext("/echo", new EchoHandler());
  99         HttpContext c6 = httpServer.createContext("/keepalive", new KeepAliveHandler());
 100         redirectErrorHandler = new RedirectErrorHandler("/redirecterror");
 101         redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror");
 102         HttpContext c7 = httpServer.createContext("/redirecterror", redirectErrorHandler);
 103         HttpContext c71 = httpsServer.createContext("/redirecterror", redirectErrorHandlerSecure);
 104         delayHandler = new DelayHandler();
 105         HttpContext c8 = httpServer.createContext("/delay", delayHandler);
 106         HttpContext c81 = httpsServer.createContext("/delay", delayHandler);
 107 
 108         executor = Executors.newCachedThreadPool();
 109         httpServer.setExecutor(executor);
 110         httpsServer.setExecutor(executor);
 111         ctx = new SimpleSSLContext().get();
 112         httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx));
 113         httpServer.start();
 114         httpsServer.start();
 115 
 116         port = httpServer.getAddress().getPort();
 117         System.out.println("HTTP server port = " + port);
 118         httpsport = httpsServer.getAddress().getPort();
 119         System.out.println("HTTPS server port = " + httpsport);
 120         httproot = "http://127.0.0.1:" + port + "/";
 121         httpsroot = "https://127.0.0.1:" + httpsport + "/";
 122 
 123         proxy = new ProxyServer(0, false);
 124         proxyPort = proxy.getPort();
 125         System.out.println("Proxy port = " + proxyPort);
 126     }
 127 
 128     public static void stop() throws IOException {
 129         if (httpServer != null) {
 130             httpServer.stop(0);
 131         }
 132         if (httpsServer != null) {
 133             httpsServer.stop(0);
 134         }
 135         if (proxy != null) {
 136             proxy.close();
 137         }
 138         if (executor != null) {
 139             executor.shutdownNow();
 140         }
 141     }
 142 
 143     static class RedirectErrorHandler implements HttpHandler {
 144 
 145         String root;
 146         volatile int count = 1;
 147 
 148         RedirectErrorHandler(String root) {
 149             this.root = root;
 150         }
 151 
 152         synchronized int count() {
 153             return count;
 154         }
 155 
 156         synchronized void increment() {
 157             count++;
 158         }
 159 
 160         @Override
 161         public synchronized void handle(HttpExchange t)
 162                 throws IOException {
 163             byte[] buf = new byte[2048];
 164             try (InputStream is = t.getRequestBody()) {
 165                 while (is.read(buf) != -1) ;
 166             }
 167 
 168             Headers map = t.getResponseHeaders();
 169             String redirect = root + "/foo/" + Integer.toString(count);
 170             increment();
 171             map.add("Location", redirect);
 172             t.sendResponseHeaders(301, -1);
 173             t.close();
 174         }
 175     }
 176 
 177     static class RedirectHandler implements HttpHandler {
 178 
 179         String root;
 180         volatile int count = 0;
 181 
 182         RedirectHandler(String root) {
 183             this.root = root;
 184         }
 185 
 186         @Override
 187         public synchronized void handle(HttpExchange t)
 188                 throws IOException {
 189             byte[] buf = new byte[2048];
 190             try (InputStream is = t.getRequestBody()) {
 191                 while (is.read(buf) != -1) ;
 192             }
 193 
 194             Headers map = t.getResponseHeaders();
 195 
 196             if (count++ < 1) {
 197                 map.add("Location", root + "/foo/" + count);
 198             } else {
 199                 map.add("Location", SmokeTest.midSizedFilename);
 200             }
 201             t.sendResponseHeaders(301, -1);
 202             t.close();
 203         }
 204 
 205         int count() {
 206             return count;
 207         }
 208 
 209         void reset() {
 210             count = 0;
 211         }
 212     }
 213 
 214     static class KeepAliveHandler implements HttpHandler {
 215 
 216         volatile int counter = 0;
 217         HashSet<Integer> portSet = new HashSet<>();
 218         volatile int[] ports = new int[4];
 219 
 220         void sleep(int n) {
 221             try {
 222                 Thread.sleep(n);
 223             } catch (InterruptedException e) {
 224             }
 225         }
 226 
 227         @Override
 228         public synchronized void handle(HttpExchange t)
 229                 throws IOException {
 230             int remotePort = t.getRemoteAddress().getPort();
 231             String result = "OK";
 232 
 233             int n = counter++;
 234             /// First test
 235             if (n < 4) {
 236                 ports[n] = remotePort;
 237             }
 238             if (n == 3) {
 239                 // check all values in ports[] are the same
 240                 if (ports[0] != ports[1] || ports[2] != ports[3]
 241                         || ports[0] != ports[2]) {
 242                     result = "Error " + Integer.toString(n);
 243                     System.out.println(result);
 244                 }
 245             }
 246             // Second test
 247             if (n >= 4 && n < 8) {
 248                 // delay to ensure ports are different
 249                 sleep(500);
 250                 ports[n - 4] = remotePort;
 251             }
 252             if (n == 7) {
 253                 // should be all different
 254                 if (ports[0] == ports[1] || ports[2] == ports[3]
 255                         || ports[0] == ports[2]) {
 256                     result = "Error " + Integer.toString(n);
 257                     System.out.println(result);
 258                     System.out.printf("Ports: %d, %d, %d, %d\n",
 259                                       ports[0], ports[1], ports[2], ports[3]);
 260                 }
 261                 // setup for third test
 262                 for (int i = 0; i < 4; i++) {
 263                     portSet.add(ports[i]);
 264                 }
 265             }
 266             // Third test
 267             if (n > 7) {
 268                 // just check that port is one of the ones in portSet
 269                 if (!portSet.contains(remotePort)) {
 270                     System.out.println("UNEXPECTED REMOTE PORT " + remotePort);
 271                     result = "Error " + Integer.toString(n);
 272                     System.out.println(result);
 273                 }
 274             }
 275             byte[] buf = new byte[2048];
 276 
 277             try (InputStream is = t.getRequestBody()) {
 278                 while (is.read(buf) != -1) ;
 279             }
 280             t.sendResponseHeaders(200, result.length());
 281             OutputStream o = t.getResponseBody();
 282             o.write(result.getBytes("US-ASCII"));
 283             t.close();
 284         }
 285     }
 286 
 287     static class DelayHandler implements HttpHandler {
 288 
 289         CyclicBarrier bar1 = new CyclicBarrier(2);
 290         CyclicBarrier bar2 = new CyclicBarrier(2);
 291         CyclicBarrier bar3 = new CyclicBarrier(2);
 292 
 293         CyclicBarrier barrier1() {
 294             return bar1;
 295         }
 296 
 297         CyclicBarrier barrier2() {
 298             return bar2;
 299         }
 300 
 301         @Override
 302         public synchronized void handle(HttpExchange he) throws IOException {
 303             byte[] buf = Util.readAll(he.getRequestBody());
 304             try {
 305                 bar1.await();
 306                 bar2.await();
 307             } catch (InterruptedException | BrokenBarrierException e) {
 308             }
 309             he.sendResponseHeaders(200, -1); // will probably fail
 310             he.close();
 311         }
 312     }
 313 }
< prev index next >