Path: blob/master/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/CookieHandlerTest.java
41161 views
/*1* Copyright (c) 2003, 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/* @test24* @bug 4696506 494265025* @summary Unit test for java.net.CookieHandler26* @library /test/lib27* @run main/othervm CookieHandlerTest28*29* SunJSSE does not support dynamic system properties, no way to re-use30* system properties in samevm/agentvm mode.31* @author Yingxian Wang32*/3334import java.net.*;35import java.util.*;36import java.io.*;37import javax.net.ssl.*;38import jdk.test.lib.net.URIBuilder;3940public class CookieHandlerTest {41static Map<String,String> cookies;42ServerSocket ss;4344/*45* =============================================================46* Set the various variables needed for the tests, then47* specify what tests to run on each side.48*/4950/*51* Should we run the client or server in a separate thread?52* Both sides can throw exceptions, but do you have a preference53* as to which side should be the main thread.54*/55static boolean separateServerThread = true;5657/*58* Where do we find the keystores?59*/60static String pathToStores = "../../../../../../javax/net/ssl/etc";61static String keyStoreFile = "keystore";62static String trustStoreFile = "truststore";63static String passwd = "passphrase";6465/*66* Is the server ready to serve?67*/68volatile static boolean serverReady = false;6970/*71* Turn on SSL debugging?72*/73static boolean debug = false;7475/*76* Define the server side of the test.77*78* If the server prematurely exits, serverReady will be set to true79* to avoid infinite hangs.80*/81void doServerSide() throws Exception {82InetAddress loopback = InetAddress.getLoopbackAddress();83SSLServerSocketFactory sslssf =84(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();85SSLServerSocket sslServerSocket =86(SSLServerSocket) sslssf.createServerSocket();87sslServerSocket.bind(new InetSocketAddress(loopback, serverPort));88serverPort = sslServerSocket.getLocalPort();8990/*91* Signal Client, we're ready for his connect.92*/93serverReady = true;94SSLSocket sslSocket = null;95try {96sslSocket = (SSLSocket) sslServerSocket.accept();9798// check request contains "Cookie"99InputStream is = sslSocket.getInputStream ();100BufferedReader r = new BufferedReader(new InputStreamReader(is));101boolean flag = false;102String x;103while ((x=r.readLine()) != null) {104if (x.length() ==0) {105break;106}107String header = "Cookie: ";108if (x.startsWith(header)) {109if (x.equals("Cookie: "+((String)cookies.get("Cookie")))) {110flag = true;111}112}113}114if (!flag) {115throw new RuntimeException("server should see cookie in request");116}117118PrintStream out = new PrintStream(119new BufferedOutputStream(120sslSocket.getOutputStream() ));121122/* send the header */123out.print("HTTP/1.1 200 OK\r\n");124out.print("Set-Cookie2: "+((String)cookies.get("Set-Cookie2")+"\r\n"));125out.print("Content-Type: text/html; charset=iso-8859-1\r\n");126out.print("Connection: close\r\n");127out.print("\r\n");128out.print("<HTML>");129out.print("<HEAD><TITLE>Testing cookie</TITLE></HEAD>");130out.print("<BODY>OK.</BODY>");131out.print("</HTML>");132out.flush();133134sslSocket.close();135sslServerSocket.close();136} catch (Exception e) {137e.printStackTrace();138}139}140141/*142* Define the client side of the test.143*144* If the server prematurely exits, serverReady will be set to true145* to avoid infinite hangs.146*/147void doClientSide() throws Exception {148149/*150* Wait for server to get started.151*/152while (!serverReady) {153Thread.sleep(50);154}155HttpsURLConnection http = null;156/* establish http connection to server */157URL url = URIBuilder.newBuilder()158.scheme("https")159.loopback()160.port(serverPort)161.toURL();162HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());163http = (HttpsURLConnection)url.openConnection();164165int respCode = http.getResponseCode();166http.disconnect();167168}169170static class NameVerifier implements HostnameVerifier {171public boolean verify(String hostname, SSLSession session) {172return true;173}174}175176/*177* =============================================================178* The remainder is just support stuff179*/180181// use any free port by default182volatile int serverPort = 0;183184volatile Exception serverException = null;185volatile Exception clientException = null;186187public static void main(String args[]) throws Exception {188String keyFilename =189System.getProperty("test.src", "./") + "/" + pathToStores +190"/" + keyStoreFile;191String trustFilename =192System.getProperty("test.src", "./") + "/" + pathToStores +193"/" + trustStoreFile;194195CookieHandler reservedCookieHandler = CookieHandler.getDefault();196HostnameVerifier reservedHV =197HttpsURLConnection.getDefaultHostnameVerifier();198try {199System.setProperty("javax.net.ssl.keyStore", keyFilename);200System.setProperty("javax.net.ssl.keyStorePassword", passwd);201System.setProperty("javax.net.ssl.trustStore", trustFilename);202System.setProperty("javax.net.ssl.trustStorePassword", passwd);203204if (debug)205System.setProperty("javax.net.debug", "all");206207/*208* Start the tests.209*/210cookies = new HashMap<String, String>();211cookies.put("Cookie",212"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"");213cookies.put("Set-Cookie2",214"$Version=\"1\"; Part_Number=\"Riding_Rocket_0023\"; " +215"$Path=\"/acme/ammo\"; Part_Number=\"Rocket_Launcher_0001\"; "+216"$Path=\"/acme\"");217CookieHandler.setDefault(new MyCookieHandler());218new CookieHandlerTest();219} finally {220HttpsURLConnection.setDefaultHostnameVerifier(reservedHV);221CookieHandler.setDefault(reservedCookieHandler);222}223}224225Thread clientThread = null;226Thread serverThread = null;227/*228* Primary constructor, used to drive remainder of the test.229*230* Fork off the other side, then do your work.231*/232CookieHandlerTest() throws Exception {233if (separateServerThread) {234startServer(true);235startClient(false);236} else {237startClient(true);238startServer(false);239}240241/*242* Wait for other side to close down.243*/244if (separateServerThread) {245serverThread.join();246} else {247clientThread.join();248}249250/*251* When we get here, the test is pretty much over.252*253* If the main thread excepted, that propagates back254* immediately. If the other thread threw an exception, we255* should report back.256*/257if (serverException != null)258throw serverException;259if (clientException != null)260throw clientException;261262if (!getCalled || !putCalled) {263throw new RuntimeException ("Either get or put method is not called");264}265}266267void startServer(boolean newThread) throws Exception {268if (newThread) {269serverThread = new Thread() {270public void run() {271try {272doServerSide();273} catch (Exception e) {274/*275* Our server thread just died.276*277* Release the client, if not active already...278*/279System.err.println("Server died...");280serverReady = true;281serverException = e;282}283}284};285serverThread.start();286} else {287doServerSide();288}289}290291void startClient(boolean newThread) throws Exception {292if (newThread) {293clientThread = new Thread() {294public void run() {295try {296doClientSide();297} catch (Exception e) {298/*299* Our client thread just died.300*/301System.err.println("Client died...");302clientException = e;303}304}305};306clientThread.start();307} else {308doClientSide();309}310}311312static boolean getCalled = false, putCalled = false;313314static class MyCookieHandler extends CookieHandler {315public Map<String,List<String>>316get(URI uri, Map<String,List<String>> requestHeaders)317throws IOException {318getCalled = true;319// returns cookies[0]320// they will be include in request321Map<String,List<String>> map = new HashMap<>();322List<String> l = new ArrayList<>();323l.add(cookies.get("Cookie"));324map.put("Cookie",l);325return Collections.unmodifiableMap(map);326}327328public void329put(URI uri, Map<String,List<String>> responseHeaders)330throws IOException {331putCalled = true;332// check response has cookies[1]333List<String> l = responseHeaders.get("Set-Cookie2");334String value = l.get(0);335if (!value.equals((String)cookies.get("Set-Cookie2"))) {336throw new RuntimeException("cookie should be available for handle to put into cache");337}338}339}340341}342343344