1 /* 2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.io.*; 25 import java.util.function.Supplier; 26 import jdk.incubator.http.internal.common.HttpHeadersImpl; 27 import static java.nio.charset.StandardCharsets.ISO_8859_1; 28 29 public class RedirectHandler implements Http2Handler { 30 31 final Supplier<String> supplier; 32 33 public RedirectHandler(Supplier<String> redirectSupplier) { 34 supplier = redirectSupplier; 35 } 36 37 static String consume(InputStream is) throws IOException { 38 byte[] b = new byte[1024]; 39 int i; 40 StringBuilder sb = new StringBuilder(); 41 42 while ((i=is.read(b)) != -1) { 43 sb.append(new String(b, 0, i, ISO_8859_1)); 44 } 45 is.close(); 46 return sb.toString(); 47 } 48 49 @Override 50 public void handle(Http2TestExchange t) throws IOException { 51 try { 52 consume(t.getRequestBody()); 53 String location = supplier.get(); 54 System.err.println("RedirectHandler received request to " + t.getRequestURI()); 55 System.err.println("Redirecting to: " + location); 56 HttpHeadersImpl map1 = t.getResponseHeaders(); 57 map1.addHeader("Location", location); 58 t.sendResponseHeaders(301, 0); 59 // return the number of bytes received (no echo) 60 t.close(); 61 } catch (Throwable e) { 62 e.printStackTrace(); 63 throw new IOException(e); 64 } 65 } 66 }