undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,83 @@
/*
* Copyright (c) 2006, 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.URL;
import java.net.URLConnection;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args)
throws Exception {
String baseDir = args[0];
String archiveName = args[1];
String lProperty = System.getProperty("do.iterations", "5000");
int lRepetitions = Integer.valueOf(lProperty);
System.out.println("Start creating copys of the archive, "
+ lRepetitions + " times");
for (int i = 0; i < lRepetitions; i++) {
// Copy the given jar file and add a prefix
copyFile(baseDir, archiveName, i);
}
System.out.println("Start opening the archives archive, "
+ lRepetitions + " times");
System.out.println("First URL is jar:" + Paths.get(baseDir,
0 + archiveName).toUri() + "!/foo/Test.class");
for (int i = 0; i < lRepetitions; i++) {
// Create URL
String lURLPath = "jar:" + Paths.get(baseDir, i
+ archiveName).toUri() + "!/foo/Test.class";
URL lURL = new URL(lURLPath);
// Open URL Connection
try {
URLConnection lConnection = lURL.openConnection();
lConnection.getInputStream();
} catch (java.io.FileNotFoundException fnfe) {
// Ignore this one because we expect this one
} catch (java.util.zip.ZipException ze) {
throw new RuntimeException("Test failed: " + ze.getMessage());
}
}
}
private static void copyFile( String pBaseDir, String pArchiveName, int pIndex) {
try {
java.io.File lSource = new java.io.File( pBaseDir, pArchiveName );
java.io.File lDestination = new java.io.File( pBaseDir, pIndex + pArchiveName );
if( !lDestination.exists() ) {
lDestination.createNewFile();
java.io.InputStream lInput = new java.io.FileInputStream( lSource );
java.io.OutputStream lOutput = new java.io.FileOutputStream( lDestination );
byte[] lBuffer = new byte[ 1024 ];
int lLength = -1;
while( ( lLength = lInput.read( lBuffer ) ) > 0 ) {
lOutput.write( lBuffer, 0, lLength );
}
lInput.close();
lOutput.close();
}
} catch( Exception e ) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2017, 2024, 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.
*/
/**
* @test
* @bug 6212146
* @summary URLConnection.connect() fails on JAR Entry it creates
* file handler leak
* @library /test/lib
* @requires vm.flagless
* @build jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* Test
* @run main/othervm TestDriver
*/
import jdk.test.lib.JDKToolFinder;
import jdk.test.lib.process.ProcessTools;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class TestDriver {
private static final String BASE_DIR = System.getProperty("user.dir")
+ "/jars/";
private static final String ARCHIVE_NAME = "test.jar";
private static final String CMD_ULIMIT = "ulimit -n 300;";
public static void main(String[] args)
throws Throwable {
setup(BASE_DIR);
String testCMD = CMD_ULIMIT + JDKToolFinder.getTestJDKTool("java")
+ " Test " + BASE_DIR + " " + ARCHIVE_NAME;
boolean isWindows = System.getProperty("os.name").startsWith("Windows");
if (isWindows) {
testCMD = testCMD.replace("\\", "/");
}
ProcessTools.executeCommand("sh", "-c", testCMD)
.outputTo(System.out)
.errorTo(System.err)
.shouldHaveExitValue(0);
}
private static void setup(String baseDir) throws IOException {
Path testJar = Paths.get(System.getProperty("test.src"), ARCHIVE_NAME);
Path targetDir = Paths.get(baseDir);
Files.createDirectories(targetDir);
Files.copy(testJar, targetDir.resolve(ARCHIVE_NAME), REPLACE_EXISTING);
}
}

Binary file not shown.

View file

@ -0,0 +1,116 @@
/*
* 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
* 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.
*/
/*
* @test
* @modules java.base/sun.net.www.protocol.file
* @bug 5052093
* @library /test/lib
* @run main/othervm B5052093
* @summary URLConnection doesn't support large files
*/
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 {
private static HttpServer server;
static long testSize = ((long) (Integer.MAX_VALUE)) + 2;
public static class LargeFile extends File {
public LargeFile() {
super("/dev/zero");
}
public long length() {
return testSize;
}
}
public static class LargeFileURLConnection extends FileURLConnection {
public LargeFileURLConnection(LargeFile f) throws IOException {
super(new URL("file:///dev/zero"), f);
}
}
public static void main(String[] args) throws Exception {
InetAddress loopback = InetAddress.getLoopbackAddress();
server = HttpServer.create(new InetSocketAddress(loopback, 0), 10, "/", new B5052093Handler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
try {
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();
if (i != -1 || l != testSize) {
System.out.println("conn.getContentLength = " + i);
System.out.println("conn.getContentLengthLong = " + l);
System.out.println("testSize = " + testSize);
throw new RuntimeException("Wrong content-length from http");
}
URLConnection fu = new LargeFileURLConnection(new LargeFile());
i = fu.getContentLength();
l = fu.getContentLengthLong();
if (i != -1 || l != testSize) {
System.out.println("fu.getContentLength = " + i);
System.out.println("fu.getContentLengthLong = " + l);
System.out.println("testSize = " + testSize);
throw new RuntimeException("Wrong content-length from file");
}
} finally {
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();
}
}
}

View file

@ -0,0 +1,202 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/**
* @test
* @bug 4333920
* @bug 4394548
* @library /test/lib
* @summary Check that chunked encoding response doesn't cause
* getInputStream to block until last chunk arrives.
* Also regression against NPE in ChunkedInputStream.
*/
import java.net.*;
import java.io.*;
import java.util.Random;
import jdk.test.lib.net.URIBuilder;
public class ChunkedEncoding implements Runnable {
ServerSocket ss;
/*
* Our "http" server to return a chunked response
*/
public void run() {
try {
Socket s = ss.accept();
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
/* send the header */
out.print("HTTP/1.1 200\r\n");
out.print("Transfer-Encoding: chunked\r\n");
out.print("Content-Type: text/html\r\n");
out.print("\r\n");
out.flush();
/* delay the server before first chunk */
Thread.sleep(5000);
/*
* Our response will be of random length
* but > 32k
*/
Random rand = new Random();
int len;
do {
len = rand.nextInt(128*1024);
} while (len < 32*1024);
/*
* Our chunk size will be 2-32k
*/
int chunkSize;
do {
chunkSize = rand.nextInt(len / 3);
} while (chunkSize < 2*1024);
/*
* Generate random content and check sum it
*/
byte buf[] = new byte[len];
int cs = 0;
for (int i=0; i<len; i++) {
buf[i] = (byte)('a' + rand.nextInt(26));
cs = (cs + buf[i]) % 65536;
}
/*
* Stream the chunks to the client
*/
int remaining = len;
int pos = 0;
while (remaining > 0) {
int size = Math.min(remaining, chunkSize);
out.print( Integer.toHexString(size) );
out.print("\r\n");
out.write( buf, pos, size );
pos += size;
remaining -= size;
out.print("\r\n");
out.flush();
}
/* send EOF chunk */
out.print("0\r\n");
out.flush();
/*
* Send trailer with checksum
*/
String trailer = "Checksum:" + cs + "\r\n";
out.print(trailer);
out.print("\r\n");
out.flush();
/*
* Sleep added to avoid connection reset
* on the client side
*/
Thread.sleep(1000);
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
ChunkedEncoding() throws Exception {
/* start the server */
ss = new ServerSocket();
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
(new Thread(this)).start();
/* establish http connection to server */
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.path("/foo")
.toURL();
HttpURLConnection http = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
/*
* Server should only send headers if TE:trailers
* specified - see updated HTTP 1.1 spec.
*/
http.setRequestProperty("TE", "trailers");
/* Time how long the getInputStream takes */
long ts = System.currentTimeMillis();
InputStream in = http.getInputStream();
long te = System.currentTimeMillis();
/*
* If getInputStream takes >2 seconds it probably means
* that the implementation is waiting for the chunks to
* arrive.
*/
if ( (te-ts) > 2000) {
throw new Exception("getInputStream didn't return immediately");
}
/*
* Read the stream and checksum it as it arrives
*/
int nread;
int cs = 0;
byte b[] = new byte[1024];
do {
nread = in.read(b);
if (nread > 0) {
for (int i=0; i<nread; i++) {
cs = (cs + b[i]) % 65536;
}
}
} while (nread > 0);
/*
* Verify that the checksums match
*/
String trailer = http.getHeaderField("Checksum");
if (trailer == null) {
throw new Exception("Checksum trailer missing from response");
}
int rcvd_cs = Integer.parseInt(trailer);
if (rcvd_cs != cs) {
throw new Exception("Trailer checksum doesn't equal calculated checksum");
}
http.disconnect();
}
public static void main(String args[]) throws Exception {
new ChunkedEncoding();
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 1998, 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.
*/
/* @test
@bug 4134855
@summary Test for opening non existant file
*/
import java.net.*;
import java.io.*;
public class Connect {
public static void main(String s[]) throws Exception {
try {
// This file does not exist.
URL url = new URL("file:azwe.txt");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
// We reach here in JDK1.2beta3.
throw new RuntimeException("No FileNotFoundException thrown.");
}
catch(MalformedURLException e) {
}
catch(IOException e) {
}
}
}

View file

@ -0,0 +1,370 @@
/*
* Copyright (c) 2015, 2024, 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 jdk.test.lib.process.ProcessTools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonMap;
/*
* @test
* @bug 8064925
* @library /test/lib
* @summary Basic test for ContentHandler. Ensures discovery paths for content
* handlers follow a particular order.
*/
public class ContentHandlersTest {
public static void main(String[] args) throws Throwable {
step1_ContentHandlerFactory();
step2_ServiceLoader();
step3_UserDefined();
step4_BuiltIn();
}
private static void step1_ContentHandlerFactory() throws IOException {
String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory";
Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-1"));
Path src = templatesHome().resolve("test.template");
Path dst = tmp.resolve("Test.java");
Files.copy(src, dst);
Path build = Files.createDirectory(tmp.resolve("build"));
Path dst1 = fromTemplate(templatesHome().resolve("broken_factory.template"),
factoryClassFqn, tmp);
javac(build, dst, dst1);
Result r = java(emptyMap(), singleton(build), "Test", factoryClassFqn);
if (r.exitValue == 0 || !r.output.startsWith(
stackTraceStringForBrokenFactory(factoryClassFqn))) {
throw new RuntimeException(
"Expected a different kind of failure: " + r.output);
}
}
private static void step2_ServiceLoader() throws IOException {
String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory";
Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-2"));
Path src = templatesHome().resolve("test.template");
Path dst = tmp.resolve("Test.java");
Files.copy(src, dst);
Path dst1 = fromTemplate(templatesHome().resolve("broken_constructor_factory.template"),
factoryClassFqn, tmp);
Path build = Files.createDirectory(tmp.resolve("build"));
javac(build, dst);
Path explodedJar = Files.createDirectory(tmp.resolve("exploded-jar"));
Path services = Files.createDirectories(explodedJar.resolve("META-INF")
.resolve("services"));
Path s = services.resolve("java.net.ContentHandlerFactory");
try (FileWriter fw = new FileWriter(s.toFile())) {
fw.write(factoryClassFqn);
}
javac(explodedJar, dst1);
jar(tmp.resolve("test.jar"), explodedJar);
Files.copy(tmp.resolve("test.jar"), build.resolve("test.jar"));
Result r = java(emptyMap(), asList(build.resolve("test.jar"), build), "Test");
if (r.exitValue == 0 || !verifyOutput(r.output, factoryClassFqn))
throw new RuntimeException(r.output);
}
private static void step3_UserDefined() throws IOException {
String packagePrefix = "net.java.openjdk.test";
String fqn = packagePrefix + ".text.plain";
Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-3"));
Path src = templatesHome().resolve("test.template");
Path dst = tmp.resolve("Test.java");
Files.copy(src, dst);
Path dst1 = fromTemplate(templatesHome().resolve("plain.template"),
fqn, tmp);
Path build = Files.createDirectory(tmp.resolve("build"));
javac(build, dst);
Path classes = Files.createDirectory(tmp.resolve("classes"));
javac(classes, dst1);
Map<String, String> m = singletonMap("java.content.handler.pkgs", packagePrefix);
Result r = java(m, asList(build, classes), "Test");
if (r.exitValue != 0 || !r.output.contains(fqn))
throw new RuntimeException(r.output);
}
private static void step4_BuiltIn() throws IOException {
Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-4"));
Path src = templatesHome().resolve("test.template");
Path dst = tmp.resolve("Test.java");
Files.copy(src, dst);
Path build = Files.createDirectory(tmp.resolve("build"));
javac(build, dst);
Result r = java(emptyMap(), singleton(build), "Test");
if (r.exitValue != 0 || !r.output.contains("sun.net.www.content.text.PlainTextInputStream"))
throw new RuntimeException(r.output);
}
private static String stackTraceStringForBrokenFactory(String fqn) {
return "Exception in thread \"main\" java.lang.RuntimeException: " +
"This is a broken factory. It is supposed to throw this exception.";
}
private static Path fromTemplate(Path srcTemplate,
String factoryFqn,
Path dstFolder) throws IOException {
String factorySimpleName, packageName;
int i = factoryFqn.lastIndexOf('.');
if (i < 0) {
packageName = "";
factorySimpleName = factoryFqn;
} else {
packageName = factoryFqn.substring(0, i);
factorySimpleName = factoryFqn.substring(i + 1);
}
Path result = dstFolder.resolve(factorySimpleName + ".java");
File dst = result.toFile();
File src = srcTemplate.toFile();
try (BufferedReader r = new BufferedReader(new FileReader(src));
BufferedWriter w = new BufferedWriter(new FileWriter(dst))) {
List<String> lines = processTemplate(packageName, factorySimpleName,
r.lines()).collect(Collectors.toList());
Iterator<String> it = lines.iterator();
if (it.hasNext())
w.write(it.next());
while (it.hasNext()) {
w.newLine();
w.write(it.next());
}
}
return result;
}
private static Stream<String> processTemplate(String packageName,
String factorySimpleName,
Stream<String> lines) {
Function<String, String> pckg;
if (packageName.isEmpty()) {
pckg = s -> s.contains("$package") ? "" : s;
} else {
pckg = s -> s.replaceAll("\\$package", packageName);
}
Function<String, String> factory
= s -> s.replaceAll("\\$className", factorySimpleName);
return lines.map(pckg).map(factory);
}
// IMO, that's the easiest way that gives you a fair amount of confidence in
// that j.u.ServiceLoader is loading a factory rather than Class.forName
private static boolean verifyOutput(String output, String fqn) {
String s1 = String.format("java.util.ServiceConfigurationError: " +
"java.net.ContentHandlerFactory: " +
"Provider %s could not be instantiated", fqn);
return output.contains(s1);
}
private static void jar(Path jarName, Path jarRoot) {
String jar = getJDKTool("jar");
ProcessBuilder p = new ProcessBuilder(jar, "cf", jarName.toString(),
"-C", jarRoot.toString(), ".");
quickFail(run(p));
}
private static void javac(Path compilationOutput, Path... sourceFiles) {
String javac = getJDKTool("javac");
List<String> commands = new ArrayList<>();
commands.addAll(asList(javac, "-d", compilationOutput.toString()));
List<Path> paths = asList(sourceFiles);
commands.addAll(paths.stream()
.map(Path::toString)
.collect(Collectors.toList()));
quickFail(run(new ProcessBuilder(commands)));
}
private static void quickFail(Result r) {
if (r.exitValue != 0)
throw new RuntimeException(r.output);
}
private static Result java(Map<String, String> properties,
Collection<Path> classpath,
String classname, String... args) {
List<String> commands = properties.entrySet()
.stream()
.map(e -> "-D" + e.getKey() + "=" + e.getValue())
.collect(Collectors.toList());
String cp = classpath.stream()
.map(Path::toString)
.collect(Collectors.joining(File.pathSeparator));
commands.add("-cp");
commands.add(cp);
commands.add(classname);
commands.addAll(Arrays.asList(args));
return run(ProcessTools.createTestJavaProcessBuilder(commands));
}
private static Result run(ProcessBuilder b) {
Process p;
try {
p = b.start();
} catch (IOException e) {
throw new RuntimeException(
format("Couldn't start process '%s'", b.command()), e);
}
String output;
try {
output = toString(p.getInputStream(), p.getErrorStream());
} catch (IOException e) {
throw new RuntimeException(
format("Couldn't read process output '%s'", b.command()), e);
}
try {
p.waitFor();
} catch (InterruptedException e) {
throw new RuntimeException(
format("Process hasn't finished '%s'", b.command()), e);
}
return new Result(p.exitValue(), output);
}
private static String getJDKTool(String name) {
String testJdk = System.getProperty("test.jdk");
if (testJdk == null)
throw new RuntimeException("Please provide test.jdk property at a startup");
return testJdk + File.separator + "bin" + File.separator + name;
}
private static Path templatesHome() {
String testSrc = System.getProperty("test.src");
if (testSrc == null)
throw new RuntimeException("Please provide test.src property at a startup");
return Paths.get(testSrc);
}
private static String toString(InputStream... src) throws IOException {
StringWriter dst = new StringWriter();
Reader concatenated =
new InputStreamReader(
new SequenceInputStream(
Collections.enumeration(asList(src))));
copy(concatenated, dst);
return dst.toString();
}
private static void copy(Reader src, Writer dst) throws IOException {
int len;
char[] buf = new char[1024];
try {
while ((len = src.read(buf)) != -1)
dst.write(buf, 0, len);
} finally {
try {
src.close();
} catch (IOException ignored1) {
} finally {
try {
dst.close();
} catch (IOException ignored2) {
}
}
}
}
private static class Result {
final int exitValue;
final String output;
private Result(int exitValue, String output) {
this.exitValue = exitValue;
this.output = output;
}
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2015, 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.
*/
package $package;
import java.net.ContentHandler;
import java.net.ContentHandlerFactory;
public class $className implements ContentHandlerFactory {
public $className() {
throw new RuntimeException(
"This is a broken factory. It is supposed to throw this exception.");
}
@Override
public ContentHandler createContentHandler(String mimetype) {
throw new RuntimeException( "This method is not supposed to be called.");
}
}

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2015, 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.
*/
package $package;
import java.net.ContentHandler;
import java.net.ContentHandlerFactory;
public class $className implements ContentHandlerFactory {
@Override
public ContentHandler createContentHandler(String mimetype) {
throw new RuntimeException(
"This is a broken factory. It is supposed to throw this exception.");
}
}

View file

@ -0,0 +1,35 @@
/*
* Copyright (c) 2015, 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.
*/
package $package;
import java.io.IOException;
import java.net.ContentHandler;
import java.net.URLConnection;
public final class $className extends ContentHandler {
@Override
public Object getContent(URLConnection urlc) throws IOException {
return this;
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2015, 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.ByteArrayInputStream;
import java.io.InputStream;
import java.net.ContentHandlerFactory;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
public class Test {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
String fqn = args[0];
@SuppressWarnings("unchecked")
Class<? extends ContentHandlerFactory> c =
(Class<? extends ContentHandlerFactory>) Class.forName(fqn);
ContentHandlerFactory f = c.newInstance();
URLConnection.setContentHandlerFactory(f);
}
// One does not simply use a ContentHandler...
// From an end user perspective ContentHandler is used indirectly
// and it's more like SPI rather than API. So there's a certain amount
// of preparations needs to be done beforehand.
URLStreamHandlerFactory streamHandlerFactory =
(protocol) ->
new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) {
return newUrlConnection(u);
}
};
URL.setURLStreamHandlerFactory(streamHandlerFactory);
// Finally
Object content = new URL("whatever:").getContent();
System.out.println("Content class is: " + content.getClass());
}
private static URLConnection newUrlConnection(URL u) {
return new URLConnection(u) {
@Override public void connect() { }
@Override
public InputStream getInputStream() { return null; }
@Override public String getContentType() { return "text/plain"; }
};
}
}

View file

@ -0,0 +1,307 @@
/*
* Copyright (c) 2002, 2019, 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.
*/
/**
* @test
* @bug 4774503
* @library /test/lib
* @summary Calling HttpURLConnection's disconnect method after the
* response has been received causes havoc with persistent
* connections.
*/
import java.net.*;
import java.io.*;
import java.util.*;
import jdk.test.lib.net.URIBuilder;
import static java.net.Proxy.NO_PROXY;
public class DisconnectAfterEOF {
/*
* Worker thread to service single connection - can service
* multiple http requests on same connection.
*/
static class Worker extends Thread {
Socket s;
Worker(Socket s) {
this.s = s;
}
public void run() {
try {
InputStream in = s.getInputStream();
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
byte b[] = new byte[1024];
int n = -1;
int cl = -1;
int remaining = -1;
StringBuffer sb = new StringBuffer();
boolean close = false;
boolean inBody = false;
for (;;) {
boolean sendResponse = false;
try {
n = in.read(b);
} catch (IOException ioe) {
n = -1;
}
if (n <= 0) {
if (inBody) {
System.err.println("ERROR: Client closed before " +
"entire request received.");
}
return;
}
// reading entity-body
if (inBody) {
if (n > remaining) {
System.err.println("Receiving more than expected!!!");
return;
}
remaining -= n;
if (remaining == 0) {
sendResponse = true;
n = 0;
} else {
continue;
}
}
// reading headers
for (int i=0; i<n; i++) {
char c = (char)b[i];
if (c != '\n') {
sb.append(c);
continue;
}
// Got end-of-line
int len = sb.length();
if (len > 0) {
if (sb.charAt(len-1) != '\r') {
System.err.println("Unexpected CR in header!!");
return;
}
}
sb.setLength(len-1);
// empty line
if (sb.length() == 0) {
if (cl < 0) {
System.err.println("Content-Length not found!!!");
return;
}
// the surplus is body data
int dataRead = n - (i+1);
remaining = cl - dataRead;
if (remaining > 0) {
inBody = true;
break;
} else {
// entire body has been read
sendResponse = true;
}
} else {
// non-empty line - check for Content-Length
String line = sb.toString().toLowerCase();
if (line.startsWith("content-length")) {
StringTokenizer st = new StringTokenizer(line, ":");
st.nextToken();
cl = Integer.parseInt(st.nextToken().trim());
}
if (line.startsWith("connection")) {
StringTokenizer st = new StringTokenizer(line, ":");
st.nextToken();
if (st.nextToken().trim().equals("close")) {
close =true;
}
}
}
sb = new StringBuffer();
}
if (sendResponse) {
// send a large response
int rspLen = 32000;
out.print("HTTP/1.1 200 OK\r\n");
out.print("Content-Length: " + rspLen + "\r\n");
out.print("\r\n");
if (rspLen > 0)
out.write(new byte[rspLen]);
out.flush();
if (close)
return;
sendResponse = false;
inBody = false;
cl = -1;
}
}
} catch (IOException ioe) {
} finally {
try {
s.close();
} catch (Exception e) { }
System.out.println("+ Worker thread shutdown.");
}
}
}
/*
* Server thread to accept connection and create worker threads
* to service each connection.
*/
static class Server extends Thread {
ServerSocket ss;
Server(ServerSocket ss) {
this.ss = ss;
}
public void run() {
try {
for (;;) {
Socket s = ss.accept();
Worker w = new Worker(s);
w.start();
}
} catch (IOException ioe) {
}
System.out.println("+ Server shutdown.");
}
public void shutdown() {
try {
ss.close();
} catch (IOException ioe) { }
}
}
static URLConnection doRequest(String uri) throws IOException {
URLConnection uc = (new URL(uri)).openConnection(NO_PROXY);
uc.setDoOutput(true);
OutputStream out = uc.getOutputStream();
out.write(new byte[16000]);
// force the request to be sent
uc.getInputStream();
return uc;
}
static URLConnection doResponse(URLConnection uc) throws IOException {
int cl = ((HttpURLConnection)uc).getContentLength();
byte b[] = new byte[4096];
int n;
do {
n = uc.getInputStream().read(b);
if (n > 0) cl -= n;
} while (n > 0);
if (cl != 0) {
throw new RuntimeException("ERROR: content-length mismatch");
}
return uc;
}
public static void main(String args[]) throws Exception {
// start server
InetAddress loopback = InetAddress.getLoopbackAddress();
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(loopback, 0));
Server svr = new Server(ss);
svr.start();
String uri = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.path("/foo.html")
.build().toString();
/*
* The following is the test scenario we create here :-
*
* 1. We do a http request/response and read the response
* to EOF. As it's a persistent connection the idle
* connection should go into the keep-alive cache for a
* few seconds.
*
* 2. We start a second request but don't read the response.
* As the request is to the same server we can assume it
* (for our implementation anyway) that it will use the
* same TCP connection.
*
* 3. We "disconnect" the first HttpURLConnection. This
* should be no-op because the connection is in use
* but another request. However with 1.3.1 and 1.4/1.4.1
* this causes the TCP connection for the second request
* to be closed.
*
*/
URLConnection uc1 = doRequest(uri);
doResponse(uc1);
Thread.sleep(2000);
URLConnection uc2 = doRequest(uri);
((HttpURLConnection)uc1).disconnect();
IOException ioe = null;
try {
doResponse(uc2);
} catch (IOException x) {
ioe = x;
}
((HttpURLConnection)uc2).disconnect();
/*
* Shutdown server as we are done. Worker threads created
* by the server will shutdown automatically when the
* client connection closes.
*/
svr.shutdown();
if (ioe != null) {
throw ioe;
}
}
}

View file

@ -0,0 +1,66 @@
/*
* 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.
*/
/*
* @test
* @bug 4639576
* @summary java.net.URLConnection.guessContentTypeFromStream cannot
* handle Exif format
*/
import java.net.URLConnection;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
/**
* This test makes sure that URLConnection.guessContentTypeFromStream
* recognizes Exif file format. This test uses the file:
* olympus.jpg for testing the same.
*/
public class ExifContentGuesser {
public static void main(String args[]) throws Exception {
String filename = System.getProperty("test.src", ".") +
"/" + "olympus.jpg";
System.out.println("filename: " + filename);
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(filename));
String content_type = URLConnection.guessContentTypeFromStream(in);
if (content_type == null) {
throw new Exception("Test failed: Could not recognise " +
"Exif image");
} else {
System.out.println("content-type: " + content_type);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 1998, 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.
*/
/* @test
* @bug 4112524
* @summary check for correct implementation of getContentType for JAR urls.
*/
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
public class GetContentType {
static final String JAR_MIME_TYPE = "x-java/jar";
static final String GIF_MIME_TYPE = "image/gif";
public static void main(String[] args) throws Exception {
/* test JAR URLs -- NOTE: we musn't connect! */
URL url = new URL(getSpec());
URLConnection connection = url.openConnection();
String contentType = connection.getContentType();
System.out.println(url + " jar content type: " + contentType);
if (!contentType.equals(JAR_MIME_TYPE)) {
throw new RuntimeException("invalid MIME type for JAR archive");
}
url = new URL(url, "image.gif");
connection = url.openConnection();
contentType = connection.getContentType();
System.out.println(url + " img content type: " + contentType);
if (!contentType.equals(GIF_MIME_TYPE)) {
throw new RuntimeException("invalid MIME type for JAR entry");
}
}
static String getSpec() throws IOException {
File file = new File(".");
return "jar:file:" + file.getCanonicalPath() +
File.separator + "jars" + File.separator + "test.jar!/";
}
}

View file

@ -0,0 +1,38 @@
/*
* Copyright (c) 1999, 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.
*/
/*
* @test
* @bug 4075040
* @summary Make sure the Mimetable is initialized
* at first use.
*/
import java.net.*;
public class GetFileNameMap {
public static void main(String[] args) throws Exception {
FileNameMap map = URLConnection.getFileNameMap();
String s = map.getContentTypeFor("test.pdf");
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2001, 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.
*/
/*
* @test
* @bug 4109476
* @summary Test that URLConnection.getLastModified returns the last
* modified date on files and jar files.
*/
import java.net.URL;
import java.net.URLConnection;
import java.io.File;
public class GetLastModified {
static boolean testFailed = false;
static void test(String s) throws Exception {
URL url = new URL(s);
URLConnection conn = url.openConnection();
if (conn.getLastModified() == 0) {
System.out.println("Failed: getLastModified returned 0 for URL: " + s);
testFailed = true;
}
}
public static void main(String args[]) throws Exception {
File file = new File(System.getProperty("test.src", "."), "jars");
String fileURL = "file:" + file.getCanonicalPath() + file.separator +
"test.jar";
test(fileURL);
String jarURL = "jar:" + fileURL + "!/";
test(jarURL);
if (testFailed) {
throw new Exception("Test failed - getLastModified returned 0");
}
}
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/**
* @test
* @bug 4191815
* @library /test/lib
* @summary Check that getResponseCode doesn't throw exception if http
* respone code is >= 400.
*/
import java.net.*;
import java.io.*;
import jdk.test.lib.net.URIBuilder;
public class GetResponseCode implements Runnable {
ServerSocket ss;
/*
* Our "http" server to return a 404
*/
public void run() {
try {
Socket s = ss.accept();
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
/* send the header */
out.print("HTTP/1.1 404 Not Found\r\n");
out.print("Content-Type: text/html; charset=iso-8859-1\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.print("<HTML>");
out.print("<HEAD><TITLE>404 Not Found</TITLE></HEAD>");
out.print("<BODY>The requested URL was not found.</BODY>");
out.print("</HTML>");
out.flush();
/*
* Sleep added to avoid connection reset
* on the client side
*/
Thread.sleep(1000);
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
GetResponseCode() throws Exception {
/* start the server */
ss = new ServerSocket();
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
(new Thread(this)).start();
/* establish http connection to server */
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.path("/missing.nohtml")
.toURL();
HttpURLConnection http = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
int respCode = http.getResponseCode();
http.disconnect();
}
public static void main(String args[]) throws Exception {
new GetResponseCode();
}
}

View file

@ -0,0 +1,142 @@
/*
* Copyright (c) 1999, 2011, 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.
*/
/*
* @test
* @bug 4160195 7026346
* @summary Check for correct detection of XML content type, including BOM streams
*/
import java.io.*;
import java.net.*;
public class GetXmlContentType {
static final String XML_MIME_TYPE = "application/xml";
static final String XML_HEADER = "<?xml";
static int passed, failed;
// guess type from content and filename
static final String goodFiles [] = {
"xml1", // US-ASCII and supersets
"xml2.xml", // typed inferred from filename
"xml3", // UTF-16 little endian (partial)
"xml4" // UTF-16 big endian (partial)
};
// some common non-XML examples
static final String badFiles [] = {
"not-xml1",
"not-xml2"
};
public static void main(String[] args) throws Exception {
contentTypeFromFile();
contentTypeFromBOMStream();
if (failed > 0)
throw new RuntimeException (
"Test failed; passed = " + passed + ", failed = " + failed);
}
static void contentTypeFromFile() throws Exception {
// POSITIVE tests: good data --> good result
for (String goodFile : goodFiles) {
String result = getUrlContentType(goodFile);
if (!XML_MIME_TYPE.equals(result)) {
System.out.println("Wrong MIME type: " + goodFile + " --> " + result);
failed++;
} else {
passed++;
}
}
// NEGATIVE tests: bad data --> correct diagnostic
for (String badFile : badFiles) {
String result = getUrlContentType(badFile);
if (XML_MIME_TYPE.equals(result)) {
System.out.println("Wrong MIME type: " + badFile + " --> " + result);
failed++;
} else {
passed++;
}
}
}
static String getUrlContentType(String name) throws IOException {
File file = new File(System.getProperty("test.src", "."), "xml");
URL u = new URL("file:"
+ file.getCanonicalPath()
+ file.separator
+ name);
URLConnection conn = u.openConnection();
return conn.getContentType();
}
static void contentTypeFromBOMStream() throws Exception {
final String[] encodings = new String[]
{"UTF-8", "UTF-16BE", "UTF-16LE", "UTF-32BE", "UTF-32LE"};
for (String encoding : encodings) {
try (InputStream is = new ByteArrayInputStream(toBOMBytes(encoding))) {
String mime = URLConnection.guessContentTypeFromStream(is);
if ( !XML_MIME_TYPE.equals(mime) ) {
System.out.println("Wrong MIME type: " + encoding + " --> " + mime);
failed++;
} else {
passed++;
}
}
}
}
static byte[] toBOMBytes(String encoding) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
switch (encoding) {
case "UTF-8" :
bos.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
break;
case "UTF-16BE" :
bos.write(new byte[] { (byte) 0xFE, (byte) 0xFF });
break;
case "UTF-16LE" :
bos.write(new byte[] { (byte) 0xFF, (byte) 0xFE });
break;
case "UTF-32BE" :
bos.write(new byte[] { (byte) 0x00, (byte) 0x00,
(byte) 0xFE, (byte) 0xFF });
break;
case "UTF-32LE" :
bos.write(new byte[] { (byte) 0xFF, (byte) 0xFE,
(byte) 0x00, (byte) 0x00 });
}
bos.write(XML_HEADER.getBytes(encoding));
return bos.toByteArray();
}
}

View file

@ -0,0 +1,250 @@
/*
* Copyright (c) 1998, 2019, 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.
*/
/*
* @test
* @bug 4160200
* @summary Make sure URLConnection.getContentHandler
* can handle MIME types with attributes
* @library /test/lib
* @modules java.base/sun.net.www java.base/sun.net.www.content.text
*/
import java.net.*;
import java.io.*;
import sun.net.www.content.text.*;
import sun.net.www.MessageHeader;
import static java.net.Proxy.NO_PROXY;
import jdk.test.lib.net.URIBuilder;
public class HandleContentTypeWithAttrs {
URL url;
public HandleContentTypeWithAttrs (int port) throws Exception {
// Request echo.html from myHttpServer.
// In the header of the response, we make
// the content type have some attributes.
url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.path("/echo.html")
.toURL();
URLConnection urlConn = url.openConnection(NO_PROXY);
// the method getContent() calls the method
// getContentHandler(). With the fix, the method
// getContentHandler() gets the correct content
// handler for our response - it should be the
// PlainText conten handler; without the fix,
// it gets the UnknownContent handler.
// So based on what the getContent()
// returns, we know whether getContentHandler()
// can handle content type with attributes or not.
Object obj = urlConn.getContent();
if (!(obj instanceof PlainTextInputStream))
throw new Exception("Cannot get the correct content handler.");
}
public static void main(String [] argv) throws Exception {
// Start myHttpServer
myHttpServer testServer = new myHttpServer();
testServer.startServer(0);
int serverPort = testServer.getServerLocalPort();
new HandleContentTypeWithAttrs(serverPort);
}
}
// myHttpServer is pretty much like
// sun.net.www.httpd.BasicHttpServer.
// But we only need it to handle one
// simple request.
class myHttpServer implements Runnable, Cloneable {
/** Socket for communicating with client. */
public Socket clientSocket = null;
private Thread serverInstance;
private ServerSocket serverSocket;
/** Stream for printing to the client. */
public PrintStream clientOutput;
/** Buffered stream for reading replies from client. */
public InputStream clientInput;
static URL defaultContext;
/** Close an open connection to the client. */
public void close() throws IOException {
clientSocket.close();
clientSocket = null;
clientInput = null;
clientOutput = null;
}
final public void run() {
if (serverSocket != null) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try {
// wait for incoming request
Socket ns = serverSocket.accept();
myHttpServer n = (myHttpServer)clone();
n.serverSocket = null;
n.clientSocket = ns;
new Thread(n).start();
} catch(Exception e) {
System.out.print("Server failure\n");
e.printStackTrace();
} finally {
try { serverSocket.close(); } catch(IOException unused) {}
}
} else {
try {
clientOutput = new PrintStream(
new BufferedOutputStream(clientSocket.getOutputStream()),
false);
clientInput = new BufferedInputStream(
clientSocket.getInputStream());
serviceRequest();
} catch(Exception e) {
// System.out.print("Service handler failure\n");
// e.printStackTrace();
} finally {
try { close(); } catch(IOException unused) {}
}
}
}
/** Start a server on port <i>port</i>. It will call serviceRequest()
for each new connection. */
final public void startServer(int port) throws IOException {
serverSocket = new ServerSocket(port, 50,
InetAddress.getLoopbackAddress());
serverInstance = new Thread(this);
serverInstance.start();
}
final public int getServerLocalPort() throws Exception {
if (serverSocket != null) {
return serverSocket.getLocalPort();
}
throw new Exception("serverSocket is null");
}
MessageHeader mh;
final public void serviceRequest() {
//totalConnections++;
try {
mh = new MessageHeader(clientInput);
String cmd = mh.findValue(null);
// if (cmd == null) {
// error("Missing command " + mh);
// return;
// }
int fsp = cmd.indexOf(' ');
// if (fsp < 0) {
// error("Syntax error in command: " + cmd);
// return;
// }
String k = cmd.substring(0, fsp);
int nsp = cmd.indexOf(' ', fsp + 1);
String p1, p2;
if (nsp > 0) {
p1 = cmd.substring(fsp + 1, nsp);
p2 = cmd.substring(nsp + 1);
} else {
p1 = cmd.substring(fsp + 1);
p2 = null;
}
// expectsMime = p2 != null;
if (k.equalsIgnoreCase("get"))
getRequest(new URL(defaultContext, p1), p2);
else {
// error("Unknown command: " + k + " (" + cmd + ")");
return;
}
} catch(IOException e) {
// totally ignore IOException. They're usually client crashes.
} catch(Exception e) {
// error("Exception: " + e);
e.printStackTrace();
}
}
/** Satisfy one get request. It is invoked with the clientInput and
clientOutput streams initialized. This method handles one client
connection. When it is done, it can simply exit. The default
server just echoes it's input. */
protected void getRequest(URL u, String param) {
try {
if (u.getFile().equals("/echo.html")) {
startHtml("Echo reply");
clientOutput.print("<p>URL was " + u.toExternalForm() + "\n");
clientOutput.print("<p>Socket was " + clientSocket + "\n<p><pre>");
mh.print(clientOutput);
}
} catch(Exception e) {
System.out.print("Failed on "+u.getFile()+"\n");
e.printStackTrace();
}
}
/**
* Clone this object;
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
public myHttpServer () {
try {
defaultContext = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.path("/")
.toURL();
} catch(Exception e) {
System.out.println("Failed to construct default URL context: "
+ e);
e.printStackTrace();
}
}
// Make the content type have some attributes
protected void startHtml(String title) {
clientOutput.print("HTTP/1.0 200 Document follows\n" +
"Server: Java/" + getClass().getName() + "\n" +
"Content-type: text/plain; charset=Shift_JIS \n\n");
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright (c) 2000, 2019, 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.
*/
/* @test
* @bug 4258697
* @library /test/lib
* @summary Make sure that http CONTINUE status followed by invalid
* response doesn't cause HttpClient to recursively loop and
* eventually StackOverflow.
*
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.HttpURLConnection;
import jdk.test.lib.net.URIBuilder;
import static java.net.Proxy.NO_PROXY;
public class HttpContinueStackOverflow {
static class Server implements Runnable {
ServerSocket serverSock ;
Server() throws IOException {
serverSock = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
}
int getLocalPort() {
return serverSock.getLocalPort();
}
public void run() {
Socket sock = null;
try {
serverSock.setSoTimeout(10000);
sock = serverSock.accept();
/* setup streams and read http request */
BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
PrintStream out = new PrintStream( sock.getOutputStream() );
in.readLine();
/* send continue followed by invalid response */
out.println("HTTP/1.1 100 Continue\r");
out.println("\r");
out.println("junk junk junk");
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { serverSock.close(); } catch (IOException unused) {}
try { sock.close(); } catch (IOException unused) {}
}
}
}
HttpContinueStackOverflow() throws Exception {
/* create the server */
Server s = new Server();
(new Thread(s)).start();
/* connect to server and get response code */
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(s.getLocalPort())
.path("/anything.html")
.toURL();
HttpURLConnection conn = (HttpURLConnection)url.openConnection(NO_PROXY);
conn.getResponseCode();
System.out.println("TEST PASSED");
}
public static void main(String args[]) throws Exception {
System.out.println("Testing 100-Continue");
new HttpContinueStackOverflow();
}
}

View file

@ -0,0 +1,127 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/**
* @test
* @bug 4380568 7095949
* @library /test/lib
* @summary HttpURLConnection does not support 307 redirects
*/
import java.io.*;
import java.net.*;
import jdk.test.lib.net.URIBuilder;
import static java.net.Proxy.NO_PROXY;
class RedirServer extends Thread {
static final int TIMEOUT = 10 * 1000;
ServerSocket ss;
int port;
String reply1Part1 = "HTTP/1.1 307 Temporary Redirect\r\n" +
"Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
"Server: Apache/1.3.14 (Unix)\r\n" +
"Location: http://localhost:";
String reply1Part2 = "/redirected.html\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
"<html>Hello</html>";
RedirServer (ServerSocket ss) throws IOException {
this.ss = ss;
this.ss.setSoTimeout(TIMEOUT);
port = this.ss.getLocalPort();
}
String reply2 = "HTTP/1.1 200 Ok\r\n" +
"Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
"Server: Apache/1.3.14 (Unix)\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
"World";
static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' };
// Read until the end of a HTTP request
void readOneRequest(InputStream is) throws IOException {
int requestEndCount = 0, r;
while ((r = is.read()) != -1) {
if (r == requestEnd[requestEndCount]) {
requestEndCount++;
if (requestEndCount == 4) {
break;
}
} else {
requestEndCount = 0;
}
}
}
public void run () {
try {
try (Socket s = ss.accept()) {
s.setSoTimeout(TIMEOUT);
readOneRequest(s.getInputStream());
String reply = reply1Part1 + port + reply1Part2;
s.getOutputStream().write(reply.getBytes());
}
/* wait for redirected connection */
try (Socket s = ss.accept()) {
s.setSoTimeout(TIMEOUT);
readOneRequest(s.getInputStream());
s.getOutputStream().write(reply2.getBytes());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { ss.close(); } catch (IOException unused) {}
}
}
};
public class Redirect307Test {
public static void main(String[] args) throws Exception {
ServerSocket sock = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
int port = sock.getLocalPort();
RedirServer server = new RedirServer(sock);
server.start();
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.toURL();
URLConnection conURL = url.openConnection(NO_PROXY);
conURL.setDoInput(true);
conURL.setAllowUserInteraction(false);
conURL.setUseCaches(false);
try (InputStream in = conURL.getInputStream()) {
if ((in.read() != (int)'W') || (in.read()!=(int)'o')) {
throw new RuntimeException ("Unexpected string read");
}
}
}
}

View file

@ -0,0 +1,142 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/**
* @test
* @bug 4458085 7095949
* @library /test/lib
* @summary Redirects Limited to 5
*/
/*
* Simulate a server that redirects ( to a different URL) 9 times
* and see if the client correctly follows the trail
*/
import java.io.*;
import java.net.*;
import java.util.concurrent.CountDownLatch;
import jdk.test.lib.net.URIBuilder;
class RedirLimitServer extends Thread {
static final int TIMEOUT = 20 * 1000;
static final int NUM_REDIRECTS = 9;
static final String reply1 = "HTTP/1.1 307 Temporary Redirect\r\n" +
"Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
"Server: Apache/1.3.14 (Unix)\r\n" +
"Location: http://localhost:";
static final String reply2 = ".html\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
"<html>Hello</html>";
static final String reply3 = "HTTP/1.1 200 Ok\r\n" +
"Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
"Server: Apache/1.3.14 (Unix)\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
"World";
final ServerSocket ss;
final int port;
final CountDownLatch readyToStart = new CountDownLatch(1);
RedirLimitServer(ServerSocket ss) throws IOException {
this.ss = ss;
port = this.ss.getLocalPort();
this.ss.setSoTimeout(TIMEOUT);
}
static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' };
// Read until the end of a HTTP request
void readOneRequest(InputStream is) throws IOException {
int requestEndCount = 0, r;
StringBuilder sb = new StringBuilder();
while ((r = is.read()) != -1) {
sb.append((char)r);
if (r == requestEnd[requestEndCount]) {
requestEndCount++;
if (requestEndCount == 4) {
break;
}
} else {
requestEndCount = 0;
}
}
System.out.println("Server got request: " + sb.toString());
}
public void run() {
try {
readyToStart.countDown();
for (int i=0; i<NUM_REDIRECTS; i++) {
try (Socket s = ss.accept()) {
System.out.println("Server accepted socket: " + s);
s.setSoTimeout(TIMEOUT);
readOneRequest(s.getInputStream());
System.out.println("Redirecting to: /redirect" + i);
String reply = reply1 + port + "/redirect" + i + reply2;
s.getOutputStream().write(reply.getBytes());
}
}
try (Socket s = ss.accept()) {
System.out.println("Server accepted socket: " + s);
s.setSoTimeout(TIMEOUT);
readOneRequest(s.getInputStream());
System.out.println("Replying...");
s.getOutputStream().write(reply3.getBytes());
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
public class RedirectLimit {
public static void main(String[] args) throws Exception {
try (ServerSocket ss = new ServerSocket(0, 0, InetAddress.getLoopbackAddress())) {
int port = ss.getLocalPort();
RedirLimitServer server = new RedirLimitServer(ss);
server.start();
server.readyToStart.await();
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.toURL();
URLConnection conURL = url.openConnection(Proxy.NO_PROXY);
conURL.setDoInput(true);
conURL.setAllowUserInteraction(false);
conURL.setUseCaches(false);
try (InputStream in = conURL.getInputStream()) {
if ((in.read() != (int) 'W') || (in.read() != (int) 'o')) {
throw new RuntimeException("Unexpected string read");
}
}
}
}
}

View file

@ -0,0 +1,180 @@
/*
* Copyright (c) 2001, 2020, 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.
*/
/**
* @test
* @bug 4485208 8252767
* @summary Validate various request property methods on java.net.URLConnection
* throw NullPointerException and IllegalStateException when expected
* @run testng RequestProperties
*/
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class RequestProperties {
private static final Class NPE = NullPointerException.class;
private static final Class ISE = IllegalStateException.class;
@DataProvider(name = "urls")
private Object[][] urls() {
final List<String> urls = new ArrayList<>();
urls.add("http://foo.com/bar/");
urls.add("jar:http://foo.com/bar.html!/foo/bar");
urls.add("file:/etc/passwd");
if (hasFtp()) {
urls.add("ftp://foo:bar@foobar.com/etc/passwd");
}
final Object[][] data = new Object[urls.size()][1];
for (int i = 0; i < urls.size(); i++) {
data[i][0] = urls.get(i);
}
return data;
}
/**
* Test that {@link java.net.URLConnection#setRequestProperty(String, String)} throws
* a {@link NullPointerException} when passed null key
*/
@Test(dataProvider = "urls")
public void testSetRequestPropertyNullPointerException(final String url) throws Exception {
final URLConnection conn = new URL(url).openConnection();
Assert.assertThrows(NPE, () -> conn.setRequestProperty(null, "bar"));
// expected to pass
conn.setRequestProperty("key", null);
}
/**
* Test that {@link java.net.URLConnection#addRequestProperty(String, String)} throws
* a {@link NullPointerException} when passed null key
*/
@Test(dataProvider = "urls")
public void testAddRequestPropertyNullPointerException(final String url) throws Exception {
final URLConnection conn = new URL(url).openConnection();
Assert.assertThrows(NPE, () -> conn.addRequestProperty(null, "hello"));
// expected to pass
conn.addRequestProperty("key", null);
}
/**
* Test that {@link java.net.URLConnection#getRequestProperty(String)} returns
* null when the passed key is null
*/
@Test(dataProvider = "urls")
public void testGetRequestPropertyReturnsNull(final String url) throws Exception {
final URLConnection conn = new URL(url).openConnection();
Assert.assertNull(conn.getRequestProperty(null),
"getRequestProperty was expected to return null for null key");
}
/**
* Test that {@link java.net.URLConnection#setRequestProperty(String, String)} throws
* an {@link IllegalStateException} when already connected
*/
@Test
public void testSetRequestPropertyIllegalStateException() throws Exception {
final URLConnection conn = createAndConnectURLConnection();
try {
Assert.assertThrows(ISE, () -> conn.setRequestProperty("foo", "bar"));
} finally {
safeClose(conn);
}
}
/**
* Test that {@link java.net.URLConnection#addRequestProperty(String, String)} throws
* an {@link IllegalStateException} when already connected
*/
@Test
public void testAddRequestPropertyIllegalStateException() throws Exception {
final URLConnection conn = createAndConnectURLConnection();
try {
Assert.assertThrows(ISE, () -> conn.addRequestProperty("foo", "bar"));
} finally {
safeClose(conn);
}
}
/**
* Test that {@link java.net.URLConnection#getRequestProperty(String)} throws
* an {@link IllegalStateException} when already connected
*/
@Test
public void testGetRequestPropertyIllegalStateException() throws Exception {
final URLConnection conn = createAndConnectURLConnection();
try {
Assert.assertThrows(ISE, () -> conn.getRequestProperty("hello"));
} finally {
safeClose(conn);
}
}
/**
* Test that {@link URLConnection#getRequestProperties()} throws
* an {@link IllegalStateException} when already connected
*/
@Test
public void testGetRequestPropertiesIllegalStateException() throws Exception {
final URLConnection conn = createAndConnectURLConnection();
try {
Assert.assertThrows(ISE, () -> conn.getRequestProperties());
} finally {
safeClose(conn);
}
}
private static URLConnection createAndConnectURLConnection() throws IOException {
final URL url = Path.of(System.getProperty("java.io.tmpdir")).toUri().toURL();
final URLConnection conn = url.openConnection();
conn.connect();
return conn;
}
private static void safeClose(final URLConnection conn) {
try {
conn.getInputStream().close();
} catch (Exception e) {
// ignore
}
}
private static boolean hasFtp() {
try {
new java.net.URL("ftp://");
return true;
} catch (java.net.MalformedURLException x) {
System.out.println("FTP not supported by this runtime.");
return false;
}
}
}

View file

@ -0,0 +1,162 @@
/*
* Copyright (c) 2002, 2021, 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.
*/
/*
* @test
* @bug 4644775 6230836 8133686
* @summary Test URLConnection Request Properties
* @run main RequestPropertyValues
*/
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
/**
* Part1:
* bug 4644775: Unexpected NPE in setRequestProperty(key, null) call
* Part2:
* bug 6230836: A few methods of class URLConnection implemented incorrectly
* Part3:
* bug 8133686: Preserving the insertion-order of getRequestProperties
*/
public class RequestPropertyValues {
public static void main(String[] args) throws Exception {
part1();
part2();
part3();
}
public static void part1() throws Exception {
List<URL> urls = new ArrayList<>();
urls.add(new URL("http://localhost:8088"));
urls.add(new URL("file:/etc/passwd"));
urls.add(new URL("jar:http://foo.com/bar.html!/foo/bar"));
if (hasFtp())
urls.add(new URL("ftp://foo:bar@foobar.com/etc/passwd"));
boolean failed = false;
for (URL url : urls) {
URLConnection uc = url.openConnection();
try {
uc.setRequestProperty("TestHeader", null);
} catch (NullPointerException npe) {
System.out.println("setRequestProperty is throwing NPE" +
" for url: " + url);
failed = true;
}
try {
uc.addRequestProperty("TestHeader", null);
} catch (NullPointerException npe) {
System.out.println("addRequestProperty is throwing NPE" +
" for url: " + url);
failed = true;
}
}
if (failed) {
throw new Exception("RequestProperty setting/adding is" +
" throwing NPE for null values");
}
}
public static void part2() throws Exception {
URL url = null;
String[] goodKeys = {"", "$", "key", "Key", " ", " "};
String[] goodValues = {"", "$", "value", "Value", " ", " "};
URLConnection conn = getConnection(url);
for (int i = 0; i < goodKeys.length; ++i) {
for (int j = 0; j < goodValues.length; ++j) {
// If a property with the key already exists, overwrite its value with the new value
conn.setRequestProperty(goodKeys[i], goodValues[j]);
String value = conn.getRequestProperty(goodKeys[i]);
if (!((goodValues[j] == null && value == null) || (value != null && value.equals(goodValues[j]))))
throw new RuntimeException("Method setRequestProperty(String,String) works incorrectly");
}
}
}
private static void part3() throws Exception{
List<URL> urls = new ArrayList<>();
urls.add(new URL("http://localhost:8088"));
urls.add(new URL("jar:http://foo.com/bar.html!/foo/bar"));
for(URL url : urls) {
System.out.println("Testing " + url.toString().split(":")[0]);
URLConnection urlConnection = url.openConnection();
addCustomRequestProperties(urlConnection);
testRequestPropertiesOrder(urlConnection);
}
}
private static void addCustomRequestProperties(URLConnection urlConnection) {
urlConnection.addRequestProperty("Testprop", "val1");
urlConnection.addRequestProperty("Testprop", "val2");
urlConnection.addRequestProperty("Testprop", "val3");
}
private static void testRequestPropertiesOrder(URLConnection con) {
List<String> expectedTestRequestProperties = Arrays.asList("val1", "val2", "val3");
Map<String, List<String>> requestProperties = con.getRequestProperties();
List<String> actualTestRequestProperties = requestProperties.get("Testprop");
Objects.requireNonNull(actualTestRequestProperties);
if (!actualTestRequestProperties.equals(expectedTestRequestProperties)) {
System.out.println("expectedTestRequestHeaders = " + expectedTestRequestProperties.toString());
System.out.println("actualTestRequestHeaders = " + actualTestRequestProperties.toString());
String errorMessageTemplate = "expectedTestRequestProperties = %s, actualTestRequestProperties = %s";
throw new RuntimeException("expectedTestRequestProperties != actualTestRequestProperties for URL = " + con.getURL().toString() + String.format(errorMessageTemplate, expectedTestRequestProperties.toString(), actualTestRequestProperties.toString()));
}
}
static URLConnection getConnection(URL url) {
return new DummyURLConnection(url);
}
static class DummyURLConnection extends URLConnection {
DummyURLConnection(URL url) {
super(url);
}
public void connect() {
connected = true;
}
}
private static boolean hasFtp() {
try {
return new java.net.URL("ftp://") != null;
} catch (java.net.MalformedURLException x) {
System.out.println("FTP not supported by this runtime.");
return false;
}
}
}

View file

@ -0,0 +1,189 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/**
* @test
* @bug 4361492
* @summary HTTPUrlConnection does not receive binary data correctly
* @library /test/lib
* @run main/timeout=20 ResendPostBody
*/
import java.io.*;
import java.net.*;
import jdk.test.lib.net.URIBuilder;
/*
* This test does the following:
* 1. client opens HTTP connection to server
* 2. client sends POST with a body containing "ZZZ"
* 3. server waits for POST and closes connection without replying
* 4. client should re-open the connection and re-send the POST
* 5. <bug>The client forgets to re-send the body with the POST
* The server hangs waiting for the body</bug>
*
* <bugfixed>The client sends the body. The server reads it and the
* test terminates normally </bugfixed>
*/
public class ResendPostBody {
static class Server extends Thread {
private InputStream in;
private OutputStream out;
private Socket sock;
private StringBuffer response;
private ServerSocket server;
Server(ServerSocket s) throws IOException {
server = s;
}
void waitFor(String s) throws IOException {
byte[] w = s.getBytes();
for (int c = 0; c < w.length; c++) {
byte expected = w[c];
int b = in.read();
if (b == -1) {
acceptConn();
}
if ((byte) b != expected) {
c = 0;
}
}
}
private boolean done = false;
public synchronized boolean finished() {
return done;
}
public synchronized void setFinished(boolean b) throws IOException {
done = b;
this.closeConn();
server.close();
}
void acceptConn() throws IOException {
sock = server.accept();
in = sock.getInputStream();
out = sock.getOutputStream();
}
void closeConn() throws IOException {
in.close();
out.close();
sock.close();
}
public void run() {
try {
response = new StringBuffer(1024);
acceptConn();
waitFor("POST");
waitFor("ZZZ");
Thread.sleep(500);
sock.close();
acceptConn();
waitFor("POST");
waitFor("ZZZ");
response.append("HTTP/1.1 200 OK\r\n");
response.append("Server: Microsoft-IIS/5.0");
response.append("Date: Wed, 26 Jul 2000 14:17:04 GMT\r\n\r\n");
out.write(response.toString().getBytes());
out.flush();
while (!finished()) {
Thread.sleep(1000);
}
} catch (Exception e) {
if (!done) {
System.err.println("Server Exception: " + e);
}
} finally {
try {
closeConn();
} catch (IOException ioe) {
if (!done) {
ioe.printStackTrace();
}
}
}
}
}
private ServerSocket ss;
private Server server;
public static void main(String[] args) throws Exception {
if (args.length == 1 && args[0].equals("-i")) {
System.out.println("Press return when ready");
System.in.read();
System.out.println("Done");
}
ResendPostBody t = new ResendPostBody();
t.execute();
}
public void execute() throws Exception {
byte b[] = "X=ABCDEFGHZZZ".getBytes();
ss = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
server = new Server(ss);
server.start();
/* Get the URL */
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.path("/test")
.toURL();
HttpURLConnection conURL = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
conURL.setDoOutput(true);
conURL.setDoInput(true);
conURL.setAllowUserInteraction(false);
conURL.setUseCaches(false);
conURL.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conURL.setRequestProperty("Content-Length", "" + b.length);
conURL.setRequestProperty("Connection", "Close");
/* POST some data */
DataOutputStream OutStream = new DataOutputStream(conURL.getOutputStream());
OutStream.write(b, 0, b.length);
OutStream.flush();
OutStream.close();
/* Read the response */
int resp = conURL.getResponseCode();
server.setFinished(true); // Set finished and close ServerSocket
server.join(); // Join server thread
if (resp != 200)
throw new RuntimeException("Response code was not 200: " + resp);
}
}

View file

@ -0,0 +1,193 @@
/*
* Copyright (c) 2002, 2019, 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.
*/
/*
* @test
* @bug 4635698
* @summary Check that HttpURLConnection.getResponseCode returns -1 for
* malformed status-lines in the http response.
*/
import java.net.*;
import java.io.*;
import static java.net.Proxy.NO_PROXY;
public class Responses {
/*
* Test cases :-
* "Response from server" expected getResponse() and
* getResponseMessage() results
*/
static Object[][] getTests() {
return new Object[][] {
{ "HTTP/1.1 200 OK", "200", "OK" },
{ "HTTP/1.1 404 ", "404", null },
{ "HTTP/1.1 200", "200", null },
{ "HTTP/1.1", "-1", null },
{ "Invalid", "-1", null },
{ null, "-1" , null },
};
}
/*
* Simple http server used by test
*
* GET /<n> HTTP/1.x results in http response with the status line
* set to geTests()[<n>][0] -- eg: GET /2 results in a response of
* "HTTP/1.1 404 "
*/
static class HttpServer implements Runnable {
final ServerSocket ss;
volatile boolean shutdown;
public HttpServer() {
try {
InetAddress loopback = InetAddress.getLoopbackAddress();
ss = new ServerSocket();
ss.bind(new InetSocketAddress(loopback, 0));
} catch (IOException ioe) {
throw new Error("Unable to create ServerSocket: " + ioe);
}
}
public int port() {
return ss.getLocalPort();
}
public String authority() {
InetAddress address = ss.getInetAddress();
String hostaddr = address.isAnyLocalAddress()
? "localhost" : address.getHostAddress();
if (hostaddr.indexOf(':') > -1) {
hostaddr = "[" + hostaddr + "]";
}
return hostaddr + ":" + port();
}
public void shutdown() throws IOException {
shutdown = true;
ss.close();
}
public void run() {
Object[][] tests = getTests();
try {
while(!shutdown) {
Socket s = ss.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(
s.getInputStream()));
String req = in.readLine();
int pos1 = req.indexOf(' ');
int pos2 = req.indexOf(' ', pos1+1);
int i = Integer.parseInt(req.substring(pos1+2, pos2));
System.out.println("Server replying to >" + tests[i][0] + "<");
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
out.print( tests[i][0] );
out.print("\r\n");
out.print("Content-Length: 0\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.flush();
s.shutdownOutput();
s.close();
}
} catch (Exception e) {
if (!shutdown) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) throws Exception {
/* start the http server */
HttpServer svr = new HttpServer();
(new Thread(svr)).start();
String authority = svr.authority();
System.out.println("Server listening on: " + authority);
/*
* Iterate through each test case and check that getResponseCode
* returns the expected result.
*/
int failures = 0;
Object tests[][] = getTests();
for (int i=0; i<tests.length; i++) {
System.out.println("******************");
System.out.println("Test with response: >" + tests[i][0] + "<");
URL url = new URL("http://" + authority + "/" + i);
HttpURLConnection http = (HttpURLConnection)url.openConnection(NO_PROXY);
try {
// test getResponseCode
//
int expectedCode = Integer.parseInt((String)tests[i][1]);
int actualCode = http.getResponseCode();
if (actualCode != expectedCode) {
System.out.println("getResponseCode returned: " + actualCode +
", expected: " + expectedCode);
failures++;
continue;
}
// test getResponseMessage
//
String expectedPhrase = (String)tests[i][2];
String actualPhrase = http.getResponseMessage();
if (actualPhrase == null && expectedPhrase == null) {
continue;
}
if (!actualPhrase.equals(expectedPhrase)) {
System.out.println("getResponseMessage returned: " +
actualPhrase + ", expected: " + expectedPhrase);
}
} catch (IOException e) {
System.err.println("Test failed for >" + tests[i][0] + "<: " + e);
e.printStackTrace();
failures++;
}
}
/* shutdown http server */
svr.shutdown();
if (failures > 0) {
throw new Exception(failures + " sub-test(s) failed.");
}
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright (c) 2016, 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.
*/
/* @test
* @bug 8163449 8175261
* @summary Allow per protocol setting for URLConnection defaultUseCaches
* @run testng/othervm SetDefaultUseCaches
*/
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.net.URLConnection;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class SetDefaultUseCaches {
final URL fileURL = uncheckURL("file:///a/b.txt");
final URL httpURL = uncheckURL("http://www.foo.com/");
final URL jarFileURL = uncheckURL("jar:file:///a/b.jar!/anEntry");
final URL jarHttpURL = uncheckURL("jar:http://www.foo.com/a/b.jar!/anEntry");
@Test
public void test() throws Exception {
// check JAR both before and after other protocol tests as JAR URLs
// effectively wrap/embed other URLs. The syntax is jar:<url>!/{entry}
checkJAR(true);
checkJAR(false);
checkJAR(true);
checkHTTP();
checkFile();
// ensure that JAR URLs still respect their per-protocol value
checkJAR(false);
checkJAR(true);
checkJAR(false);
}
void checkHTTP() throws IOException {
// check default default is true
URLConnection httpURLConn = httpURL.openConnection();
assertTrue(httpURLConn.getDefaultUseCaches());
// set default for http to false and check
URLConnection.setDefaultUseCaches("HTTP", false);
httpURLConn = httpURL.openConnection();
assertTrue(httpURLConn.getDefaultUseCaches());
assertFalse(httpURLConn.getUseCaches());
assertFalse(URLConnection.getDefaultUseCaches("http"));
}
void checkFile() throws IOException {
URLConnection fileURLConn = fileURL.openConnection();
assertTrue(fileURLConn.getDefaultUseCaches());
// set default default to false and check other values the same
fileURLConn.setDefaultUseCaches(false);
fileURLConn.setDefaultUseCaches("fiLe", true);
assertFalse(fileURLConn.getDefaultUseCaches());
assertTrue(URLConnection.getDefaultUseCaches("fiLE"));
}
void checkJAR(boolean defaultValue) throws IOException {
URLConnection.setDefaultUseCaches("JAR", defaultValue);
assertEquals(URLConnection.getDefaultUseCaches("JAr"), defaultValue);
URLConnection jarFileURLConn = jarFileURL.openConnection();
URLConnection jarHttpURLConn = jarHttpURL.openConnection();
assertEquals(jarFileURLConn.getUseCaches(), defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), defaultValue);
jarFileURLConn.setUseCaches(!defaultValue);
jarHttpURLConn.setUseCaches(!defaultValue);
assertEquals(jarFileURLConn.getUseCaches(), !defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), !defaultValue);
URLConnection.setDefaultUseCaches("JaR", !defaultValue); // case-insensitive
assertEquals(URLConnection.getDefaultUseCaches("jAR"), !defaultValue);
jarFileURLConn = jarFileURL.openConnection();
jarHttpURLConn = jarHttpURL.openConnection();
assertEquals(jarFileURLConn.getUseCaches(), !defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), !defaultValue);
jarFileURLConn.setUseCaches(defaultValue);
jarHttpURLConn.setUseCaches(defaultValue);
assertEquals(jarFileURLConn.getUseCaches(), defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), defaultValue);
}
static URL uncheckURL(String url) {
try { return new URL(url); }
catch (IOException e) { throw new UncheckedIOException(e); }
}
}

View file

@ -0,0 +1,138 @@
/*
* Copyright (c) 2000, 2019, 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.
*/
/* @test
* @bug 4397096
* @library /test/lib
* @run main/othervm SetIfModifiedSince
* @summary setIfModifiedSince() of HttpURLConnection sets invalid date of default locale
*/
import java.net.*;
import java.io.*;
import java.util.*;
import jdk.test.lib.net.URIBuilder;
public class SetIfModifiedSince {
static volatile boolean successfulHeaderCheck = false;
static final String MARKER = "A-test-name";
static class XServer extends Thread {
ServerSocket srv;
Socket s;
InputStream is;
OutputStream os;
XServer (ServerSocket s) {
srv = s;
}
Socket getSocket () {
return (s);
}
public void run() {
boolean foundMarker = false;
while (!foundMarker) {
String x;
try {
s = srv.accept();
System.out.println("Server: accepting connection from: " + s);
is = s.getInputStream ();
} catch (IOException io) {
System.err.println("Server: Failed to accept connection: " + io);
io.printStackTrace();
try { srv.close(); } catch (IOException ioc) { }
break;
}
try {
BufferedReader r = new BufferedReader(new InputStreamReader(is));
os = s.getOutputStream ();
boolean foundHeader;
while ((x=r.readLine()) != null) {
String testname = MARKER + ": ";
String header = "If-Modified-Since: ";
if (x.startsWith(header)) {
foundHeader = true;
System.out.println("Server: found header: " + x);
if (x.charAt(header.length()) == '?') {
s.close ();
srv.close (); // or else the HTTPURLConnection will retry
throw new RuntimeException
("Invalid HTTP date specification");
}
if (foundMarker) break;
} else if (x.startsWith(testname)) {
foundMarker = true;
System.out.println("Server: found marker: " + x);
}
}
successfulHeaderCheck = true;
s.close ();
// only close server if connected from this test.
if (foundMarker) {
srv.close (); // or else the HTTPURLConnection will retry
}
} catch (IOException e) {}
}
}
}
public static void main(String[] args) throws Exception {
Locale reservedLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.JAPAN);
ServerSocket serversocket = new ServerSocket();
serversocket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
int port = serversocket.getLocalPort ();
XServer server = new XServer (serversocket);
server.start ();
Thread.sleep (2000);
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.path("/index.html")
.toURLUnchecked();
URLConnection urlc = url.openConnection(Proxy.NO_PROXY);
urlc.setRequestProperty(MARKER, "SetIfModifiedSince");
urlc.setIfModifiedSince (10000000);
InputStream is = urlc.getInputStream ();
int i = 0, c;
Thread.sleep(5000);
if (!successfulHeaderCheck) {
throw new RuntimeException("Header check was unsuccessful");
}
} catch (SocketException ce) {
if (!successfulHeaderCheck) {
throw ce;
}
System.out.println("ConnectionException expected on successful check of If-modified-since header");
} finally {
// restore the reserved locale
Locale.setDefault(reservedLocale);
}
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2016, 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.
*/
/*
* @test
* @bug 8146041
* @summary java.net.URLConnection.guessContentTypeFromStream() does not
* recognize TIFF streams
*/
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLConnection;
public class TIFFContentGuesser {
private static final byte[] LITTLE_ENDIAN_MAGIC =
new byte[] {(byte)0x49, (byte)0x49, (byte)0x2a, (byte)0};
private static final byte[] BIG_ENDIAN_MAGIC =
new byte[] {(byte)0x4d, (byte)0x4d, (byte)0, (byte)0x2a};
private static final String TIFF_MIME_TYPE = "image/tiff";
public static void main(String[] args) throws Throwable {
int failures = 0;
InputStream stream = new ByteArrayInputStream(LITTLE_ENDIAN_MAGIC);
String contentType = URLConnection.guessContentTypeFromStream(stream);
if (contentType == null || !contentType.equals(TIFF_MIME_TYPE)) {
failures++;
System.err.println("Test failed for little endian magic");
}
stream = new ByteArrayInputStream(BIG_ENDIAN_MAGIC);
contentType = URLConnection.guessContentTypeFromStream(stream);
if (contentType == null || !contentType.equals(TIFF_MIME_TYPE)) {
failures++;
System.err.println("Test failed for big endian magic");
}
if (failures != 0) {
throw new RuntimeException
("Test failed with " + failures + " error(s)");
}
}
}

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/*
* @test
* @bug 4389976
* @library /test/lib
* @summary can't unblock read() of InputStream from URL connection
* @run main/timeout=40/othervm -Dsun.net.client.defaultReadTimeout=2000 TimeoutTest
*/
import java.io.*;
import java.net.*;
import jdk.test.lib.net.URIBuilder;
public class TimeoutTest {
class Server extends Thread {
ServerSocket server;
Server (ServerSocket server) {
super ();
this.server = server;
}
public void run () {
try {
Socket s = server.accept ();
while (!finished ()) {
Thread.sleep (1000);
}
s.close();
} catch (Exception e) {
}
}
boolean isFinished = false;
synchronized boolean finished () {
return (isFinished);
}
synchronized void done () {
isFinished = true;
}
}
public static void main(String[] args) throws Exception {
TimeoutTest t = new TimeoutTest ();
t.test ();
}
public void test() throws Exception {
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
Server s = new Server (ss);
try{
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.toURL();
System.out.println("URL: " + url);
URLConnection urlc = url.openConnection ();
InputStream is = urlc.getInputStream ();
throw new RuntimeException("Should have received timeout");
} catch (SocketTimeoutException e) {
return;
} finally {
s.done();
ss.close();
}
}
}

View file

@ -0,0 +1,112 @@
/*
* Copyright (c) 2024, 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.
*/
/**
* @test
* @bug 8335135
* @library /test/lib
* @summary Check that reading from inputStream throws an IOException
* if the fixed response stream is closed before reading all bytes.
*/
import jdk.test.lib.net.URIBuilder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
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;
public class TruncatedFixedResponse implements Runnable {
ServerSocket ss;
/*
* Our "http" server to return a truncated fixed response
*/
public void run() {
try {
Socket s = ss.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
while (true) {
String req = in.readLine();
if (req.isEmpty()) {
break;
}
}
PrintStream out = new PrintStream(
new BufferedOutputStream(s.getOutputStream()));
/* send the header */
out.print("HTTP/1.1 200\r\n");
out.print("Content-Length: 100\r\n");
out.print("Content-Type: text/html\r\n");
out.print("\r\n");
out.print("Some content, but too short");
out.close();
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
TruncatedFixedResponse() throws Exception {
/* start the server */
ss = new ServerSocket();
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
new Thread(this).start();
/* establish http connection to server */
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.path("/foo")
.toURL();
HttpURLConnection http = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
try (InputStream in = http.getInputStream()) {
while (in.read() != -1) {
// discard response
}
throw new AssertionError("Expected IOException was not thrown");
} catch (IOException ex) {
System.out.println("Got expected exception: " + ex);
}
}
public static void main(String args[]) throws Exception {
new TruncatedFixedResponse();
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2001, 2025, 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.
*/
/**
* @test
* @bug 4401485
* @requires (os.family == "windows")
* @modules java.base/sun.net.www.protocol.file
* @library /test/lib
* @summary Check that URL.openConnection() doesn't open connection to UNC
*/
import jtreg.SkippedException;
import sun.net.www.protocol.file.FileURLConnection;
import java.io.File;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
public class UNCTest {
public static void main(String[] args) throws Exception {
// Get the "computer name" for this host
String hostName = InetAddress.getLocalHost().getHostName();
// UNC path which always exists with Administrative Shares enabled
String path = "\\\\" + hostName + "\\C$\\Windows";
// Skip test if Administrative Shares is disabled
if (! new File(path).exists()) {
throw new SkippedException("Administrative Shares not enabled");
}
// File URL for the UNC path
URL url = new URI("file://" + hostName + "/C$/Windows").toURL();
// Should open a FileURLConnection for the UNC path
URLConnection conn = url.openConnection();
// Sanity check that the connection is a FileURLConnection
if (! (conn instanceof FileURLConnection)) {
throw new Exception("Expected FileURLConnection, instead got "
+ conn.getClass().getName());
}
// Verify that the connection is not in an already connected state
conn.setRequestProperty( "User-Agent", "Java" );
}
}

View file

@ -0,0 +1,122 @@
/*
* Copyright (c) 2001, 2021, 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.
*/
/*
* @test
* @bug 4143541 4147035 4244362 8133686
* @summary URLConnection cannot enumerate request properties,
* and URLConnection can neither get nor set multiple
* request properties w/ same key
* @library /test/lib
*
*/
import java.net.*;
import java.util.*;
import java.io.*;
import jdk.test.lib.net.URIBuilder;
import static java.net.Proxy.NO_PROXY;
public class URLConnectionHeaders {
static class XServer extends Thread {
ServerSocket srv;
Socket s;
InputStream is;
OutputStream os;
XServer (ServerSocket s) {
srv = s;
}
Socket getSocket () {
return (s);
}
public void run() {
try {
String x;
s = srv.accept ();
is = s.getInputStream ();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
os = s.getOutputStream ();
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os));
w.write("HTTP/1.1 200 OK\r\n");
w.write("Content-Type: text/plain\r\n");
while ((x=r.readLine()).length() != 0) {
System.out.println("request: "+x);
if (!x.startsWith("GET")) {
w.write(x);
w.newLine();
}
}
w.newLine();
w.flush();
s.close ();
} catch (IOException e) { e.printStackTrace();
} finally {
try { srv.close(); } catch (IOException unused) {}
}
}
}
public static void main(String[] args) throws Exception {
try {
InetAddress loopback = InetAddress.getLoopbackAddress();
ServerSocket serversocket = new ServerSocket();
serversocket.bind(new InetSocketAddress(loopback, 0));
int port = serversocket.getLocalPort();
XServer server = new XServer(serversocket);
server.start();
Thread.sleep(200);
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.path("/index.html")
.toURL();
URLConnection uc = url.openConnection(NO_PROXY);
// add request properties
uc.addRequestProperty("Cookie", "cookie1");
uc.addRequestProperty("Cookie", "cookie2");
uc.addRequestProperty("Cookie", "cookie3");
Map e = uc.getRequestProperties();
if (!((List)e.get("Cookie")).toString().equals("[cookie1, cookie2, cookie3]")) {
throw new RuntimeException("getRequestProperties fails");
}
e = uc.getHeaderFields();
if ((e.get("Content-Type") == null) || (e.get(null) == null)) {
throw new RuntimeException("getHeaderFields fails");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}

View file

@ -0,0 +1,84 @@
/*
* Copyright (c) 2021, 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.
*/
/**
* @test
* @bug 8133686
* @summary Ensuring that multiple header values for a given field-name are returned in
* the order they were added for HttpURLConnection.getRequestProperties
* and HttpURLConnection.getHeaderFields
* @library /test/lib
* @run testng URLConnectionHeadersOrder
*/
import jdk.test.lib.net.URIBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
public class URLConnectionHeadersOrder {
@Test
public void testRequestPropertiesOrder() throws Exception {
var url = URIBuilder.newBuilder()
.scheme("http")
.host(InetAddress.getLoopbackAddress())
.toURL();
var conn = new DummyHttpURLConnection(url);
conn.addRequestProperty("test", "a");
conn.addRequestProperty("test", "b");
conn.addRequestProperty("test", "c");
conn.connect();
var expectedRequestProps = Arrays.asList("a", "b", "c");
var actualRequestProps = conn.getRequestProperties().get("test");
Assert.assertNotNull(actualRequestProps);
String errorMessageTemplate = "Expected Request Properties = %s, Actual Request Properties = %s";
Assert.assertEquals(actualRequestProps, expectedRequestProps, String.format(errorMessageTemplate, expectedRequestProps.toString(), actualRequestProps.toString()));
}
}
class DummyHttpURLConnection extends URLConnection {
/**
* Constructs a URL connection to the specified URL. A connection to
* the object referenced by the URL is not created.
*
* @param url the specified URL.
*/
protected DummyHttpURLConnection(URL url) {
super(url);
}
@Override
public void connect() throws IOException {
var connected = true;
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2004, 2006, 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.
*/
/* @test
* @bug 4975103
* @summary URLConnection.getContentType() does not always return content-type header field
*/
import java.net.*;
import java.io.*;
public class UnknownContentType {
public static void main(String[] args) throws Exception {
File tmp = File.createTempFile("bug4975103", null);
tmp.deleteOnExit();
URL url = tmp.toURL();
URLConnection conn = url.openConnection();
conn.connect();
String s1 = conn.getContentType();
String s2 = conn.getHeaderField("content-type");
if (!s1.equals(s2))
throw new RuntimeException("getContentType() differs from getHeaderField(\"content-type\")");
}
}

View file

@ -0,0 +1,345 @@
/*
* Copyright (c) 2001, 2019, 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.
*/
/**
* @test
* @bug 4507412
* @bug 4506998
* @summary Check that a 304 "Not-Modified" response from a server
* doesn't cause http client to close a keep-alive
* connection.
* Check that a content-length of 0 results in an
* empty input stream.
* @library /test/lib
* @run main ZeroContentLength
* @run main/othervm -Djava.net.preferIPv6Addresses=true ZeroContentLength
*/
import java.net.*;
import java.io.*;
import jdk.test.lib.net.URIBuilder;
public class ZeroContentLength {
/*
* Is debugging enabled - start with -d to enable.
*/
static boolean debug = false;
static void debug(String msg) {
if (debug)
System.out.println(msg);
}
/*
* The response string and content-length that
* the server should return;
*/
static String response;
static int contentLength;
static synchronized void setResponse(String rsp, int cl) {
response = rsp;
contentLength = cl;
}
static synchronized String getResponse() {
return response;
}
static synchronized int getContentLength() {
return contentLength;
}
/*
* Worker thread to service single connection - can service
* multiple http requests on same connection.
*/
class Worker extends Thread {
Socket s;
int id;
Worker(Socket s, int id) {
this.s = s;
this.id = id;
}
final int CR = '\r';
final int LF = '\n';
public void run() {
try {
s.setSoTimeout(2000);
int max = 20; // there should only be 20 connections
InputStream in = new BufferedInputStream(s.getInputStream());
for (;;) {
// read entire request from client, until CR LF CR LF
int c, total=0;
try {
while ((c = in.read()) > 0) {
total++;
if (c == CR) {
if ((c = in.read()) > 0) {
total++;
if (c == LF) {
if ((c = in.read()) > 0) {
total++;
if (c == CR) {
if ((c = in.read()) > 0) {
total++;
if (c == LF) {
break;
}
}
}
}
}
}
}
}
} catch (SocketTimeoutException e) {}
debug("worker " + id +
": Read request from client " +
"(" + total + " bytes).");
if (total == 0) {
debug("worker: " + id + ": Shutdown");
return;
}
// response to client
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
out.print("HTTP/1.1 " + getResponse() + "\r\n");
int clen = getContentLength();
if (clen >= 0) {
out.print("Content-Length: " + clen +
"\r\n");
}
out.print("\r\n");
for (int i=0; i<clen; i++) {
out.write( (byte)'.' );
}
out.flush();
debug("worked " + id +
": Sent response to client, length: " + clen);
if (--max == 0) {
s.close();
return;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception e) { }
}
}
}
/*
* Server thread to accept connection and create worker threads
* to service each connection.
*/
class Server extends Thread {
ServerSocket ss;
int connectionCount;
boolean shutdown = false;
Server(ServerSocket ss) {
this.ss = ss;
}
public synchronized int connectionCount() {
return connectionCount;
}
public synchronized void shutdown() {
shutdown = true;
}
public void run() {
try {
ss.setSoTimeout(2000);
for (;;) {
Socket s;
try {
debug("server: Waiting for connections");
s = ss.accept();
} catch (SocketTimeoutException te) {
synchronized (this) {
if (shutdown) {
debug("server: Shuting down.");
return;
}
}
continue;
}
int id;
synchronized (this) {
id = connectionCount++;
}
Worker w = new Worker(s, id);
w.start();
debug("server: Started worker " + id);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (Exception e) { }
}
}
}
/*
* Make a single http request and return the content length
* received. Also do sanity check to ensure that the
* content-length header matches the total received on
* the input stream.
*/
int doRequest(String uri) throws Exception {
URL url = new URL(uri);
HttpURLConnection http = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
int cl = http.getContentLength();
InputStream in = http.getInputStream();
byte b[] = new byte[100];
int total = 0;
int n;
do {
n = in.read(b);
if (n > 0) total += n;
} while (n > 0);
in.close();
if (cl >= 0 && total != cl) {
System.err.println("content-length header indicated: " + cl);
System.err.println("Actual received: " + total);
throw new Exception("Content-length didn't match actual received");
}
return total;
}
/*
* Send http requests to "server" and check that they all
* use the same network connection and that the content
* length corresponds to the content length expected.
* stream.
*/
ZeroContentLength() throws Exception {
/* start the server */
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
Server svr = new Server(ss);
svr.start();
String uri = URIBuilder.newBuilder()
.scheme("http")
.host(ss.getInetAddress())
.port(ss.getLocalPort())
.path("/foo.html")
.build().toString();
int expectedTotal = 0;
int actualTotal = 0;
System.out.println("**********************************");
System.out.println("200 OK, content-length:1024 ...");
setResponse("200 OK", 1024);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
expectedTotal += 1024;
}
System.out.println("**********************************");
System.out.println("200 OK, content-length:0 ...");
setResponse("200 OK", 0);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
}
System.out.println("**********************************");
System.out.println("304 Not-Modified, (no content-length) ...");
setResponse("304 Not-Modifed", -1);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
}
System.out.println("**********************************");
System.out.println("204 No-Content, (no content-length) ...");
setResponse("204 No-Content", -1);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
}
// shutdown server - we're done.
svr.shutdown();
System.out.println("**********************************");
if (actualTotal == expectedTotal) {
System.out.println("Passed: Actual total equal to expected total");
} else {
throw new Exception("Actual total != Expected total!!!");
}
int cnt = svr.connectionCount();
if (cnt == 1) {
System.out.println("Passed: Only 1 connection established");
} else {
throw new Exception("Test failed: Number of connections " +
"established: " + cnt + " - see log for details.");
}
}
public static void main(String args[]) throws Exception {
if (args.length > 0 && args[0].equals("-d")) {
debug = true;
}
new ZeroContentLength();
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 1999, 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
* 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.
*/
/**
* Plain text file handler
*
* This class provides an example of a replacement content handler for
* the text/plain content type. It reads the content of the URL, and prepends
* an additional message at the beginning.
*
* Note that the only restrictions on the package/class names are:
* 1) the package must end in the major type of the content type (such as
* text, image, application, etc).
* 2) the class name must be named with the subtype of the content type (for
* content type "text/plain", this would be "plain" as in this example; for
* content type "image/gif", the class name would be "gif", and the package
* name must end with ".image".
* 3) the class must be a subclass of ContentHandler.
* 4) It must define the getContent function.
*/
package COM.foo.content.text;
import java.net.ContentHandler;
import java.io.InputStream;
import java.net.URLConnection;
import java.io.IOException;
public class plain extends ContentHandler {
/**
* Returns one of several object types (this set may change in future
* versions):
* 1) instance of Thread:
* Invoke the thread to launch an external viewer.
* 2) instance of InputStream:
* Bring up the "Save to disk" dialog page to allow the content
* to be saved to disk.
* 3) instance of InputStreamImageSource:
* Load the image into HotJava in an image viewer page.
* 4) instance of String:
* Go to a new page with the string as the plain text content
* of that page.
*/
public Object getContent(URLConnection uc) {
try {
InputStream is = uc.getInputStream();
StringBuffer sb = new StringBuffer();
int c;
sb.append("[Content of " + uc.getURL() + "]\n\n");
sb.append("[This opening message brought to you by your plain/text\n");
sb.append("content handler. To remove this content handler, delete the\n");
sb.append("COM.foo.content.text directory from your class path and\n");
sb.append("the java.content.handler.pkgs property from your HotJava\n");
sb.append("properties file.]\n");
sb.append("----------------------------------------------------------------\n\n");
// Read the characters from the source, accumulate them into the string buffer.
// (Not the most efficient, but simplest for this example.)
while ((c = is.read()) >= 0) {
sb.append((char)c);
}
// Tidy up
is.close();
// Return the resulting string to our client (we're case 4 above)
return sb.toString();
} catch (IOException e) {
// For any exception, just return an indication of what went wrong.
return "Problem reading document: " + uc.getURL();
}
}
}

View file

@ -0,0 +1,112 @@
/*
* Copyright (c) 1999, 2019, 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.
*/
/* @test
* @bug 4191147
* @summary 1.2beta4 does not load user defined content handlers
* @library /test/lib
* @build UserContentHandler
* @run main/othervm UserContentHandler
*/
/* Run in othervm mode since the test sets a system property, java.content.handler.pkgs,
* that prepends a specific package prefix defining a text/plain content
* handler. If other URLConnection tests run before this one they might trigger
* the Sun implementation text/plain content handler in sun.net.www.content
* to be loaded and cached, this will break this test.
*/
import java.net.*;
import java.io.*;
import java.util.*;
import jdk.test.lib.net.URIBuilder;
import static java.net.Proxy.NO_PROXY;
public class UserContentHandler implements Runnable {
ServerSocket ss;
public void run() {
try {
Socket s = ss.accept();
s.setTcpNoDelay(true);
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
out.print("HTTP/1.1 200 OK\r\n");
out.print("Content-Length: 11\r\n");
out.print("Content-Type: text/plain\r\n");
out.print("\r\n");
out.print("l;ajfdjafd\n");
out.flush();
// don't close the connection immediately as otherwise
// the http headers may not have been received and the
// http client will re-connect.
Thread.sleep(2000);
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
UserContentHandler() throws Exception {
InetAddress loopback = InetAddress.getLoopbackAddress();
ss = new ServerSocket();
ss.bind(new InetSocketAddress(loopback, 0));
Thread thr = new Thread(this);
thr.start();
try {
Object o = new COM.foo.content.text.plain();
} catch (Exception ex) {
ex.printStackTrace();
}
Properties props = System.getProperties();
props.put("java.content.handler.pkgs", "COM.foo.content");
System.setProperties(props);
URL u = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.path("/anything.txt")
.toURL();
if (!(u.openConnection(NO_PROXY).getContent() instanceof String)) {
throw new RuntimeException("Load user defined content handler failed.");
} else {
System.err.println("Load user defined content handler succeed!");
}
}
public static void main(String args[]) throws Exception {
new UserContentHandler();
}
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

View file

@ -0,0 +1,7 @@
<?XML VERSION="1.0" ENCODING="windows-1525"?>
<doc/>
<!--
Microsoft has been shipping "XML" that is noncompliant.
This must be rejected by any conforming XML processor.
-->

View file

@ -0,0 +1,6 @@
<?xMl version="1.0"?>
<doc/>
<!--
XML declarations MUST be in lowercase.
-->

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="US-ASCII"?>
<doc/>
<!--
Most legal XML documents encoded with supersets of US-ASCII
will start like this document. Includes ISO-8859-1, EUC-JP,
Shift_JIS, UTF-8, ISO-2022-JP, and other encodings.
That is: they're flagged up front with an XML declaration.
-->

View file

@ -0,0 +1,6 @@
<!--
XML declarations are optional, sometimes file types
are used to flag things.
-->
<doc/>

Binary file not shown.

Binary file not shown.