Skip to content
Snippets Groups Projects
Commit e96daf3b authored by Christoph Langer's avatar Christoph Langer
Browse files

8282354: Remove dependancy of TestHttpServer, HttpTransaction, HttpCallback...

8282354: Remove dependancy of TestHttpServer, HttpTransaction, HttpCallback from open/test/jdk/ tests

Reviewed-by: mbaesken
Backport-of: 95ca94436d12974d98b1b999f9cc8408d64cbe3c
parent 0e729527
No related branches found
No related tags found
No related merge requests found
Showing
with 312 additions and 1511 deletions
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -27,15 +27,25 @@
* @summary PIT: Can no launch jnlp application via 127.0.0.1 address on the web server.
* This test might fail intermittently as it needs a server that
* binds to the wildcard address.
* @modules java.base/sun.net.www
* @library ../../../sun/net/www/httptest/ /test/lib
* @build ClosedChannelList TestHttpServer HttpTransaction HttpCallback
* @library /test/lib
* @compile LoopbackAddresses.java
* @run main/othervm LoopbackAddresses
*/
import java.net.*;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
/**
......@@ -43,17 +53,8 @@ import jdk.test.lib.net.URIBuilder;
* addresses when selecting proxies. This is the existing behaviour.
*/
public class LoopbackAddresses implements HttpCallback {
static TestHttpServer server;
public void request (HttpTransaction req) {
req.setResponseEntityBody ("Hello .");
try {
req.sendResponse (200, "Ok");
req.orderlyClose();
} catch (IOException e) {
}
}
public class LoopbackAddresses {
static HttpServer server;
public static void main(String[] args) {
try {
......@@ -63,15 +64,18 @@ public class LoopbackAddresses implements HttpCallback {
// to answer both for the loopback and "localhost".
// Though "localhost" usually point to the loopback there is no
// hard guarantee.
server = new TestHttpServer (new LoopbackAddresses(), 1, 10, 0);
ProxyServer pserver = new ProxyServer(InetAddress.getByName("localhost"), server.getLocalPort());
server = HttpServer.create(new InetSocketAddress(loopback, 0), 10);
server.createContext("/", new LoopbackAddressesHandler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
ProxyServer pserver = new ProxyServer(InetAddress.getByName("localhost"), server.getAddress().getPort());
// start proxy server
new Thread(pserver).start();
System.setProperty("http.proxyHost", loopback.getHostAddress());
System.setProperty("http.proxyPort", pserver.getPort()+"");
URL url = new URL("http://localhost:"+server.getLocalPort());
URL url = new URL("http://localhost:"+server.getAddress().getPort());
try {
HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
......@@ -85,7 +89,7 @@ public class LoopbackAddresses implements HttpCallback {
url = URIBuilder.newBuilder()
.scheme("http")
.host(loopback.getHostAddress())
.port(server.getLocalPort())
.port(server.getAddress().getPort())
.toURL();
HttpURLConnection urlc = (HttpURLConnection)url.openConnection ();
int respCode = urlc.getResponseCode();
......@@ -97,7 +101,7 @@ public class LoopbackAddresses implements HttpCallback {
throw new RuntimeException(e);
} finally {
if (server != null) {
server.terminate();
server.stop(1);
}
}
......@@ -151,3 +155,18 @@ public class LoopbackAddresses implements HttpCallback {
}
}
}
class LoopbackAddressesHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
exchange.sendResponseHeaders(200, 0);
} catch (IOException e) {
e.printStackTrace();
}
try(PrintWriter pw = new PrintWriter(exchange.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print("Hello .");
}
}
}
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -25,33 +25,37 @@
* @test
* @bug 4696512
* @summary HTTP client: Improve proxy server configuration and selection
* @modules java.base/sun.net.www
* @library ../../../sun/net/www/httptest/ /test/lib
* @build ClosedChannelList TestHttpServer HttpTransaction HttpCallback
* @library /test/lib
* @compile ProxyTest.java
* @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 ProxyTest
*/
import java.net.*;
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
public class ProxyTest implements HttpCallback {
static TestHttpServer server;
public class ProxyTest {
static HttpServer server;
public ProxyTest() {
}
public void request(HttpTransaction req) {
req.setResponseEntityBody("Hello .");
try {
req.sendResponse(200, "Ok");
req.orderlyClose();
} catch (IOException e) {
}
}
static public class MyProxySelector extends ProxySelector {
private static volatile URI lastURI;
private final static List<Proxy> NO_PROXY = List.of(Proxy.NO_PROXY);
......@@ -75,11 +79,14 @@ public class ProxyTest implements HttpCallback {
ProxySelector.setDefault(new MyProxySelector());
try {
InetAddress loopback = InetAddress.getLoopbackAddress();
server = new TestHttpServer(new ProxyTest(), 1, 10, loopback, 0);
server = HttpServer.create(new InetSocketAddress(loopback, 0), 10);
server.createContext("/", new ProxyTestHandler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(server.getLocalPort())
.port(server.getAddress().getPort())
.toURL();
System.out.println("client opening connection to: " + url);
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
......@@ -93,8 +100,23 @@ public class ProxyTest implements HttpCallback {
throw new RuntimeException(e);
} finally {
if (server != null) {
server.terminate();
server.stop(1);
}
}
}
}
class ProxyTestHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
exchange.sendResponseHeaders(200, 0);
} catch (IOException e) {
e.printStackTrace();
}
try(PrintWriter pw = new PrintWriter(exchange.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print("Hello .");
}
}
}
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -24,42 +24,48 @@
/* @test
* @bug 4920526
* @summary Needs per connection proxy support for URLs
* @modules java.base/sun.net.www
* @library ../../../sun/net/www/httptest/ /test/lib
* @build ClosedChannelList TestHttpServer HttpTransaction HttpCallback
* @library /test/lib
* @compile PerConnectionProxy.java
* @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 PerConnectionProxy
*/
import java.net.*;
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
public class PerConnectionProxy implements HttpCallback {
static TestHttpServer server;
public void request (HttpTransaction req) {
req.setResponseEntityBody ("Hello .");
try {
req.sendResponse (200, "Ok");
req.orderlyClose();
} catch (IOException e) {
}
}
public class PerConnectionProxy {
static HttpServer server;
public static void main(String[] args) {
try {
InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
server = new TestHttpServer(new PerConnectionProxy(), 1, 10, loopbackAddress, 0);
ProxyServer pserver = new ProxyServer(loopbackAddress, server.getLocalPort());
server = HttpServer.create(new InetSocketAddress(loopbackAddress, 0), 10);
server.createContext("/", new PerConnectionProxyHandler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
ProxyServer pserver = new ProxyServer(loopbackAddress, server.getAddress().getPort());
// start proxy server
new Thread(pserver).start();
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(server.getLocalPort())
.port(server.getAddress().getPort())
.toURLUnchecked();
// for non existing proxy expect an IOException
......@@ -73,7 +79,6 @@ public class PerConnectionProxy implements HttpCallback {
} catch (IOException ioex) {
// expected
}
// for NO_PROXY, expect direct connection
try {
HttpURLConnection urlc = (HttpURLConnection)url.openConnection (Proxy.NO_PROXY);
......@@ -82,7 +87,6 @@ public class PerConnectionProxy implements HttpCallback {
} catch (IOException ioex) {
throw new RuntimeException("direct connection should succeed :"+ioex.getMessage());
}
// for a normal proxy setting expect to see connection
// goes through that proxy
try {
......@@ -101,10 +105,9 @@ public class PerConnectionProxy implements HttpCallback {
throw new RuntimeException(e);
} finally {
if (server != null) {
server.terminate();
server.stop(1);
}
}
}
static class ProxyServer extends Thread {
......@@ -145,7 +148,6 @@ public class PerConnectionProxy implements HttpCallback {
private void processRequests() throws Exception {
// connection set to the tunneling mode
Socket serverSocket = new Socket(serverInetAddr, serverPort);
ProxyTunnel clientToServer = new ProxyTunnel(
clientSocket, serverSocket);
......@@ -161,7 +163,6 @@ public class PerConnectionProxy implements HttpCallback {
clientToServer.close();
serverToClient.close();
}
/**
......@@ -221,6 +222,20 @@ public class PerConnectionProxy implements HttpCallback {
} catch (IOException ignored) { }
}
}
}
}
class PerConnectionProxyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
exchange.sendResponseHeaders(200, 0);
} catch (IOException e) {
}
try(PrintWriter pw = new PrintWriter(exchange.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print("Hello .");
}
}
}
/*
* Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -23,21 +23,31 @@
/*
* @test
* @modules java.base/sun.net.www.protocol.file
* @bug 5052093
* @modules java.base/sun.net.www java.base/sun.net.www.protocol.file
* @library ../../../sun/net/www/httptest/
* @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
* @run main B5052093
* @library /test/lib
* @run main/othervm B5052093
* @summary URLConnection doesn't support large files
*/
import java.net.*;
import java.io.*;
import sun.net.www.protocol.file.FileURLConnection;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import static java.net.Proxy.NO_PROXY;
import jdk.test.lib.net.URIBuilder;
import sun.net.www.protocol.file.FileURLConnection;
public class B5052093 implements HttpCallback {
private static TestHttpServer server;
private static long testSize = ((long) (Integer.MAX_VALUE)) + 2;
public class B5052093 {
private static HttpServer server;
static long testSize = ((long) (Integer.MAX_VALUE)) + 2;
public static class LargeFile extends File {
public LargeFile() {
......@@ -55,20 +65,19 @@ public class B5052093 implements HttpCallback {
}
}
public void request(HttpTransaction req) {
try {
req.setResponseHeader("content-length", Long.toString(testSize));
req.sendResponse(200, "OK");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
InetAddress loopback = InetAddress.getLoopbackAddress();
server = new TestHttpServer(new B5052093(), 1, 10, loopback, 0);
server = HttpServer.create(new InetSocketAddress(loopback, 0), 10);
server.createContext("/", new B5052093Handler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
try {
URL url = new URL("http://" + server.getAuthority() + "/foo");
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(server.getAddress().getPort())
.path("/foo")
.build().toURL();
URLConnection conn = url.openConnection(NO_PROXY);
int i = conn.getContentLength();
long l = conn.getContentLengthLong();
......@@ -89,7 +98,20 @@ public class B5052093 implements HttpCallback {
throw new RuntimeException("Wrong content-length from file");
}
} finally {
server.terminate();
server.stop(1);
}
}
}
class B5052093Handler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
exchange.getResponseHeaders().set("content-length", Long.toString(B5052093.testSize));
exchange.sendResponseHeaders(200, 0);
exchange.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -24,53 +24,31 @@
/**
* @test
* @bug 4804309
* @modules java.base/sun.net.www
* @library ../../../sun/net/www/httptest/
* @build HttpCallback TestHttpServer ClosedChannelList HttpTransaction
* @run main AuthHeaderTest
* @library /test/lib
* @run main/othervm AuthHeaderTest
* @summary AuthHeaderTest bug
*/
import java.io.*;
import java.net.*;
public class AuthHeaderTest implements HttpCallback {
static int count = 0;
static String authstring;
void errorReply (HttpTransaction req, String reply) throws IOException {
req.addResponseHeader ("Connection", "close");
req.addResponseHeader ("Www-authenticate", reply);
req.sendResponse (401, "Unauthorized");
req.orderlyClose();
}
void okReply (HttpTransaction req) throws IOException {
req.setResponseEntityBody ("Hello .");
req.sendResponse (200, "Ok");
req.orderlyClose();
}
public void request (HttpTransaction req) {
try {
authstring = req.getRequestHeader ("Authorization");
System.out.println (authstring);
switch (count) {
case 0:
errorReply (req, "Basic realm=\"wallyworld\"");
break;
case 1:
/* client stores a username/pw for wallyworld
*/
okReply (req);
break;
}
count ++;
} catch (IOException e) {
e.printStackTrace();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
public class AuthHeaderTest {
static HttpServer server;
static void read (InputStream is) throws IOException {
int c;
......@@ -91,19 +69,28 @@ public class AuthHeaderTest implements HttpCallback {
is.close();
}
static TestHttpServer server;
public static void main (String[] args) throws Exception {
MyAuthenticator auth = new MyAuthenticator ();
Authenticator.setDefault (auth);
InetAddress loopback = InetAddress.getLoopbackAddress();
try {
server = new TestHttpServer (new AuthHeaderTest(), 1, 10, loopback, 0);
System.out.println ("Server: listening on port: " + server.getAuthority());
client ("http://" + server.getAuthority() + "/d1/foo.html");
server = HttpServer.create(new InetSocketAddress(loopback, 0), 10);
server.createContext("/", new AuthHeaderTestHandler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
System.out.println ("Server: listening on port: " + server.getAddress().getPort());
String serverURL = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(server.getAddress().getPort())
.path("/")
.build()
.toString();
client (serverURL + "d1/foo.html");
} catch (Exception e) {
if (server != null) {
server.terminate();
server.stop(1);
}
throw e;
}
......@@ -111,11 +98,11 @@ public class AuthHeaderTest implements HttpCallback {
if (f != 1) {
except ("Authenticator was called "+f+" times. Should be 1");
}
server.terminate();
server.stop(1);
}
public static void except (String s) {
server.terminate();
server.stop(1);
throw new RuntimeException (s);
}
......@@ -138,3 +125,45 @@ public class AuthHeaderTest implements HttpCallback {
}
}
}
class AuthHeaderTestHandler implements HttpHandler {
static int count = 0;
static String authstring;
void errorReply (HttpExchange req, String reply) throws IOException {
req.getResponseHeaders().set("Connection", "close");
req.getResponseHeaders().set("Www-authenticate", reply);
req.sendResponseHeaders(401, -1);
}
void okReply (HttpExchange req) throws IOException {
req.sendResponseHeaders (200, 0);
try(PrintWriter pw = new PrintWriter(req.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print("Hello .");
}
}
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
if(exchange.getRequestHeaders().get("Authorization") != null) {
authstring = exchange.getRequestHeaders().get("Authorization").get(0);
System.out.println (authstring);
}
switch (count) {
case 0:
errorReply (exchange, "Basic realm=\"wallyworld\"");
break;
case 1:
/* client stores a username/pw for wallyworld
*/
okReply (exchange);
break;
}
count ++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
/*
* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -24,19 +24,30 @@
/*
* @test
* @bug 5045306 6356004 6993490 8255124
* @modules java.base/sun.net.www
* java.management
* @library ../../httptest/
* @build HttpCallback TestHttpServer HttpTransaction
* @library /test/lib
* @run main/othervm B5045306
* @summary Http keep-alive implementation is not efficient
*/
import java.net.*;
import java.io.*;
import java.lang.management.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/* Part 1:
* The http client makes a connection to a URL whos content contains a lot of
......@@ -51,20 +62,20 @@ import java.util.List;
* Content-length header.
*/
public class B5045306
{
static SimpleHttpTransaction httpTrans;
static TestHttpServer server;
public class B5045306 {
static HttpServer server;
public static void main(String[] args) throws Exception {
public static void main(String[] args) {
startHttpServer();
clientHttpCalls();
}
public static void startHttpServer() {
try {
httpTrans = new SimpleHttpTransaction();
server = new TestHttpServer(httpTrans, 1, 10, InetAddress.getLocalHost(), 0);
server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 0), 10);
server.createContext("/", new SimpleHttpTransactionHandler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
} catch (IOException e) {
e.printStackTrace();
}
......@@ -76,10 +87,10 @@ public class B5045306
uncaught.add(ex);
});
try {
System.out.println("http server listen on: " + server.getLocalPort());
System.out.println("http server listen on: " + server.getAddress().getPort());
String hostAddr = InetAddress.getLocalHost().getHostAddress();
if (hostAddr.indexOf(':') > -1) hostAddr = "[" + hostAddr + "]";
String baseURLStr = "http://" + hostAddr + ":" + server.getLocalPort() + "/";
String baseURLStr = "http://" + hostAddr + ":" + server.getAddress().getPort() + "/";
URL bigDataURL = new URL (baseURLStr + "firstCall");
URL smallDataURL = new URL (baseURLStr + "secondCall");
......@@ -98,7 +109,7 @@ public class B5045306
uc = (HttpURLConnection)smallDataURL.openConnection(Proxy.NO_PROXY);
uc.getResponseCode();
if (SimpleHttpTransaction.failed)
if (SimpleHttpTransactionHandler.failed)
throw new RuntimeException("Failed: Initial Keep Alive Connection is not being reused");
// Part 2
......@@ -137,7 +148,7 @@ public class B5045306
} catch (IOException e) {
e.printStackTrace();
} finally {
server.terminate();
server.stop(1);
}
if (!uncaught.isEmpty()) {
throw new RuntimeException("Unhandled exception:", uncaught.get(0));
......@@ -145,9 +156,9 @@ public class B5045306
}
}
class SimpleHttpTransaction implements HttpCallback
class SimpleHttpTransactionHandler implements HttpHandler
{
static boolean failed = false;
static volatile boolean failed = false;
// Need to have enough data here that is too large for the socket buffer to hold.
// Also http.KeepAlive.remainingData must be greater than this value, default is 256K.
......@@ -155,48 +166,46 @@ class SimpleHttpTransaction implements HttpCallback
int port1;
public void request(HttpTransaction trans) {
public void handle(HttpExchange trans) {
try {
String path = trans.getRequestURI().getPath();
if (path.equals("/firstCall")) {
port1 = trans.channel().socket().getPort();
port1 = trans.getLocalAddress().getPort();
System.out.println("First connection on client port = " + port1);
byte[] responseBody = new byte[RESPONSE_DATA_LENGTH];
for (int i=0; i<responseBody.length; i++)
responseBody[i] = 0x41;
trans.setResponseEntityBody (responseBody, responseBody.length);
trans.sendResponse(200, "OK");
trans.sendResponseHeaders(200, 0);
try(PrintWriter pw = new PrintWriter(trans.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print(responseBody);
}
} else if (path.equals("/secondCall")) {
int port2 = trans.channel().socket().getPort();
int port2 = trans.getLocalAddress().getPort();
System.out.println("Second connection on client port = " + port2);
if (port1 != port2)
failed = true;
trans.setResponseHeader ("Content-length", Integer.toString(0));
/* Force the server to not respond for more that the timeout
* set by the keepalive cleaner (5000 millis). This ensures the
* timeout is correctly resets the default read timeout,
* infinity. See 6993490. */
System.out.println("server sleeping...");
try {Thread.sleep(6000); } catch (InterruptedException e) {}
trans.sendResponse(200, "OK");
trans.sendResponseHeaders(200, -1);
} else if(path.equals("/part2")) {
System.out.println("Call to /part2");
byte[] responseBody = new byte[RESPONSE_DATA_LENGTH];
for (int i=0; i<responseBody.length; i++)
responseBody[i] = 0x41;
trans.setResponseEntityBody (responseBody, responseBody.length);
// override the Content-length header to be greater than the actual response body
trans.setResponseHeader("Content-length", Integer.toString(responseBody.length+1));
trans.sendResponse(200, "OK");
trans.sendResponseHeaders(200, responseBody.length+1);
try(PrintWriter pw = new PrintWriter(trans.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print(responseBody);
}
// now close the socket
trans.channel().socket().close();
trans.close();
}
} catch (Exception e) {
e.printStackTrace();
......
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.net.*;
import java.util.*;
import java.io.IOException;
/**
* This class provides a partial implementation of the HttpCallback
* interface. Use this class if you want to use the requestURI as a means
* of tracking multiple invocations of a request (on the server).
* In this case, you implement the modified request() method, which includes
* an integer count parameter. This parameter indicates the number of times
* (starting at zero) the request URI has been received.
*/
public abstract class AbstractCallback implements HttpCallback {
Map requests;
static class Request {
URI uri;
int count;
Request (URI u) {
uri = u;
count = 0;
}
}
AbstractCallback () {
requests = Collections.synchronizedMap (new HashMap());
}
/**
* handle the given request and generate an appropriate response.
* @param msg the transaction containing the request from the
* client and used to send the response
*/
public void request (HttpTransaction msg) {
URI uri = msg.getRequestURI();
Request req = (Request) requests.get (uri);
if (req == null) {
req = new Request (uri);
requests.put (uri, req);
}
request (msg, req.count++);
}
/**
* Same as HttpCallback interface except that the integer n
* is provided to indicate sequencing of repeated requests using
* the same request URI. n starts at zero and is incremented
* for each successive call.
*
* @param msg the transaction containing the request from the
* client and used to send the response
* @param n value is 0 at first call, and is incremented by 1 for
* each subsequent call using the same request URI.
*/
abstract public void request (HttpTransaction msg, int n);
}
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.*;
import java.nio.channels.*;
import java.util.*;
class ClosedChannelList {
static final long TIMEOUT = 10 * 1000; /* 10 sec */
static class Element {
long expiry;
SelectionKey key;
Element (long l, SelectionKey key) {
expiry = l;
this.key = key;
}
}
LinkedList list;
public ClosedChannelList () {
list = new LinkedList ();
}
/* close chan after TIMEOUT milliseconds */
public synchronized void add (SelectionKey key) {
long exp = System.currentTimeMillis () + TIMEOUT;
list.add (new Element (exp, key));
}
public synchronized void check () {
check (false);
}
public synchronized void terminate () {
check (true);
}
public synchronized void check (boolean forceClose) {
Iterator iter = list.iterator ();
long now = System.currentTimeMillis();
while (iter.hasNext ()) {
Element elm = (Element)iter.next();
if (forceClose || elm.expiry <= now) {
SelectionKey k = elm.key;
try {
k.channel().close ();
} catch (IOException e) {}
k.cancel();
iter.remove();
}
}
}
}
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* This interface is implemented by classes that wish to handle incoming HTTP
* requests and generate responses. This could be a general purpose HTTP server
* or a test case that expects specific requests from a client.
* <p>
* The incoming request fields can be examined via the {@link HttpTransaction}
* object, and a response can also be generated and sent via the request object.
*/
public interface HttpCallback {
/**
* handle the given request and generate an appropriate response.
* @param msg the transaction containing the request from the
* client and used to send the response
*/
void request (HttpTransaction msg);
}
/*
* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import sun.net.www.MessageHeader;
/**
* This class encapsulates a HTTP request received and a response to be
* generated in one transaction. It provides methods for examaining the
* request from the client, and for building and sending a reply.
*/
public class HttpTransaction {
String command;
URI requesturi;
TestHttpServer.Server server;
MessageHeader reqheaders, reqtrailers;
String reqbody;
byte[] rspbody;
MessageHeader rspheaders, rsptrailers;
SelectionKey key;
int rspbodylen;
boolean rspchunked;
HttpTransaction (TestHttpServer.Server server, String command,
URI requesturi, MessageHeader headers,
String body, MessageHeader trailers, SelectionKey key) {
this.command = command;
this.requesturi = requesturi;
this.reqheaders = headers;
this.reqbody = body;
this.reqtrailers = trailers;
this.key = key;
this.server = server;
}
/**
* Get the value of a request header whose name is specified by the
* String argument.
*
* @param key the name of the request header
* @return the value of the header or null if it does not exist
*/
public String getRequestHeader (String key) {
return reqheaders.findValue (key);
}
/**
* Get the value of a response header whose name is specified by the
* String argument.
*
* @param key the name of the response header
* @return the value of the header or null if it does not exist
*/
public String getResponseHeader (String key) {
return rspheaders.findValue (key);
}
/**
* Get the request URI
*
* @return the request URI
*/
public URI getRequestURI () {
return requesturi;
}
public String toString () {
StringBuffer buf = new StringBuffer();
buf.append ("Request from: ").append (key.channel().toString()).append("\r\n");
buf.append ("Command: ").append (command).append("\r\n");
buf.append ("Request URI: ").append (requesturi).append("\r\n");
buf.append ("Headers: ").append("\r\n");
buf.append (reqheaders.toString()).append("\r\n");
buf.append ("Body: ").append (reqbody).append("\r\n");
buf.append ("---------Response-------\r\n");
buf.append ("Headers: ").append("\r\n");
if (rspheaders != null) {
buf.append (rspheaders.toString()).append("\r\n");
}
String rbody = rspbody == null? "": new String (rspbody);
buf.append ("Body: ").append (rbody).append("\r\n");
return new String (buf);
}
/**
* Get the value of a request trailer whose name is specified by
* the String argument.
*
* @param key the name of the request trailer
* @return the value of the trailer or null if it does not exist
*/
public String getRequestTrailer (String key) {
return reqtrailers.findValue (key);
}
/**
* Add a response header to the response. Multiple calls with the same
* key value result in multiple header lines with the same key identifier
* @param key the name of the request header to add
* @param val the value of the header
*/
public void addResponseHeader (String key, String val) {
if (rspheaders == null)
rspheaders = new MessageHeader ();
rspheaders.add (key, val);
}
/**
* Set a response header. Searches for first header with named key
* and replaces its value with val
* @param key the name of the request header to add
* @param val the value of the header
*/
public void setResponseHeader (String key, String val) {
if (rspheaders == null)
rspheaders = new MessageHeader ();
rspheaders.set (key, val);
}
/**
* Add a response trailer to the response. Multiple calls with the same
* key value result in multiple trailer lines with the same key identifier
* @param key the name of the request trailer to add
* @param val the value of the trailer
*/
public void addResponseTrailer (String key, String val) {
if (rsptrailers == null)
rsptrailers = new MessageHeader ();
rsptrailers.add (key, val);
}
/**
* Get the request method
*
* @return the request method
*/
public String getRequestMethod (){
return command;
}
/**
* Perform an orderly close of the TCP connection associated with this
* request. This method guarantees that any response already sent will
* not be reset (by this end). The implementation does a shutdownOutput()
* of the TCP connection and for a period of time consumes and discards
* data received on the reading side of the connection. This happens
* in the background. After the period has expired the
* connection is completely closed.
*/
public void orderlyClose () {
try {
server.orderlyCloseChannel (key);
} catch (IOException e) {
System.out.println (e);
}
}
/**
* Do an immediate abortive close of the TCP connection associated
* with this request.
*/
public void abortiveClose () {
try {
server.abortiveCloseChannel(key);
} catch (IOException e) {
System.out.println (e);
}
}
/**
* Get the SocketChannel associated with this request
*
* @return the socket channel
*/
public SocketChannel channel() {
return (SocketChannel) key.channel();
}
/**
* Get the request entity body associated with this request
* as a single String.
*
* @return the entity body in one String
*/
public String getRequestEntityBody (){
return reqbody;
}
/**
* Set the entity response body with the given string
* The content length is set to the length of the string
* @param body the string to send in the response
*/
public void setResponseEntityBody (String body){
rspbody = body.getBytes();
rspbodylen = body.length();
rspchunked = false;
addResponseHeader ("Content-length", Integer.toString (rspbodylen));
}
/**
* Set the entity response body with the given byte[]
* The content length is set to the gven length
* @param body the string to send in the response
*/
public void setResponseEntityBody (byte[] body, int len){
rspbody = body;
rspbodylen = len;
rspchunked = false;
addResponseHeader ("Content-length", Integer.toString (rspbodylen));
}
/**
* Set the entity response body by reading the given inputstream
*
* @param is the inputstream from which to read the body
*/
public void setResponseEntityBody (InputStream is) throws IOException {
byte[] buf = new byte [2048];
byte[] total = new byte [2048];
int total_len = 2048;
int c, len=0;
while ((c=is.read (buf)) != -1) {
if (len+c > total_len) {
byte[] total1 = new byte [total_len * 2];
System.arraycopy (total, 0, total1, 0, len);
total = total1;
total_len = total_len * 2;
}
System.arraycopy (buf, 0, total, len, c);
len += c;
}
setResponseEntityBody (total, len);
}
/* chunked */
/**
* Set the entity response body with the given array of strings
* The content encoding is set to "chunked" and each array element
* is sent as one chunk.
* @param body the array of string chunks to send in the response
*/
public void setResponseEntityBody (String[] body) {
StringBuffer buf = new StringBuffer ();
int len = 0;
for (int i=0; i<body.length; i++) {
String chunklen = Integer.toHexString (body[i].length());
len += body[i].length();
buf.append (chunklen).append ("\r\n");
buf.append (body[i]).append ("\r\n");
}
buf.append ("0\r\n");
rspbody = new String (buf).getBytes();
rspbodylen = rspbody.length;
rspchunked = true;
addResponseHeader ("Transfer-encoding", "chunked");
}
/**
* Send the response with the current set of response parameters
* but using the response code and string tag line as specified
* @param rCode the response code to send
* @param rTag the response string to send with the response code
*/
public void sendResponse (int rCode, String rTag) throws IOException {
OutputStream os = new TestHttpServer.NioOutputStream(channel());
PrintStream ps = new PrintStream (os);
ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
if (rspheaders != null) {
rspheaders.print (ps);
} else {
ps.print ("\r\n");
}
ps.flush ();
if (rspbody != null) {
os.write (rspbody, 0, rspbodylen);
os.flush();
}
if (rsptrailers != null) {
rsptrailers.print (ps);
} else if (rspchunked) {
ps.print ("\r\n");
}
ps.flush();
}
/* sends one byte less than intended */
public void sendPartialResponse (int rCode, String rTag)throws IOException {
OutputStream os = new TestHttpServer.NioOutputStream(channel());
PrintStream ps = new PrintStream (os);
ps.print ("HTTP/1.1 " + rCode + " " + rTag + "\r\n");
ps.flush();
if (rspbody != null) {
os.write (rspbody, 0, rspbodylen-1);
os.flush();
}
if (rsptrailers != null) {
rsptrailers.print (ps);
}
ps.flush();
}
}
This diff is collapsed.
......@@ -32,12 +32,22 @@
* system properties in samevm/agentvm mode.
*/
import java.io.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.URL;
import java.security.KeyStore;
import javax.net.*;
import javax.net.ssl.*;
import java.security.cert.*;
import javax.net.ServerSocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
/*
* ClientHelloRead.java -- includes a simple server that can serve
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment