Path: blob/master/test/jdk/sun/net/www/protocol/http/HttpStreams.java
41159 views
/*1* Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 801171926* @library /test/lib27* @modules jdk.httpserver28* @summary Basic checks to verify behavior of returned input streams29*/3031import com.sun.net.httpserver.HttpExchange;32import com.sun.net.httpserver.HttpHandler;33import com.sun.net.httpserver.HttpServer;34import java.io.*;35import java.net.*;36import java.nio.charset.StandardCharsets;37import java.util.*;3839import jdk.test.lib.net.URIBuilder;4041public class HttpStreams {4243void client(String u) throws Exception {44byte[] ba = new byte[5];45HttpURLConnection urlc = (HttpURLConnection)(new URL(u)).openConnection();46int resp = urlc.getResponseCode();47InputStream is;48if (resp == 200)49is = urlc.getInputStream();50else51is = urlc.getErrorStream();5253expectNoThrow(() -> { is.read(); }, "read on open stream should not throw :" + u);54expectNoThrow(() -> { is.close(); }, "close should never throw: " + u);55expectNoThrow(() -> { is.close(); }, "close should never throw: " + u);56expectThrow(() -> { is.read(); }, "read on closed stream should throw: " + u);57expectThrow(() -> { is.read(ba); }, "read on closed stream should throw: " + u);58expectThrow(() -> { is.read(ba, 0, 2); }, "read on closed stream should throw: " + u);59}6061String constructUrlString(int port, String path) throws Exception {62return URIBuilder.newBuilder()63.scheme("http")64.port(port)65.loopback()66.path(path)67.toURL().toString();68}6970void test() throws Exception {71HttpServer server = null;72try {73server = startHttpServer();74int serverPort = server.getAddress().getPort();75client(constructUrlString(serverPort, "/chunked/"));76client(constructUrlString(serverPort, "/fixed/"));77client(constructUrlString(serverPort, "/error/"));78client(constructUrlString(serverPort, "/chunkedError/"));7980// Test with a response cache81ResponseCache ch = ResponseCache.getDefault();82ResponseCache.setDefault(new TrivialCacheHandler());83try {84client(constructUrlString(serverPort, "/chunked/"));85client(constructUrlString(serverPort, "/fixed/"));86client(constructUrlString(serverPort, "/error/"));87client(constructUrlString(serverPort, "/chunkedError/"));88} finally {89ResponseCache.setDefault(ch);90}91} finally {92if (server != null)93server.stop(0);94}9596System.out.println("passed: " + pass + ", failed: " + fail);97if (fail > 0)98throw new RuntimeException("some tests failed check output");99}100101public static void main(String[] args) throws Exception {102(new HttpStreams()).test();103}104105// HTTP Server106HttpServer startHttpServer() throws IOException {107HttpServer httpServer = HttpServer.create();108httpServer.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);109httpServer.createContext("/chunked/", new ChunkedHandler());110httpServer.createContext("/fixed/", new FixedHandler());111httpServer.createContext("/error/", new ErrorHandler());112httpServer.createContext("/chunkedError/", new ChunkedErrorHandler());113httpServer.start();114return httpServer;115}116117static abstract class AbstractHandler implements HttpHandler {118@Override119public void handle(HttpExchange t) throws IOException {120try (InputStream is = t.getRequestBody()) {121while (is.read() != -1);122}123t.sendResponseHeaders(respCode(), length());124try (OutputStream os = t.getResponseBody()) {125os.write(message());126}127t.close();128}129130abstract int respCode();131abstract int length();132abstract byte[] message();133}134135static class ChunkedHandler extends AbstractHandler {136static final byte[] ba =137"Hello there from chunked handler!".getBytes(StandardCharsets.US_ASCII);138int respCode() { return 200; }139int length() { return 0; }140byte[] message() { return ba; }141}142143static class FixedHandler extends AbstractHandler {144static final byte[] ba =145"Hello there from fixed handler!".getBytes(StandardCharsets.US_ASCII);146int respCode() { return 200; }147int length() { return ba.length; }148byte[] message() { return ba; }149}150151static class ErrorHandler extends AbstractHandler {152static final byte[] ba =153"This is an error mesg from the server!".getBytes(StandardCharsets.US_ASCII);154int respCode() { return 400; }155int length() { return ba.length; }156byte[] message() { return ba; }157}158159static class ChunkedErrorHandler extends ErrorHandler {160int length() { return 0; }161}162163static class TrivialCacheHandler extends ResponseCache164{165public CacheResponse get(URI uri, String rqstMethod, Map rqstHeaders) {166return null;167}168169public CacheRequest put(URI uri, URLConnection conn) {170return new TrivialCacheRequest();171}172}173174static class TrivialCacheRequest extends CacheRequest175{176ByteArrayOutputStream baos = new ByteArrayOutputStream();177public void abort() {}178public OutputStream getBody() throws IOException { return baos; }179}180181static interface ThrowableRunnable {182void run() throws IOException;183}184185void expectThrow(ThrowableRunnable r, String msg) {186try { r.run(); fail(msg); } catch (IOException x) { pass(); }187}188189void expectNoThrow(ThrowableRunnable r, String msg) {190try { r.run(); pass(); } catch (IOException x) { fail(msg, x); }191}192193private int pass;194private int fail;195void pass() { pass++; }196void fail(String msg, Exception x) { System.out.println(msg); x.printStackTrace(); fail++; }197void fail(String msg) { System.out.println(msg); Thread.dumpStack(); fail++; }198}199200201