Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/CookieHandlerTest.java
38889 views
/*1* Copyright (c) 2003, 2011, 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* @run main/othervm CookieHandlerTest27*28* SunJSSE does not support dynamic system properties, no way to re-use29* system properties in samevm/agentvm mode.30* @author Yingxian Wang31*/3233import java.net.*;34import java.util.*;35import java.io.*;36import javax.net.ssl.*;3738public class CookieHandlerTest {39static Map<String,String> cookies;40ServerSocket ss;4142/*43* =============================================================44* Set the various variables needed for the tests, then45* specify what tests to run on each side.46*/4748/*49* Should we run the client or server in a separate thread?50* Both sides can throw exceptions, but do you have a preference51* as to which side should be the main thread.52*/53static boolean separateServerThread = true;5455/*56* Where do we find the keystores?57*/58static String pathToStores = "../../../../../../javax/net/ssl/etc";59static String keyStoreFile = "keystore";60static String trustStoreFile = "truststore";61static String passwd = "passphrase";6263/*64* Is the server ready to serve?65*/66volatile static boolean serverReady = false;6768/*69* Turn on SSL debugging?70*/71static boolean debug = false;7273/*74* Define the server side of the test.75*76* If the server prematurely exits, serverReady will be set to true77* to avoid infinite hangs.78*/79void doServerSide() throws Exception {80SSLServerSocketFactory sslssf =81(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();82SSLServerSocket sslServerSocket =83(SSLServerSocket) sslssf.createServerSocket(serverPort);84serverPort = sslServerSocket.getLocalPort();8586/*87* Signal Client, we're ready for his connect.88*/89serverReady = true;90SSLSocket sslSocket = null;91try {92sslSocket = (SSLSocket) sslServerSocket.accept();9394// check request contains "Cookie"95InputStream is = sslSocket.getInputStream ();96BufferedReader r = new BufferedReader(new InputStreamReader(is));97boolean flag = false;98String x;99while ((x=r.readLine()) != null) {100if (x.length() ==0) {101break;102}103String header = "Cookie: ";104if (x.startsWith(header)) {105if (x.equals("Cookie: "+((String)cookies.get("Cookie")))) {106flag = true;107}108}109}110if (!flag) {111throw new RuntimeException("server should see cookie in request");112}113114PrintStream out = new PrintStream(115new BufferedOutputStream(116sslSocket.getOutputStream() ));117118/* send the header */119out.print("HTTP/1.1 200 OK\r\n");120out.print("Set-Cookie2: "+((String)cookies.get("Set-Cookie2")+"\r\n"));121out.print("Content-Type: text/html; charset=iso-8859-1\r\n");122out.print("Connection: close\r\n");123out.print("\r\n");124out.print("<HTML>");125out.print("<HEAD><TITLE>Testing cookie</TITLE></HEAD>");126out.print("<BODY>OK.</BODY>");127out.print("</HTML>");128out.flush();129130sslSocket.close();131sslServerSocket.close();132} catch (Exception e) {133e.printStackTrace();134}135}136137/*138* Define the client side of the test.139*140* If the server prematurely exits, serverReady will be set to true141* to avoid infinite hangs.142*/143void doClientSide() throws Exception {144145/*146* Wait for server to get started.147*/148while (!serverReady) {149Thread.sleep(50);150}151HttpsURLConnection http = null;152/* establish http connection to server */153String uri = "https://localhost:" + +serverPort ;154URL url = new URL(uri);155HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());156http = (HttpsURLConnection)url.openConnection();157158int respCode = http.getResponseCode();159http.disconnect();160161}162163static class NameVerifier implements HostnameVerifier {164public boolean verify(String hostname, SSLSession session) {165return true;166}167}168169/*170* =============================================================171* The remainder is just support stuff172*/173174// use any free port by default175volatile int serverPort = 0;176177volatile Exception serverException = null;178volatile Exception clientException = null;179180public static void main(String args[]) throws Exception {181String keyFilename =182System.getProperty("test.src", "./") + "/" + pathToStores +183"/" + keyStoreFile;184String trustFilename =185System.getProperty("test.src", "./") + "/" + pathToStores +186"/" + trustStoreFile;187188CookieHandler reservedCookieHandler = CookieHandler.getDefault();189HostnameVerifier reservedHV =190HttpsURLConnection.getDefaultHostnameVerifier();191try {192System.setProperty("javax.net.ssl.keyStore", keyFilename);193System.setProperty("javax.net.ssl.keyStorePassword", passwd);194System.setProperty("javax.net.ssl.trustStore", trustFilename);195System.setProperty("javax.net.ssl.trustStorePassword", passwd);196197if (debug)198System.setProperty("javax.net.debug", "all");199200/*201* Start the tests.202*/203cookies = new HashMap<String, String>();204cookies.put("Cookie",205"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"");206cookies.put("Set-Cookie2",207"$Version=\"1\"; Part_Number=\"Riding_Rocket_0023\"; " +208"$Path=\"/acme/ammo\"; Part_Number=\"Rocket_Launcher_0001\"; "+209"$Path=\"/acme\"");210CookieHandler.setDefault(new MyCookieHandler());211new CookieHandlerTest();212} finally {213HttpsURLConnection.setDefaultHostnameVerifier(reservedHV);214CookieHandler.setDefault(reservedCookieHandler);215}216}217218Thread clientThread = null;219Thread serverThread = null;220/*221* Primary constructor, used to drive remainder of the test.222*223* Fork off the other side, then do your work.224*/225CookieHandlerTest() throws Exception {226if (separateServerThread) {227startServer(true);228startClient(false);229} else {230startClient(true);231startServer(false);232}233234/*235* Wait for other side to close down.236*/237if (separateServerThread) {238serverThread.join();239} else {240clientThread.join();241}242243/*244* When we get here, the test is pretty much over.245*246* If the main thread excepted, that propagates back247* immediately. If the other thread threw an exception, we248* should report back.249*/250if (serverException != null)251throw serverException;252if (clientException != null)253throw clientException;254255if (!getCalled || !putCalled) {256throw new RuntimeException ("Either get or put method is not called");257}258}259260void startServer(boolean newThread) throws Exception {261if (newThread) {262serverThread = new Thread() {263public void run() {264try {265doServerSide();266} catch (Exception e) {267/*268* Our server thread just died.269*270* Release the client, if not active already...271*/272System.err.println("Server died...");273serverReady = true;274serverException = e;275}276}277};278serverThread.start();279} else {280doServerSide();281}282}283284void startClient(boolean newThread) throws Exception {285if (newThread) {286clientThread = new Thread() {287public void run() {288try {289doClientSide();290} catch (Exception e) {291/*292* Our client thread just died.293*/294System.err.println("Client died...");295clientException = e;296}297}298};299clientThread.start();300} else {301doClientSide();302}303}304305static boolean getCalled = false, putCalled = false;306307static class MyCookieHandler extends CookieHandler {308public Map<String,List<String>>309get(URI uri, Map<String,List<String>> requestHeaders)310throws IOException {311getCalled = true;312// returns cookies[0]313// they will be include in request314Map<String,List<String>> map = new HashMap<>();315List<String> l = new ArrayList<>();316l.add(cookies.get("Cookie"));317map.put("Cookie",l);318return Collections.unmodifiableMap(map);319}320321public void322put(URI uri, Map<String,List<String>> responseHeaders)323throws IOException {324putCalled = true;325// check response has cookies[1]326List<String> l = responseHeaders.get("Set-Cookie2");327String value = l.get(0);328if (!value.equals((String)cookies.get("Set-Cookie2"))) {329throw new RuntimeException("cookie should be available for handle to put into cache");330}331}332}333334}335336337