Path: blob/master/test/jdk/java/net/ResponseCache/ResponseCacheTest.java
41149 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* @summary Unit test for java.net.ResponseCache25* @bug 483726726* @library /test/lib27* @author Yingxian Wang28*/2930import java.net.*;31import java.util.*;32import java.io.*;33import javax.net.ssl.*;34import jdk.test.lib.net.URIBuilder;35import static java.net.Proxy.NO_PROXY;3637/**38* Request should get serviced by the cache handler. Response get39* saved through the cache handler.40*/41public class ResponseCacheTest implements Runnable {42ServerSocket ss;43static URL url1;44static URL url2;45static String FNPrefix, OutFNPrefix;46static List<Closeable> streams = new ArrayList<>();47static List<File> files = new ArrayList<>();4849/*50* Our "http" server to return a 404 */51public void run() {52Socket s = null;53FileInputStream fis = null;54try {55s = ss.accept();5657InputStream is = s.getInputStream ();58BufferedReader r = new BufferedReader(new InputStreamReader(is));59String x;60while ((x=r.readLine()) != null) {61if (x.length() ==0) {62break;63}64}65PrintStream out = new PrintStream(66new BufferedOutputStream(67s.getOutputStream() ));6869/* send file2.1 */70File file2 = new File(FNPrefix+"file2.1");71out.print("HTTP/1.1 200 OK\r\n");72out.print("Content-Type: text/html; charset=iso-8859-1\r\n");73out.print("Content-Length: "+file2.length()+"\r\n");74out.print("Connection: close\r\n");75out.print("\r\n");76fis = new FileInputStream(file2);77byte[] buf = new byte[(int)file2.length()];78int len;79while ((len = fis.read(buf)) != -1) {80out.print(new String(buf));81}8283out.flush();8485s.close();86ss.close();87} catch (Exception e) {88e.printStackTrace();89} finally {90try { ss.close(); } catch (IOException unused) {}91try { s.close(); } catch (IOException unused) {}92try { fis.close(); } catch (IOException unused) {}93}94}95static class NameVerifier implements HostnameVerifier {96public boolean verify(String hostname, SSLSession session) {97return true;98}99}100ResponseCacheTest() throws Exception {101/* start the server */102InetAddress loopback = InetAddress.getLoopbackAddress();103ss = new ServerSocket();104ss.bind(new InetSocketAddress(loopback, 0));105106(new Thread(this)).start();107/* establish http connection to server */108url1 = new URL("http://localhost/file1.cache");109HttpURLConnection http = (HttpURLConnection)url1.openConnection();110InputStream is = null;111System.out.println("request headers: "+http.getRequestProperties());112System.out.println("responsecode is :"+http.getResponseCode());113Map<String,List<String>> headers1 = http.getHeaderFields();114try {115is = http.getInputStream();116} catch (IOException ioex) {117throw new RuntimeException(ioex.getMessage());118}119BufferedReader r = new BufferedReader(new InputStreamReader(is));120String x;121File fileout = new File(OutFNPrefix+"file1");122PrintStream out = new PrintStream(123new BufferedOutputStream(124new FileOutputStream(fileout)));125while ((x=r.readLine()) != null) {126out.print(x+"\n");127}128out.flush();129out.close();130131http.disconnect();132133// testing ResponseCacheHandler.put()134url2 = URIBuilder.newBuilder()135.scheme("http")136.host(ss.getInetAddress())137.port(ss.getLocalPort())138.path("/file2.1")139.toURL();140http = (HttpURLConnection)url2.openConnection(NO_PROXY);141System.out.println("responsecode2 is :"+http.getResponseCode());142Map<String,List<String>> headers2 = http.getHeaderFields();143144try {145is = http.getInputStream();146} catch (IOException ioex) {147throw new RuntimeException(ioex.getMessage());148}149r = new BufferedReader(new InputStreamReader(is));150fileout = new File(OutFNPrefix+"file2.2");151out = new PrintStream(152new BufferedOutputStream(153new FileOutputStream(fileout)));154while ((x=r.readLine()) != null) {155out.print(x+"\n");156}157out.flush();158out.close();159160// assert (headers1 == headers2 && file1 == file2.2)161File file1 = new File(OutFNPrefix+"file1");162File file2 = new File(OutFNPrefix+"file2.2");163files.add(file1);164files.add(file2);165System.out.println("headers1"+headers1+"\nheaders2="+headers2);166if (!headers1.equals(headers2) || file1.length() != file2.length()) {167throw new RuntimeException("test failed");168}169}170171public static void main(String args[]) throws Exception {172try {173ResponseCache.setDefault(new MyResponseCache());174FNPrefix = System.getProperty("test.src", ".")+"/";175OutFNPrefix = System.getProperty("test.scratch", ".")+"/";176new ResponseCacheTest();177} finally{178ResponseCache.setDefault(null);179for (Closeable c: streams) {180try { c.close(); } catch (IOException unused) {}181}182for (File f: files) {183f.delete();184}185}186}187188static class MyResponseCache extends ResponseCache {189public CacheResponse get(URI uri, String rqstMethod,190Map<String,List<String>> rqstHeaders)191throws IOException192{193try {194if (uri.equals(url1.toURI())) {195return new MyCacheResponse(FNPrefix+"file1.cache");196}197} catch (URISyntaxException ex) {198throw new RuntimeException (ex);199}200return null;201}202203public CacheRequest put(URI uri, URLConnection conn) throws IOException {204// save cache to file2.cache205// 1. serialize headers into file2.cache206// 2. write data to file2.cache207return new MyCacheRequest(OutFNPrefix+"file2.cache", conn.getHeaderFields());208}209}210211static class MyCacheResponse extends CacheResponse {212FileInputStream fis;213Map<String,List<String>> headers;214public MyCacheResponse(String filename) {215try {216fis = new FileInputStream(new File(filename));217streams.add(fis);218ObjectInputStream ois = new ObjectInputStream(fis);219headers = (Map<String,List<String>>)ois.readObject();220} catch (Exception ex) {221// throw new RuntimeException(ex.getMessage());222}223}224225public InputStream getBody() throws IOException {226return fis;227}228229public Map<String,List<String>> getHeaders() throws IOException {230return headers;231}232}233234static class MyCacheRequest extends CacheRequest {235FileOutputStream fos;236public MyCacheRequest(String filename, Map<String,List<String>> rspHeaders) {237try {238File file = new File(filename);239fos = new FileOutputStream(file);240streams.add(fos);241files.add(file);242ObjectOutputStream oos = new ObjectOutputStream(fos);243oos.writeObject(rspHeaders);244} catch (Exception ex) {245throw new RuntimeException(ex.getMessage());246}247}248public OutputStream getBody() throws IOException {249return fos;250}251252public void abort() {253// no op254}255}256257258}259260261