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,81 @@
/*
* Copyright (c) 2003, 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 4148751
* @summary URL.sameFile return false on URL's, that are equal modulo url-encoding
*/
import java.net.*;
public class B4148751
{
// unencoded parameters
final static String scheme = "http";
final static String auth = "web2.javasoft.com";
final static String path = "/some file.html";
final static String unencoded = "http://web2.javasoft.com/some file.html";
// encoded URL / URI
final static String encoded = "http://web2.javasoft.com/some%20file.html";
public static void main(String args[]) throws URISyntaxException,
MalformedURLException {
URL url = null;
URL url1 = null;
try {
url = new URL(unencoded);
url1 = new URL(encoded);
}
catch(Exception e) {
System.out.println("Unexpected exception :" + e);
System.exit(-1);
}
if(url.sameFile(url1)) {
throw new RuntimeException ("URL does not understand escaping");
}
/* check decoding of a URL */
URI uri = url1.toURI();
if (!uri.getPath().equals (path)) {
throw new RuntimeException ("Got: " + uri.getPath() + " expected: " +
path);
}
/* check encoding of a URL */
URI uri1 = new URI (scheme, auth, path);
url = uri.toURL();
if (!url.toString().equals (encoded)) {
throw new RuntimeException ("Got: " + url.toString() + " expected: " +
encoded);
}
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2005, 2017, 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 5086147
* @requires (os.family == "windows")
* @run main B5086147
* @summary File,URI,URL conversions are strange for UNC path
*/
import java.io.File;
import java.net.URI;
public class B5086147 {
public static final void main( String[] aaParamters ) throws Exception{
File file = new File( "\\\\somehost\\someshare\\somefile.ext" );
URI uri = file.toURI();
if (!(uri.toURL().toURI().equals(uri))) {
throw new RuntimeException("Test failed : (uri.toURL().toURI().equals(uri)) isn't hold");
}
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2007, 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 6529759
* @summary URL constructor of specific form does not provide exception chaining
*/
import java.net.URL;
public class B6529759
{
public static void main(String[] args) {
try {
new java.net.URL(null, "a:", new a());
} catch (Exception e) {
if (e.getCause() == null) {
e.printStackTrace();
throw new RuntimeException("Failed: Exception has no cause");
}
}
}
static class a extends java.net.URLStreamHandler {
protected java.net.URLConnection openConnection(java.net.URL u) {
throw new UnsupportedOperationException();
}
protected void parseURL(java.net.URL u, String spec, int start, int limit) {
throw new RuntimeException();
}
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 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
* @summary URL.openConnection can throw IOOBE
* @bug 8282395
*/
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
public class B8282395 {
public static void main(String[] args) throws Exception {
boolean res = false;
URL url = new URL("ftp://.:%@");
try {
// Will throw IndexOutOfBoundsException if not fixed
url.openConnection();
} catch (MalformedURLException e) {
res = true;
}
if (!res) {
throw new RuntimeException("MalformedURLException should be thrown");
}
res = false;
try {
// Will throw IndexOutOfBoundsException if not fixed
url.openConnection(Proxy.NO_PROXY);
} catch (MalformedURLException e) {
res = true;
}
if (!res) {
throw new RuntimeException("MalformedURLException should be thrown");
}
}
}

View file

@ -0,0 +1,272 @@
/*
* Copyright (c) 1998, 2026, 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 4393671
* @summary URL constructor URL(URL context, String spec) FAILED with specific input
*/
/*
* This program tests the URL parser in the URL constructor. It
* tries to construct a variety of valid URLs with a given context
* (which may be null) and a variety of specs. It then compares the
* result with an expected value.
*/
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Constructor {
public static void main(String[] args) throws Exception {
List<Entry> entries = new ArrayList<>();
entries.addAll(Arrays.asList(fileURLs));
entries.addAll(Arrays.asList(jarURLs));
entries.addAll(Arrays.asList(normalHttpURLs));
entries.addAll(Arrays.asList(abnormalHttpURLs));
entries.addAll(Arrays.asList(blankComponents));
if (hasFtp())
entries.addAll(Arrays.asList(ftpURLs));
URL url;
for (Entry e : entries) {
if (e.context == null)
url = new URL(e.spec);
else
url = new URL(new URL(e.context), e.spec);
if (!(url.toString().equals(e.expected))) {
throw new RuntimeException("error for: \n\tURL:" + e.context +
"\n\tspec: " + e.spec +
"\n\texpected: " + e.expected +
"\n\tactual: " + url.toString());
} else {
//debug
//System.out.println("success for: " + url);
}
}
}
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;
}
}
static class Entry {
final String context;
final String spec;
final String expected;
Entry(String context, String spec, String expected) {
this.context = context;
this.spec =spec;
this.expected = expected;
}
}
static Entry[] fileURLs = new Entry[] {
new Entry(null,
"file://JavaSoft/Test",
"file://JavaSoft/Test"),
new Entry(null,
"file:///JavaSoft/Test",
"file:/JavaSoft/Test"),
new Entry(null,
"file:/JavaSoft/Test",
"file:/JavaSoft/Test"),
new Entry(null,
"file:/c:/JavaSoft/Test",
"file:/c:/JavaSoft/Test"),
new Entry(null,
"file:/c:/JavaSoft/Test:something",
"file:/c:/JavaSoft/Test:something"),
new Entry(null,
"file:/c:/JavaSoft/Test#anchor",
"file:/c:/JavaSoft/Test#anchor"),
new Entry("file://JavaSoft/Test",
"Test#bar",
"file://JavaSoft/Test#bar"),
new Entry("file://codrus/c:/jdk/eng/index.html",
"pulsar.html",
"file://codrus/c:/jdk/eng/pulsar.html"),
new Entry("file:///c:/jdk/eng/index.html",
"pulsar.html",
"file:/c:/jdk/eng/pulsar.html"),
new Entry("file:///jdk/eng/index.html",
"pulsar.html",
"file:/jdk/eng/pulsar.html"),
new Entry("file://JavaSoft/Test",
"file://radartoad.com/Test#bar",
"file://radartoad.com/Test#bar"),
new Entry("file://JavaSoft/Test",
"/c:/Test#bar",
"file://JavaSoft/c:/Test#bar"),
};
static Entry[] jarURLs = new Entry[] {
new Entry(null,
"jar:http://www.foo.com/dir1/jar.jar!/dir2/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir2/entry.txt"),
new Entry(null,
"jar:http://www.foo.com/dir1/jar.jar!/",
"jar:http://www.foo.com/dir1/jar.jar!/"),
new Entry(null,
"jar:http://www.foo.com/dir1/jar.jar!/",
"jar:http://www.foo.com/dir1/jar.jar!/"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"dir1/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"/dir1/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/dir1/",
"entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/dir2/dir3/entry2.txt",
"/dir1/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"/dir1/foo/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/foo/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/dir1/dir2/dir3/",
"dir4/foo/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/dir2/dir3/dir4/foo/entry.txt"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/",
"/dir1/foo/entry.txt",
"jar:http://www.foo.com/dir1/jar.jar!/dir1/foo/entry.txt"),
new Entry(null,
"jar:http://www.foo.com/dir1/jar.jar!/foo.txt#anchor",
"jar:http://www.foo.com/dir1/jar.jar!/foo.txt#anchor"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/foo.txt",
"#anchor",
"jar:http://www.foo.com/dir1/jar.jar!/foo.txt#anchor"),
new Entry("jar:http://www.foo.com/dir1/jar.jar!/foo/bar/",
"baz/quux#anchor",
"jar:http://www.foo.com/dir1/jar.jar!/foo/bar/baz/quux#anchor"),
new Entry("jar:http://balloo.com/olle.jar!/",
"p2",
"jar:http://balloo.com/olle.jar!/p2")
};
static Entry[] normalHttpURLs = new Entry[] {
new Entry("http://a/b/c/d;p?q", "g", "http://a/b/c/g"),
new Entry("http://a/b/c/d;p?q", "./g", "http://a/b/c/g"),
new Entry("http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"),
new Entry("http://a/b/c/d;p?q", "/g", "http://a/g"),
new Entry("http://a/b/c/d;p?q", "//g", "http://g"),
new Entry("http://a/b/c/d;p?q", "?y", "http://a/b/c/?y"),
new Entry("http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"),
new Entry("http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"),
new Entry("http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"),
new Entry("http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"),
new Entry("http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"),
new Entry("http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"),
new Entry("http://a/b/c/d;p?q", ".", "http://a/b/c/"),
new Entry("http://a/b/c/d;p?q", "./", "http://a/b/c/"),
new Entry("http://a/b/c/d;p?q", "..", "http://a/b/"),
new Entry("http://a/b/c/d;p?q", "../", "http://a/b/"),
new Entry("http://a/b/c/d;p?q", "../g", "http://a/b/g"),
new Entry("http://a/b/c/d;p?q", "../..", "http://a/"),
new Entry("http://a/b/c/d;p?q", "../../", "http://a/"),
new Entry("http://a/b/c/d;p?q", "../../g", "http://a/g"),
new Entry(null,
"http://www.javasoft.com/jdc/community/chat/index.html#javalive?frontpage-jdc",
"http://www.javasoft.com/jdc/community/chat/index.html#javalive?frontpage-jdc")
};
static Entry[] abnormalHttpURLs = new Entry[] {
new Entry("http://a/b/c/d;p?q", "../../../g", "http://a/../g"),
new Entry("http://a/b/c/d;p?q", "../../../../g", "http://a/../../g"),
new Entry("http://a/b/c/d;p?q", "/./g", "http://a/./g"),
new Entry("http://a/b/c/d;p?q", "/../g", "http://a/../g"),
new Entry("http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"),
new Entry("http://a/b/c/d;p?q", "g.", "http://a/b/c/g."),
new Entry("http://a/b/c/d;p?q", "./../g", "http://a/b/g"),
new Entry("http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"),
new Entry("http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"),
new Entry("http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"),
new Entry("http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y")
};
static Entry[] ftpURLs = new Entry[] {
new Entry(null,
"ftp://ftp.foo.com/dir1/entry.txt",
"ftp://ftp.foo.com/dir1/entry.txt"),
new Entry(null,
"ftp://br:pwd@ftp.foo.com/dir1/jar.jar",
"ftp://br:pwd@ftp.foo.com/dir1/jar.jar"),
new Entry("ftp://ftp.foo.com/dir1/foo.txt",
"bar.txt",
"ftp://ftp.foo.com/dir1/bar.txt"),
new Entry("ftp://ftp.foo.com/dir1/jar.jar",
"/entry.txt",
"ftp://ftp.foo.com/entry.txt"),
new Entry("ftp://ftp.foo.com/dir1/jar.jar",
"dir1/entry.txt",
"ftp://ftp.foo.com/dir1/dir1/entry.txt"),
new Entry("ftp://ftp.foo.com/dir1/jar.jar",
"/dir1/entry.txt",
"ftp://ftp.foo.com/dir1/entry.txt"),
new Entry("ftp://br:pwd@ftp.foo.com/dir1/jar.jar",
"/dir1/entry.txt",
"ftp://br:pwd@ftp.foo.com/dir1/entry.txt")
};
static Entry[] blankComponents = new Entry[] {
new Entry(null, "http://host/path#", "http://host/path#"),
new Entry(null, "http://host/path?", "http://host/path?"),
new Entry(null, "http://host/path?#", "http://host/path?#"),
new Entry(null, "http://host/path#?", "http://host/path#?"),
new Entry(null, "file:/path#", "file:/path#"),
new Entry(null, "file:/path?", "file:/path?"),
new Entry(null, "file:/path?#", "file:/path?#"),
new Entry(null, "file:///path#", "file:/path#"),
new Entry(null, "file:///path?", "file:/path?"),
new Entry(null, "file:/path#?", "file:/path#?"),
new Entry("file:/path", "path?#", "file:/path?#"),
new Entry(null, "file:", "file:"),
new Entry(null, "file:#", "file:#")
};
}

View file

@ -0,0 +1,524 @@
/*
* Copyright (c) 2022, 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 8293590
* @summary URL built-in protocol handlers should parse the URL early
* to avoid constructing URLs for which openConnection
* would later throw an exception, when possible.
* A jdk.net.url.delayParsing property allows to switch that
* behavior off to mitigate risks of regression
* @run junit EarlyOrDelayedParsing
* @run junit/othervm -Djdk.net.url.delayParsing EarlyOrDelayedParsing
* @run junit/othervm -Djdk.net.url.delayParsing=true EarlyOrDelayedParsing
* @run junit/othervm -Djdk.net.url.delayParsing=false EarlyOrDelayedParsing
*/
import java.io.IOException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static java.lang.System.err;
import static org.junit.jupiter.api.Assertions.*;
public class EarlyOrDelayedParsing {
public final boolean EARLY_PARSING;
{
String value = System.getProperty("jdk.net.url.delayParsing", "false");
EARLY_PARSING = !value.isEmpty() && !Boolean.parseBoolean(value);
if (!EARLY_PARSING) {
// we will open the connection in that case.
// make sure no proxy is selected
ProxySelector.setDefault(new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
return List.of(Proxy.NO_PROXY);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
}
});
}
}
// Some characters that when included at the wrong place
// in the authority component, without being escaped, would
// cause an exception.
private static final String EXCLUDED_DELIMS = "<>\" ";
private static final String UNWISE = "{}|\\^`";
private static final String DELIMS = "[]/?#@";
// Test data used to test exceptions thrown by URL
// at some point, when constructed with some illegal input.
sealed interface URLArgTest
permits OneArgTest, TwoArgsTest, ThreeArgsTest, FourArgsTest {
// Some character that is expected to cause an exception
// at some point, and which this test case is built for
int character();
// An URL string containing the illegal character
String url();
// Some characters are already checked at construction
// time. They will cause an exception to be thrown,
// whether delayed parsing is activated or not.
// This method returns true if an exception is
// expected at construction time for this test case,
// even when delayed parsing is activated.
boolean early(int c);
// The URL scheme this test case is built for.
// Typically, one of "http", "https", "ftp"...
default String scheme() {
return scheme(url());
}
// Return the URL string of this test case, after
// substituting its scheme with the given scheme.
default String urlWithScheme(String scheme) {
String url = url();
int colon = url.indexOf(':');
String urlWithScheme = scheme + url.substring(colon);
return urlWithScheme;
}
// Which exception to expect when parsing is delayed
default boolean acceptDelayedException(Throwable exception) {
return exception instanceof MalformedURLException
|| exception instanceof UnknownHostException;
}
default String describe() {
return this.getClass().getSimpleName() + "(url=" + url() + ")";
}
static int port(String protocol) {
return switch (protocol) {
case "http" -> 80;
case "https" -> 443;
case "ftp" -> 21;
default -> -1;
};
}
static String scheme(String url) {
return url.substring(0, url.indexOf(':'));
}
}
// Test data for the one arg constructor
// public URL(String spec) throws MalformedURLException
sealed interface OneArgTest extends URLArgTest {
// Create a new test case identical to this one but
// with a different URL scheme
default OneArgTest withScheme(String scheme) {
String urlWithScheme = urlWithScheme(scheme);
if (this instanceof OfHost) {
return new OfHost(character(), urlWithScheme);
}
if (this instanceof OfUserInfo) {
return new OfUserInfo(character(), urlWithScheme);
}
throw new AssertionError("unexpected subclass: " + this.getClass());
}
@Override
default boolean early(int c) {
return this instanceof OfHost &&
(c < 31 || c == 127);
}
@Override
default boolean acceptDelayedException(Throwable exception) {
return URLArgTest.super.acceptDelayedException(exception)
|| "file".equalsIgnoreCase(scheme())
&& character() == '\\'
&& exception instanceof IOException;
}
record OfHost(int character, String url) implements OneArgTest { }
record OfUserInfo(int character, String url) implements OneArgTest { }
static OneArgTest ofHost(int c) {
return new OfHost(c, "http://local%shost/".formatted(Character.toString(c)));
}
static OneArgTest ofUserInfo(int c) {
return new OfUserInfo(c, "http://user%sinfo@localhost:9999/".formatted(Character.toString(c)));
}
}
// Test data for the two arg constructor
// public URL(URL context, String spec) throws MalformedURLException
sealed interface TwoArgsTest extends URLArgTest {
// Create a new test case identical to this one but
// with a different URL scheme
default TwoArgsTest withScheme(String scheme) {
String urlWithScheme = urlWithScheme(scheme);
if (this instanceof OfTwoArgsHost) {
return new OfTwoArgsHost(character(), urlWithScheme);
}
if (this instanceof OfTwoArgsUserInfo) {
return new OfTwoArgsUserInfo(character(), urlWithScheme);
}
throw new AssertionError("unexpected subclass: " + this.getClass());
}
@Override
default boolean early(int c) {
return this instanceof OfTwoArgsHost &&
(c < 31 || c == 127);
}
@Override
default boolean acceptDelayedException(Throwable exception) {
return URLArgTest.super.acceptDelayedException(exception)
|| "file".equalsIgnoreCase(scheme())
&& character() == '\\'
&& exception instanceof IOException;
}
record OfTwoArgsHost(int character, String url) implements TwoArgsTest { }
record OfTwoArgsUserInfo(int character, String url) implements TwoArgsTest { }
static TwoArgsTest ofHost(int c) {
return new OfTwoArgsHost(c, "http://local%shost/".formatted(Character.toString(c)));
}
static TwoArgsTest ofUserInfo(int c) {
return new OfTwoArgsUserInfo(c, "http://user%sinfo@localhost:9999/".formatted(Character.toString(c)));
}
static TwoArgsTest ofOneArgTest(OneArgTest test) {
if (test instanceof OneArgTest.OfHost) {
return ofHost(test.character());
} else if (test instanceof OneArgTest.OfUserInfo) {
return ofUserInfo(test.character());
}
throw new AssertionError("can't convert to TwoArgsTest: "
+ test.getClass());
}
}
// Test data for the three args constructor
// public URL(String scheme, String host, String file)
// throws MalformedURLException
sealed interface ThreeArgsTest extends URLArgTest {
// the host component
String host();
// the path + query components
String file();
// Create a new test case identical to this one but
// with a different URL scheme and port
default ThreeArgsTest withScheme(String scheme) {
String urlWithScheme = urlWithScheme(scheme);
if (this instanceof OfHostFile) {
return new OfHostFile(character(), host(), file(), urlWithScheme);
}
throw new AssertionError("unexpected subclass: " + this.getClass());
}
@Override
default boolean early(int c) {
return (c < 31 || c == 127 || c == '/');
}
@Override
default boolean acceptDelayedException(Throwable exception) {
return URLArgTest.super.acceptDelayedException(exception)
|| "file".equalsIgnoreCase(scheme())
&& exception instanceof IOException;
}
record OfHostFile(int character, String host, String file, String url)
implements ThreeArgsTest {
}
static ThreeArgsTest ofHostFile(int c) {
String host = "local%shost".formatted(Character.toString(c));
String url = "http://" + host + "/";
return new OfHostFile(c, host, "/", url);
}
}
// Test data for the four args constructor
// public URL(String scheme, String host, int port, String file)
// throws MalformedURLException
sealed interface FourArgsTest extends URLArgTest {
// the host component
String host();
// the port component
int port();
// the path + query components
String file();
// Create a new test case identical to this one but
// with a different URL scheme and port
default FourArgsTest withScheme(String scheme) {
String urlWithScheme = urlWithScheme(scheme);
if (this instanceof OfHostFilePort) {
int port = URLArgTest.port(scheme);
return new OfHostFilePort(character(), host(), port, file(), urlWithScheme);
}
throw new AssertionError("unexpected subclass: " + this.getClass());
}
@Override
default boolean early(int c) {
return (c < 31 || c == 127 || c == '/');
}
@Override
default boolean acceptDelayedException(Throwable exception) {
return URLArgTest.super.acceptDelayedException(exception)
|| "file".equalsIgnoreCase(scheme())
&& exception instanceof IOException;
}
record OfHostFilePort(int character, String host, int port, String file, String url)
implements FourArgsTest {
}
static FourArgsTest ofHostPortFile(int c) {
String host = "local%shost".formatted(Character.toString(c));
String url = "http://" + host + "/";
int port = URLArgTest.port(URLArgTest.scheme(url));
return new OfHostFilePort(c, host, port, "/", url);
}
}
// Generate test data for the URL one arg constructor, with variations
// of the host component.
static Stream<OneArgTest> oneArgHostTests() {
List<OneArgTest> tests = new ArrayList<>();
List<OneArgTest> urls = new ArrayList<>();
urls.addAll((UNWISE + EXCLUDED_DELIMS).chars()
.mapToObj(OneArgTest::ofHost).toList());
urls.addAll(IntStream.concat(IntStream.range(0, 31), IntStream.of(127))
.mapToObj(OneArgTest::ofHost).toList());
for (String scheme : List.of("http", "https", "ftp")) {
for (var test : urls) {
tests.add(test.withScheme(scheme));
}
}
return tests.stream();
}
// Generate test data for the URL one arg constructor, with variations
// of the user info component.
static Stream<OneArgTest> oneArgUserInfoTests() {
List<OneArgTest> tests = new ArrayList<>();
List<OneArgTest> urls = new ArrayList<>();
urls.addAll(IntStream.concat(IntStream.range(0, 31), IntStream.of(127))
.mapToObj(OneArgTest::ofUserInfo).toList());
urls.add(OneArgTest.ofUserInfo('\\'));
for (String scheme : List.of("http", "https", "ftp")) {
for (var test : urls) {
tests.add(test.withScheme(scheme));
}
}
return tests.stream();
}
// Test data with all variations for the URL one arg
// constructor (spec)
static Stream<OneArgTest> oneArgTests() {
return Stream.concat(oneArgHostTests(), oneArgUserInfoTests());
}
// Test data with all variations for the URL two arg
// constructor (URL, spec)
static Stream<TwoArgsTest> twoArgTests() {
return oneArgTests().map(TwoArgsTest::ofOneArgTest);
}
// Generate test data for the URL three arguments constructor
// (scheme, host, file)
static Stream<ThreeArgsTest> threeArgsTests() {
List<ThreeArgsTest> urls = new ArrayList<>();
urls.addAll((UNWISE + EXCLUDED_DELIMS + DELIMS).chars()
.mapToObj(ThreeArgsTest::ofHostFile).toList());
urls.addAll(IntStream.concat(IntStream.range(0, 31), IntStream.of(127))
.mapToObj(ThreeArgsTest::ofHostFile).toList());
List<ThreeArgsTest> tests = new ArrayList<>();
for (String scheme : List.of("http", "https", "ftp", "file")) {
for (var test : urls) {
tests.add(test.withScheme(scheme));
}
}
return tests.stream();
}
// Generate test data for the URL four arguments constructor
// (scheme, host, port, file)
static Stream<FourArgsTest> fourArgsTests() {
List<FourArgsTest> urls = new ArrayList<>();
urls.addAll((UNWISE + EXCLUDED_DELIMS + DELIMS).chars()
.mapToObj(FourArgsTest::ofHostPortFile).toList());
urls.addAll(IntStream.concat(IntStream.range(0, 31), IntStream.of(127))
.mapToObj(FourArgsTest::ofHostPortFile).toList());
List<FourArgsTest> tests = new ArrayList<>();
for (String scheme : List.of("http", "https", "ftp", "file")) {
for (var test : urls) {
tests.add(test.withScheme(scheme));
}
}
return tests.stream();
}
@ParameterizedTest
@MethodSource("oneArgTests")
public void testOneArgConstructor(OneArgTest test) throws Exception {
int c = test.character();
String url = test.url();
if (EARLY_PARSING || test.early(c)) {
err.println("Early parsing: " + test.describe());
var exception = assertThrows(MalformedURLException.class, () -> {
new URL(url);
});
err.println("Got expected exception: " + exception);
} else {
err.println("Delayed parsing: " + test.describe());
URL u = new URL(url);
var exception = assertThrows(IOException.class, () -> {
u.openConnection().connect();
});
if (!test.acceptDelayedException(exception)) {
err.println("unexpected exception type: " + exception);
throw exception;
}
err.println("Got expected exception: " + exception);
assertFalse(exception instanceof ConnectException);
}
}
@ParameterizedTest
@MethodSource("twoArgTests")
public void testTwoArgConstructor(TwoArgsTest test) throws Exception {
int c = test.character();
String url = test.url();
String scheme = URLArgTest.scheme(url);
URL u = new URL(scheme, null,"");
if (EARLY_PARSING || test.early(c)) {
err.println("Early parsing: " + test.describe());
var exception = assertThrows(MalformedURLException.class, () -> {
new URL(u, url);
});
err.println("Got expected exception: " + exception);
} else {
err.println("Delayed parsing: " + test.describe());
URL u2 = new URL(u, url);
var exception = assertThrows(IOException.class, () -> {
u2.openConnection().connect();
});
if (!test.acceptDelayedException(exception)) {
err.println("unexpected exception type: " + exception);
throw exception;
}
err.println("Got expected exception: " + exception);
assertFalse(exception instanceof ConnectException);
}
}
@ParameterizedTest
@MethodSource("threeArgsTests")
public void testThreeArgsConstructor(ThreeArgsTest test) throws Exception {
int c = test.character();
String url = test.url();
if (EARLY_PARSING || test.early(c)) {
err.println("Early parsing: " + url);
var exception = assertThrows(MalformedURLException.class, () -> {
new URL(test.scheme(), test.host(), test.file());
});
err.println("Got expected exception: " + exception);
} else {
err.println("Delayed parsing: " + url);
URL u = new URL(test.scheme(), test.host(), test.file());
var exception = assertThrows(IOException.class, () -> {
u.openConnection().connect();
});
if (!test.acceptDelayedException(exception)) {
err.println("unexpected exception type: " + exception);
throw exception;
}
err.println("Got expected exception: " + exception);
assertFalse(exception instanceof ConnectException);
}
}
@ParameterizedTest
@MethodSource("fourArgsTests")
public void testFourArgsConstructor(FourArgsTest test) throws Exception {
int c = test.character();
String url = test.url();
if (EARLY_PARSING || test.early(c)) {
err.println("Early parsing: " + url);
var exception = assertThrows(MalformedURLException.class, () -> {
new URL(test.scheme(), test.host(), test.port(), test.file());
});
err.println("Got expected exception: " + exception);
} else {
err.println("Delayed parsing: " + url);
URL u = new URL(test.scheme(), test.host(), test.port(), test.file());
var exception = assertThrows(IOException.class, () -> {
u.openConnection().connect();
});
if (!test.acceptDelayedException(exception)) {
err.println("unexpected exception type: " + exception);
throw exception;
}
err.println("Got expected exception: " + exception);
assertFalse(exception instanceof ConnectException);
}
}
}

View file

@ -0,0 +1,121 @@
/*
* Copyright (c) 1998, 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 4052976 7030649
* @summary Test URL.equals with anchors, and jar URLs
*/
import java.net.*;
public class Equals {
public static void main(String[] args) throws Exception {
anchors();
jarURLs();
}
static void anchors() throws Exception {
URL url1, url2;
url1 = new URL(null, "http://JavaSoft/Test#bar");
url2 = new URL(null, "http://JavaSoft/Test");
if (url1.equals(url2))
throw new RuntimeException("URL.equals fails with anchors");
if (url2.equals(url1))
throw new RuntimeException("URL.equals fails with anchors");
if (url1.equals(null))
throw new RuntimeException("URL.equals fails given null");
}
static final String HTTP_URL1A = "http://localhost/xyz";
static final String HTTP_URL1B = "http://LOCALHOST/xyz";
static final String FILE_URL1A = "file:///c:/foo/xyz";
static final String FILE_URL1B = "file:/c:/foo/xyz";
static void jarURLs() throws Exception {
int failed = 0;
failed = compareJarURLS(HTTP_URL1A, HTTP_URL1A, "!/abc", "!/abc", true);
failed = compareJarURLS(HTTP_URL1A, HTTP_URL1B, "!/abc", "!/abc", true);
failed = compareJarURLS(HTTP_URL1B, HTTP_URL1A, "!/", "!/", true);
failed = compareJarURLS(HTTP_URL1A, HTTP_URL1B, "!/abc", "!/", false);
failed = compareJarURLS(HTTP_URL1A, HTTP_URL1B, "!/abc", "!/xy", false);
failed = compareJarURLS(FILE_URL1A, FILE_URL1A, "!/abc", "!/abc", true);
failed = compareJarURLS(FILE_URL1A, FILE_URL1B, "!/abc", "!/abc", true);
failed = compareJarURLS(FILE_URL1A, FILE_URL1B, "!/", "!/", true);
failed = compareJarURLS(FILE_URL1A, FILE_URL1B, "!/abc", "!/", false);
failed = compareJarURLS(FILE_URL1A, FILE_URL1B, "!/abc", "!/xy", false);
failed = (new URL("jar:file://xzy!/abc")).equals(
new URL("file://xzy!/abc")) ? 1 : 0;
if (failed > 0)
throw new RuntimeException("Some jar URL tests failed. Check output");
}
static int compareJarURLS(String urlStr1, String urlStr2,
String entry1, String entry2,
boolean expectEqual) throws Exception {
int failed = 0;
URL url1 = new URL(urlStr1);
URL url2 = new URL(urlStr2);
if (!url1.equals(url2)) {
System.out.println("Urls are not equal, so the test cannot run.");
System.out.println("url1: " + url1 + ", url2:" + url2);
return 1;
}
URL jarUrl1 = new URL("jar:" + urlStr1 + entry1);
URL jarUrl2 = new URL("jar:" + urlStr2 + entry2);
jarUrl2.openConnection();
boolean equal = jarUrl1.equals(jarUrl2);
if (expectEqual && !equal) {
System.out.println("URLs should be equal, but are not. " +
jarUrl1 + ", " + jarUrl2);
failed++;
} else if (!expectEqual && equal) {
System.out.println("URLs should NOT be equal, but are. " +
jarUrl1 + ", " + jarUrl2);
failed++;
}
if (expectEqual) {
// hashCode MUST produce the same integer result for equal urls
int hash1 = jarUrl1.hashCode();
int hash2 = jarUrl2.hashCode();
if (hash1 != hash2) {
System.out.println("jarUrl1.hashCode = " + hash1);
System.out.println("jarUrl2.hashCode = " + hash2);
System.out.println("Equal urls should have same hashCode. " +
jarUrl1 + ", " + jarUrl2);
failed++;
}
}
return failed;
}
}

View file

@ -0,0 +1,100 @@
/*
* 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 4145315
* @library /test/lib
* @summary Test a read from nonexistant URL
* @run main GetContent
* @run main/othervm -Djava.net.preferIPv6Addresses GetContent
*/
import java.net.*;
import java.io.*;
import jdk.test.lib.net.URIBuilder;
public class GetContent 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 404 Not Found\r\n");
out.print("Connection: close\r\n");
out.print("Content-Type: text/html; charset=iso-8859-1\r\n");
out.print("\r\n");
out.flush();
out.print("<HTML><BODY>Sorry, page not found</BODY></HTML>");
out.flush();
// wait for client to read response - otherwise http
// client get error and re-establish connection
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
} finally {
try { ss.close(); } catch (IOException unused) {}
}
}
GetContent() throws Exception {
InetAddress loopback = InetAddress.getLoopbackAddress();
ss = new ServerSocket();
ss.bind(new InetSocketAddress(loopback, 0));
Thread thr = new Thread(this);
thr.start();
boolean error = true;
try {
java.net.URL url = URIBuilder.newBuilder()
.scheme("http")
.host(ss.getInetAddress())
.port(ss.getLocalPort())
.path("/no-such-name")
.toURL();
Object obj = url.openConnection(Proxy.NO_PROXY)
.getContent();
InputStream in = (InputStream) obj;
byte buff[] = new byte[200];
int len = in.read(buff);
} catch (IOException ex) {
error = false;
}
if (error)
throw new RuntimeException("No IOException generated.");
}
public static void main(String args[]) throws Exception {
new GetContent();
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2000, 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 4332284
* @summary URL.getPort() should not return -1
*
*/
import java.io.*;
import java.net.*;
public class GetDefaultPort {
public static void main(String args[]) throws Exception {
int p;
URL url = new URL ("http://www.sun.com");
if ((p=url.getDefaultPort ()) != 80)
throw new Exception ("getDefaultPort returned wrong value: "+p);
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 1998, 2013, 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.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
/*
* @test
* @bug 4135031
* @summary Test bootstrap problem when a URLStreamHandlerFactory is loaded
* by the application class loader.
* @modules java.base/sun.net.www.protocol.file
* @run main/othervm HandlerLoop
*/
public class HandlerLoop {
public static void main(String args[]) throws Exception {
URL.setURLStreamHandlerFactory(
new HandlerFactory("sun.net.www.protocol"));
URL url = new URL("file:///bogus/index.html");
System.out.println("url = " + url);
url.openConnection();
}
private static class HandlerFactory implements URLStreamHandlerFactory {
private String pkg;
HandlerFactory(String pkg) {
this.pkg = pkg;
}
public URLStreamHandler createURLStreamHandler(String protocol) {
String name = pkg + "." + protocol + ".Handler";
System.out.println("Loading handler class: " + name);
// Loading this dummy class demonstrates the bootstrap
// problem as the stream handler factory will be reentered
// over and over again if the application class loader
// shares the same stream handler factory.
new Dummy();
try {
Class<?> c = Class.forName(name);
return (URLStreamHandler)c.getDeclaredConstructor().newInstance();
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
NoSuchMethodException |
InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
private static class Dummy {
}
}

View file

@ -0,0 +1,95 @@
/*
* 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.net.MalformedURLException;
import java.net.URL;
import java.util.function.Consumer;
/*
* @test
* @bug 8075139
* @summary Basic test for java.protocol.handler.pkgs
* @compile handlers/foo/Handler.java handlers/bar/Handler.java HandlersPkgPrefix.java
* @run main/othervm HandlersPkgPrefix
*/
public class HandlersPkgPrefix {
static final Consumer<Result> KNOWN = r -> {
if (r.exception != null)
throw new RuntimeException("Unexpected exception " + r.exception);
String p = r.url.getProtocol();
if (!r.protocol.equals(p))
throw new RuntimeException("Expected:" + r.protocol + ", got:" + p);
};
static final Consumer<Result> UNKNOWN = r -> {
if (r.url != null)
throw new RuntimeException("Unexpected url:" + r.url);
if (!(r.exception instanceof MalformedURLException))
throw new RuntimeException("Expected MalformedURLException, got:"
+ r.exception);
};
public static void main(String[] args) {
withPrefix("unknown", "", UNKNOWN);
withPrefix("unknown", "handlers", UNKNOWN);
withPrefix("foo", "", UNKNOWN);
withPrefix("foo", "xxx|yyy|zzz", UNKNOWN);
withPrefix("foo", "||||", UNKNOWN);
withPrefix("foo", "|a|b|c|handlers", KNOWN);
withPrefix("bar", "", UNKNOWN);
withPrefix("bar", "x.y.z|y.y.y|z.z.z", UNKNOWN);
withPrefix("bar", " x.y.z | y.y.y | z.z.z| | ", UNKNOWN);
withPrefix("bar", "| a | b | c | handlers | d | e", KNOWN);
}
static void withPrefix(String protocol, String pkgPrefix,
Consumer<Result> resultChecker) {
System.out.println("Testing, " + protocol + ", " + pkgPrefix);
// The long standing implementation behavior is that the
// property is read multiple times, not cached.
System.setProperty("java.protocol.handler.pkgs", pkgPrefix);
URL url = null;
Exception exception = null;
try {
url = new URL(protocol + "://");
} catch (MalformedURLException x) {
exception = x;
}
resultChecker.accept(new Result(protocol, url, exception));
}
static class Result {
final String protocol;
final URL url;
final Exception exception;
Result(String protocol, URL url, Exception exception) {
this.protocol = protocol;
this.url = url;
this.exception = exception;
}
}
}

View file

@ -0,0 +1,37 @@
/*
* 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 handlers.bar;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
}

View file

@ -0,0 +1,37 @@
/*
* 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 handlers.foo;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
}

View file

@ -0,0 +1,39 @@
/*
* 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 4091093
* @summary Test URL.hashCode with null host
*
*/
import java.net.*;
public class HashCode {
public static void main(String[] args) throws Exception {
URL url = new URL("http", null, 80, "test");
int code = url.hashCode();
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2017, 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.
*/
import handlers.jar.Handler;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import jdk.test.lib.util.JarBuilder;
/*
* @test
* @bug 8174151
* @summary Test for java.protocol.handler.pkgs with jar protocol handler
* @library /test/lib/
* @build jdk.test.lib.util.JarBuilder
* @compile handlers/jar/Handler.java
* @run main/othervm -Djava.protocol.handler.pkgs=handlers JarHandlerPkgPrefix
*/
public class JarHandlerPkgPrefix {
static void createJar(Path p) throws Exception {
JarBuilder jb = new JarBuilder(p.toString());
jb.addEntry("resource.txt", "CONTENTS".getBytes());
jb.build();
}
public static void main(String[] args) throws Exception {
Path jarPath = Paths.get(System.getProperty("user.dir", "."), "test.jar");
try {
createJar(jarPath);
URL j = new URL("jar:file:" + jarPath.toString() + "!/");
URLClassLoader ucl = new URLClassLoader(new URL[]{j});
ucl.findResource("resource.txt");
URL r = new URL("jar:file:" + jarPath.toString() + "!/resource.txt");
if (!Handler.URLS.contains(r))
throw new AssertionError("jar: URL handler not invoked");
}
finally {
Files.delete(jarPath);
}
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright (c) 2017, 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 handlers.jar;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Handler extends URLStreamHandler {
public static Set<URL> URLS = Collections.synchronizedSet(new HashSet<>());
@Override
protected URLConnection openConnection(URL u) throws IOException {
URLS.add(u);
return null;
}
}

View file

@ -0,0 +1,41 @@
/*
* 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 8147962
* @summary Verify URLs with upper-case protocols parse correctly in any
* locale
* @run main/othervm LocaleDependentURLTest
*/
import java.net.*;
import java.util.Locale;
public class LocaleDependentURLTest {
public static void main(String args[]) throws MalformedURLException {
for (Locale locale : Locale.getAvailableLocales()) {
Locale.setDefault(locale);
new URL("FILE:///TMP/X");
}
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 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 8217364
* @summary Custom URLStreamHandler for jrt or file protocol can override default handler
* @modules java.base/java.net:open
* @run main/othervm NonOverridableHandlerFactory
*/
import java.io.*;
import java.net.*;
public class NonOverridableHandlerFactory implements URLStreamHandlerFactory {
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
return new NonOverridableHandler();
}
private static class NonOverridableHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
throw new RuntimeException("CustomURLStreamHandler used for " + u);
}
}
public static void main(String[] args) {
URL.setURLStreamHandlerFactory(new NonOverridableHandlerFactory());
for (String protocol : new String[] {"file", "jrt"}) {
String urlString = protocol + ":///test/somefile";
try {
new URL(urlString).openConnection();
} catch(RuntimeException r) {
throw r;
} catch(Throwable t) {
// possible jrt initialization issue on exploded binary image etc.
System.out.println("encountered: " + t +
"(testing: " + urlString + ")");
}
System.out.println("Default URLStreamHandler used for " + urlString);
}
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2004, 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 5086348
* @summary URL.openConnection(Proxy.NO_PROXY) throws NULLPointerException
* @run main/othervm OpenConnection
*/
import java.io.*;
import java.net.*;
public class OpenConnection {
public static void main(String[] args) throws IOException {
URL u = new URL("http://foo.bar.baz/");
try {
// Will throw NullPointerException if not fixed
URLConnection con = u.openConnection(Proxy.NO_PROXY);
} catch (UnknownHostException ex) {
// That's OK, we were expecting that!
return;
}
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 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 4064962 8202708
* @summary openStream should work even when not using proxies and
* UnknownHostException is thrown as expected.
* @comment For testing of non-local file URLs with the legacy FTP
* fallback feature enabled, see NonLocalFtpFallback.
*/
import java.io.*;
import java.net.*;
public class OpenStream {
private static final String badHttp = "http://foo.bar.baz/";
public static void main(String[] args) throws IOException {
testHttp();
}
static void testHttp() throws IOException {
checkThrows(badHttp);
}
static void checkThrows(String url) throws IOException {
URL u = new URL(url);
try {
InputStream in = u.openConnection(Proxy.NO_PROXY).getInputStream();
} catch (UnknownHostException x) {
System.out.println("UnknownHostException is thrown as expected.");
return;
}
throw new RuntimeException("Expected UnknownHostException to be " +
"thrown for " + url);
}
}

View file

@ -0,0 +1,56 @@
/*
* 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 4480308
* @summary URL is not throwinng exception for wrong URL format.
*
*/
import java.net.*;
public class ParseAuthority {
public static void main(String args[]) throws Exception {
try {
URL u1 = new URL("http://[fe80::]9999/path1/path2/");
throw new RuntimeException("URL parser didn't catch" +
" invalid authority field");
} catch (MalformedURLException me) {
if (!me.getMessage().startsWith("Invalid authority field")) {
throw new RuntimeException("URL parser didn't catch" +
" invalid authority field");
}
}
try {
URL u2 = new URL("http://[www.sun.com]:9999/path1/path2/");
throw new RuntimeException("URL parser didn't catch" +
" invalid host");
} catch (MalformedURLException me) {
if (!me.getMessage().startsWith("Invalid host")) {
throw new RuntimeException("URL parser didn't catch" +
" invalid host");
}
}
}
}

View file

@ -0,0 +1,41 @@
/*
* 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 4255229
* @summary URLStreamHandler.parseURL error
*
*/
import java.io.*;
import java.net.*;
public class ParseURL {
public static void main(String args[]) throws MalformedURLException {
String url = new URL(new URL("http://cnn.com"), "index.html").toExternalForm();
if (url.equalsIgnoreCase("http://cnn.com/index.html")) {
System.err.println("Success!!");
} else {
throw new RuntimeException("The result is "+url+", it should be http://cnn.com/index.html");
}
}
}

View file

@ -0,0 +1,240 @@
/*
* Copyright (c) 2003, 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
* @bug 4920526
* @summary Needs per connection proxy support for URLs
* @library /test/lib
* @compile PerConnectionProxy.java
* @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 PerConnectionProxy
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
public class PerConnectionProxy {
static HttpServer server;
public static void main(String[] args) {
try {
InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
server = HttpServer.create(new InetSocketAddress(loopbackAddress, 0), 10, "/", new PerConnectionProxyHandler());
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
ProxyServer pserver = new ProxyServer(loopbackAddress, server.getAddress().getPort());
// start proxy server
new Thread(pserver).start();
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(server.getAddress().getPort())
.toURLUnchecked();
// for non existing proxy expect an IOException
try {
InetSocketAddress isa = InetSocketAddress.createUnresolved("inexistent", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, isa);
HttpURLConnection urlc = (HttpURLConnection)url.openConnection (proxy);
InputStream is = urlc.getInputStream ();
is.close();
throw new RuntimeException("non existing per connection proxy should lead to IOException");
} catch (IOException ioex) {
// expected
}
// for NO_PROXY, expect direct connection
try {
HttpURLConnection urlc = (HttpURLConnection)url.openConnection (Proxy.NO_PROXY);
int respCode = urlc.getResponseCode();
urlc.disconnect();
} catch (IOException ioex) {
throw new RuntimeException("direct connection should succeed :"+ioex.getMessage());
}
// for a normal proxy setting expect to see connection
// goes through that proxy
try {
InetSocketAddress isa = InetSocketAddress.createUnresolved(
loopbackAddress.getHostAddress(),
pserver.getPort());
Proxy p = new Proxy(Proxy.Type.HTTP, isa);
HttpURLConnection urlc = (HttpURLConnection)url.openConnection (p);
int respCode = urlc.getResponseCode();
urlc.disconnect();
} catch (IOException ioex) {
throw new RuntimeException("connection through a local proxy should succeed :"+ioex.getMessage());
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (server != null) {
server.stop(1);
}
}
}
static class ProxyServer extends Thread {
private static ServerSocket ss = null;
// client requesting for a tunnel
private Socket clientSocket = null;
/*
* Origin server's address and port that the client
* wants to establish the tunnel for communication.
*/
private InetAddress serverInetAddr;
private int serverPort;
public ProxyServer(InetAddress server, int port) throws IOException {
serverInetAddr = server;
serverPort = port;
ss = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
}
public void run() {
try {
clientSocket = ss.accept();
processRequests();
} catch (Exception e) {
System.out.println("Proxy Failed: " + e);
e.printStackTrace();
try {
ss.close();
}
catch (IOException excep) {
System.out.println("ProxyServer close error: " + excep);
excep.printStackTrace();
}
}
}
private void processRequests() throws Exception {
// connection set to the tunneling mode
Socket serverSocket = new Socket(serverInetAddr, serverPort);
ProxyTunnel clientToServer = new ProxyTunnel(
clientSocket, serverSocket);
ProxyTunnel serverToClient = new ProxyTunnel(
serverSocket, clientSocket);
clientToServer.start();
serverToClient.start();
System.out.println("Proxy: Started tunneling.......");
clientToServer.join();
serverToClient.join();
System.out.println("Proxy: Finished tunneling........");
clientToServer.close();
serverToClient.close();
}
/**
***************************************************************
* helper methods follow
***************************************************************
*/
public int getPort() {
return ss.getLocalPort();
}
/*
* This inner class provides unidirectional data flow through the sockets
* by continuously copying bytes from the input socket onto the output
* socket, until both sockets are open and EOF has not been received.
*/
static class ProxyTunnel extends Thread {
Socket sockIn;
Socket sockOut;
InputStream input;
OutputStream output;
public ProxyTunnel(Socket sockIn, Socket sockOut)
throws Exception {
this.sockIn = sockIn;
this.sockOut = sockOut;
input = sockIn.getInputStream();
output = sockOut.getOutputStream();
}
public void run() {
int BUFFER_SIZE = 400;
byte[] buf = new byte[BUFFER_SIZE];
int bytesRead = 0;
int count = 0; // keep track of the amount of data transfer
try {
while ((bytesRead = input.read(buf)) >= 0) {
output.write(buf, 0, bytesRead);
output.flush();
count += bytesRead;
}
} catch (IOException e) {
/*
* The peer end has closed the connection
* we will close the tunnel
*/
close();
}
}
public void close() {
try {
if (!sockIn.isClosed())
sockIn.close();
if (!sockOut.isClosed())
sockOut.close();
} catch (IOException ignored) { }
}
}
}
}
class PerConnectionProxyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
exchange.sendResponseHeaders(200, 0);
} catch (IOException e) {
}
try(PrintWriter pw = new PrintWriter(exchange.getResponseBody(), false, Charset.forName("UTF-8"))) {
pw.print("Hello .");
}
}
}

View file

@ -0,0 +1,39 @@
/*
* 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.
*/
import java.io.*;
/*
* @test
* @bug 4073525
* @summary Test URL parsing of protocols
*
*/
import java.net.*;
public class Protocol {
public static void main(String args[]) throws Exception {
URL url = new URL("file://bogus/index.html");
URL url2 = new URL(url, "here.pl?notaspec:atall");
}
}

View file

@ -0,0 +1,114 @@
/*
* Copyright (c) 2018, 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.IOException;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.concurrent.CountDownLatch;
/*
* @test
* @bug 8213942
* @summary URLStreamHandler initialization race
* @modules java.base/java.net:open
* @run main/othervm RacyHandler
* @run main/othervm RacyHandler
* @run main/othervm RacyHandler
*/
/*
* This test makes reasonable effort to reproduce the race.
* Run repeatedly to ensure correctness.
*/
public class RacyHandler {
static volatile boolean factorySet = false;
static int NUM_THREADS = 2;
static CountDownLatch cdl = new CountDownLatch(NUM_THREADS + 1);
public static void main(String[] args) {
RacyHandler tester = new RacyHandler();
tester.runTest();
}
public void runTest() {
new Thread(() -> {
try {
cdl.await();
URL.setURLStreamHandlerFactory(proto -> new CustomHttpHandler());
factorySet = true;
} catch (Exception ignore) { }
}).start();
cdl.countDown();
for (int i = 0; i < NUM_THREADS; i++) {
new Thread(() -> {
try {
cdl.await();
while (!factorySet) {
// trigger URL class load
getURLStreamHandler();
}
} catch (Exception ignore) { }
}).start();
cdl.countDown();
}
// wait for the factory to be set
while (!factorySet) { }
// The sleep seems to help trigger the failure
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
URLStreamHandler httpHandler = getURLStreamHandler();
System.out.println("After setting factory URL handlers: http " + httpHandler);
if (!(httpHandler instanceof CustomHttpHandler))
throw new RuntimeException("FAILED: Incorrect handler type");
}
/*
* This is just so we can see what we get for the URLStreamHandler back
* from the factory to verify whether it really is using our Handler
* or something else...
*/
public URLStreamHandler getURLStreamHandler() {
try {
Method method = URL.class.getDeclaredMethod("getURLStreamHandler",
String.class);
method.setAccessible(true);
return (URLStreamHandler) method.invoke(null, "http");
} catch (Exception e) {
return null;
}
}
class CustomHttpHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2003, 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 4709003
* @summary incompatibility between jdk 1.3 and jdk1.4 for URL(URL context, String spec)
*/
import java.net.URI;
import java.net.URL;
public class RelativePath {
public static void main(String[] args) throws Exception {
String uri1 = "http://h/../d1/";
String uri2 = "../d/i.htm";
String expected = "http://h/../d/i.htm";
URI uri = new URI(uri1);
String s1 = uri.resolve(uri2).toString();
URL url = new URL(uri1);
URL url2 = new URL(url, uri2);
String s2 = url2.toString();
if (!(expected.equalsIgnoreCase(s1)))
throw new RuntimeException("URI.resolve didn't return expected result [" + s1 + " versus " + expected + "]");
if (!(expected.equalsIgnoreCase(s2)))
throw new RuntimeException("URL(url, String) didn't return expected result [" + s2 + " versus " + expected + "]");
}
}

View file

@ -0,0 +1,40 @@
/*
* 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 4148044
* @summary test a URL constructor on relative URLs
*/
import java.net.URL;
public class RelativeURL {
public static void main(String[] args) throws Exception {
URL base = new URL("http", "Layout", -1, "example1.html");
URL derived = new URL(base, "Graph.html");
base = new URL("http", "www.sun.com", -1, "index.html");
derived = new URL(base, "www.sun.com/index.html");
}
}

View file

@ -0,0 +1,43 @@
/*
* 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 4481537
* @summary URL(URL context, String spec) hangs with specific input.
*
*/
import java.net.*;
public class RelativeURLTest {
public static void main(String[] args) throws Exception {
URL base = new URL("file:./");
URL url = new URL(base, "../images/dummy/../././foo.gif");
if (!url.toString().equals("file:../images/foo.gif")) {
throw new RuntimeException("relative URL resolution failed " +
"expect: file:../images/foo.gif " +
"got: "+url.toString());
}
}
}

View file

@ -0,0 +1,59 @@
/*
* 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 4337842
* @summary URL.readObject should restore transient fields
*/
import java.net.*;
import java.io.*;
public class RestoreURL {
public static void main(String[] args) throws Exception {
URL origUrl = new URL( "http://localhost/my_path?my_query" );
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject( origUrl );
oos.close();
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( out.toByteArray() ));
URL restoredUrl = (URL)ois.readObject();
ois.close();
String path = restoredUrl.getPath();
String query = restoredUrl.getQuery();
if ((path == null) || !path.equals(origUrl.getPath())) {
throw new Exception("path not restored");
}
if ((query ==null) || !query.equals(origUrl.getQuery())) {
throw new Exception("query not restored");
}
}
}

View file

@ -0,0 +1,45 @@
/*
* 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 4135031
* @summary Test new URL contructors that allow specification of a
* URLStreamHandler protocol handler.
* @modules java.base/sun.net.www.protocol.file
*/
import java.net.*;
public class SpecifyHandler {
public static void main(String args[]) throws Exception {
URLStreamHandler handler = getFileHandler();
URL url1 = new URL("file", "", -1, "/bogus/index.html", handler);
URL url2 = new URL(null, "file://bogus.index.html", handler);
}
private static URLStreamHandler getFileHandler() throws Exception {
Class c = Class.forName("sun.net.www.protocol.file.Handler");
return (URLStreamHandler)c.newInstance();
}
}

View file

@ -0,0 +1,655 @@
/*
* Copyright (c) 2001, 2013, 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
* @summary Unit test for java.net.URL (Based on the URI tests that is authored by Mark Reinhold)
* @bug 4496251
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.MalformedURLException;
public class Test {
static PrintStream out = System.out;
static int testCount = 0;
// Properties that we check
static final int PARSEFAIL = 1 << 0;
static final int PROTOCOL = 1 << 1;
static final int USERINFO = 1 << 2;
static final int HOST = 1 << 3;
static final int PORT = 1 << 4;
static final int PATH = 1 << 5;
static final int QUERY = 1 << 6;
static final int REF = 1 << 7;
String input;
URL url = null;
URL originalURL;
URL base = null; // Base for resolution/relativization
String op = null; // Op performed if url != originalURL
int checked = 0; // Mask for checked properties
int failed = 0; // Mask for failed properties
Exception exc = null;
private Test(String s) {
testCount++;
input = s;
try {
url = new URL(s);
} catch (MalformedURLException x) {
exc = x;
}
originalURL = url;
}
static Test test(String s) {
return new Test(s);
}
private Test(String s, boolean xxx) {
testCount++;
try {
url = new URL(s);
} catch (Exception x) {
exc = x;
}
if (url != null)
input = url.toString();
originalURL = url;
}
static Test test(URL base, String spec) {
return new Test(base, spec);
}
private Test(URL base, String spec) {
testCount++;
try {
url = new URL(base, spec);
} catch (Exception x) {
exc = x;
}
if (url != null)
input = url.toString();
originalURL = url;
}
static Test test(String protocol, String host, int port, String file) {
return new Test(protocol, host, port, file);
}
private Test(String protocol, String host, int port, String file) {
testCount++;
try {
url = new URL(protocol, host, port, file);
} catch (Exception x) {
exc = x;
}
if (url != null)
input = url.toString();
originalURL = url;
}
boolean parsed() {
return url != null;
}
boolean resolved() {
return base != null;
}
URL url() {
return url;
}
// Operations on Test instances
//
// These are short so as to make test cases compact.
//
// s Scheme
// u User info
// h Host
// n port Number
// p Path
// q Query
// f Fragment
//
// rslv Resolve against given base
// rtvz Relativize
// psa Parse server Authority
// norm Normalize
//
// x Check that parse failed as expected
// z End -- ensure that unchecked components are null
private boolean check1(int prop) {
checked |= prop;
if (!parsed()) {
failed |= prop;
return false;
}
return true;
}
private void check2(String s, String ans, int prop) {
if (s == null && ans == null)
return;
if ((s == null) || !s.equals(ans))
failed |= prop;
}
Test s(String s) {
if (check1(PROTOCOL)) check2(url.getProtocol(), s, PROTOCOL);
return this;
}
Test u(String s) {
if (check1(USERINFO)) check2(url.getUserInfo(), s, USERINFO);
return this;
}
Test h(String s) {
if (check1(HOST)) check2(url.getHost(), s, HOST);
return this;
}
Test n(int n) {
checked |= PORT;
if (!parsed() || (url.getPort() != n))
failed |= PORT;
return this;
}
Test p(String s) {
if (check1(PATH)) check2(url.getPath(), s, PATH);
return this;
}
Test q(String s) {
if (check1(QUERY)) check2(url.getQuery(), s, QUERY);
return this;
}
Test f(String s) {
if (check1(REF)) check2(url.getRef(), s, REF);
return this;
}
Test x() {
checked |= PARSEFAIL;
if (parsed())
failed |= PARSEFAIL;
return this;
}
private void checkEmpty(String s, int prop) {
if (((checked & prop) == 0) && (s != null))
failed |= prop;
}
// Check that unchecked component properties are not defined,
// and report any failures
Test z() {
if (!parsed()) {
report();
return this;
}
checkEmpty(url.getProtocol(), PROTOCOL);
checkEmpty(url.getUserInfo(), USERINFO);
checkEmpty(url.getHost(), HOST);
if (((checked & PORT) == 0) && (url.getPort() != -1)) failed |= PORT;
checkEmpty(url.getPath(), PATH);
checkEmpty(url.getQuery(), QUERY);
checkEmpty(url.getRef(), REF);
report();
return this;
}
// Summarization and reporting
static void header(String s) {
out.println();
out.println();
out.println("-- " + s + " --");
}
static void show(String prefix, MalformedURLException x) {
out.println(prefix + ": " + x.getMessage());
}
private void summarize() {
out.println();
StringBuffer sb = new StringBuffer();
if (input.length() == 0)
sb.append("\"\"");
else
sb.append(input);
if (base != null) {
sb.append(" ");
sb.append(base);
}
if (!parsed()) {
String s = (((checked & PARSEFAIL) != 0)
? "Correct exception" : "UNEXPECTED EXCEPTION");
if (exc instanceof MalformedURLException)
show(s, (MalformedURLException)exc);
else {
out.println(sb.toString());
out.print(s + ": ");
exc.printStackTrace(out);
}
} else {
if (url != originalURL) {
sb.append(" ");
sb.append(op);
sb.append(" --> ");
sb.append(url);
}
out.println(sb.toString());
}
}
static void show(String n, String v) {
out.println(" " + n + " = ".substring(n.length()) + v);
}
public static void show(URL u) {
show("scheme", u.getProtocol());
show("authority", u.getAuthority());
show("userInfo", u.getUserInfo());
show("host", u.getHost());
show("port", "" + u.getPort());
show("path", u.getPath());
show("query", u.getQuery());
show("ref", u.getRef());
}
private void report() {
summarize();
if (failed == 0) return;
StringBuffer sb = new StringBuffer();
sb.append("FAIL:");
if ((failed & PARSEFAIL) != 0) sb.append(" parsefail");
if ((failed & PROTOCOL) != 0) sb.append(" scheme");
if ((failed & USERINFO) != 0) sb.append(" userinfo");
if ((failed & HOST) != 0) sb.append(" host");
if ((failed & PORT) != 0) sb.append(" port");
if ((failed & PATH) != 0) sb.append(" path");
if ((failed & QUERY) != 0) sb.append(" query");
if ((failed & REF) != 0) sb.append(" fragment");
out.println(sb.toString());
if (url != null) show(url);
throw new RuntimeException("Test failed");
}
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;
}
}
// -- Tests --
static void rfc2396() {
header("RFC2396: Basic examples");
if (hasFtp())
test("ftp://ftp.is.co.za/rfc/rfc1808.txt")
.s("ftp").h("ftp.is.co.za").p("/rfc/rfc1808.txt").z();
test("http://www.math.uio.no/faq/compression-faq/part1.html")
.s("http").h("www.math.uio.no").p("/faq/compression-faq/part1.html").z();
test("http://www.w3.org/Addressing/")
.s("http").h("www.w3.org").p("/Addressing/").z();
if (hasFtp())
test("ftp://ds.internic.net/rfc/")
.s("ftp").h("ds.internic.net").p("/rfc/").z();
test("http://www.ics.uci.edu/pub/ietf/url/historical.html#WARNING")
.s("http").h("www.ics.uci.edu").p("/pub/ietf/url/historical.html")
.f("WARNING").z();
test("http://www.ics.uci.edu/pub/ietf/url/#Related")
.s("http").h("www.ics.uci.edu").p("/pub/ietf/url/")
.f("Related").z();
test("file:/home/someone/dir1/dir2/file").s("file").h("").p("/home/someone/dir1/dir2/file").z();
header("RFC2396: Normal relative-URL examples (appendix C)");
URL base = (test("http://a/b/c/d;p?q")
.s("http").h("a").p("/b/c/d;p").q("q").z().url());
// g:h g:h
// test(base, "http:h").s("g").p("h").z();
// g http://a/b/c/g
test(base, "g").s("http").h("a").p("/b/c/g").z();
// ./g http://a/b/c/g
test(base, "./g").s("http").h("a").p("/b/c/g").z();
// g/ http://a/b/c/g/
test(base, "g/").s("http").h("a").p("/b/c/g/").z();
// /g http://a/g
test(base, "/g").s("http").h("a").p("/g").z();
// //g http://g
test(base,"//g").s("http").h("g").p("").z();
// ?y http://a/b/c/?y
test(base, "?y").s("http").h("a").p("/b/c/").q("y").z();
// g?y http://a/b/c/g?y
test(base, "g?y").s("http").h("a").p("/b/c/g").q("y").z();
// #s (current document)#s
// DEVIATION: Lone fragment parses as relative URL with empty path,
// and resolves without removing the last segment of the base path.
// test(base,"#s").s("http").h("a").p("/b/c/d;p").f("s").z();
test(base,"#s").s("http").h("a").p("/b/c/d;p").q("q").f("s").z();
// g#s http://a/b/c/g#s
test(base, "g#s").s("http").h("a").p("/b/c/g").f("s").z();
// g?y#s http://a/b/c/g?y#s
test(base,"g?y#s").s("http").h("a").p("/b/c/g").q("y").f("s").z();
// ;x http://a/b/c/;x
test(base,";x").s("http").h("a").p("/b/c/;x").z();
// g;x http://a/b/c/g;x
test(base,"g;x").s("http").h("a").p("/b/c/g;x").z();
// g;x?y#s http://a/b/c/g;x?y#s
test(base,"g;x?y#s").s("http").h("a").p("/b/c/g;x").q("y").f("s").z();
// . http://a/b/c/
test(base,".").s("http").h("a").p("/b/c/").z();
// ./ http://a/b/c/
test(base,"./").s("http").h("a").p("/b/c/").z();
// .. http://a/b/
test(base,"..").s("http").h("a").p("/b/").z();
// ../ http://a/b/
test(base,"../").s("http").h("a").p("/b/").z();
// ../g http://a/b/g
test(base,"../g").s("http").h("a").p("/b/g").z();
// ../.. http://a/
test(base,"../..").s("http").h("a").p("/").z();
// ../../ http://a/
test(base,"../../").s("http").h("a").p("/").z();
// ../../g http://a/g
test(base,"../../g").s("http").h("a").p("/g").z();
// http://u@s1/p1 http://s2/p2
test(test("http://u:p@s1/p1").url(),"http://s2/p2")
.s("http").h("s2").u(null).p("/p2").z();
header("RFC2396: Abnormal relative-URL examples (appendix C)");
// ../../../g = http://a/../g
test(base,"../../../g").s("http").h("a").p("/../g").z();
// ../../../../g = http://a/../../g
test(base, "../../../../g").s("http").h("a").p("/../../g").z();
// /./g = http://a/./g
test(base,"/./g").s("http").h("a").p("/./g").z();
// /../g = http://a/../g
test(base,"/../g").s("http").h("a").p("/../g").z();
// g. = http://a/b/c/g.
test(base,"g.").s("http").h("a").p("/b/c/g.").z();
// .g = http://a/b/c/.g
test(base,".g").s("http").h("a").p("/b/c/.g").z();
// g.. = http://a/b/c/g..
test(base,"g..").s("http").h("a").p("/b/c/g..").z();
// ..g = http://a/b/c/..g
test(base,"..g").s("http").h("a").p("/b/c/..g").z();
// ./../g = http://a/b/g
test(base,"./../g").s("http").h("a").p("/b/g").z();
// ./g/. = http://a/b/c/g/
test(base,"./g/.").s("http").h("a").p("/b/c/g/").z();
// g/./h = http://a/b/c/g/h
test(base,"g/./h").s("http").h("a").p("/b/c/g/h").z();
// g/../h = http://a/b/c/h
test(base,"g/../h").s("http").h("a").p("/b/c/h").z();
// g;x=1/./y = http://a/b/c/g;x=1/y
test(base,"g;x=1/./y").s("http").h("a").p("/b/c/g;x=1/y").z();
// g;x=1/../y = http://a/b/c/y
test(base,"g;x=1/../y").s("http").h("a").p("/b/c/y").z();
// g?y/./x = http://a/b/c/g?y/./x
test(base,"g?y/./x").s("http").h("a").p("/b/c/g").q("y/./x").z();
// g?y/../x = http://a/b/c/g?y/../x
test(base,"g?y/../x").s("http").h("a").p("/b/c/g").q("y/../x").z();
// g#s/./x = http://a/b/c/g#s/./x
test(base,"g#s/./x").s("http").h("a").p("/b/c/g").f("s/./x").z();
// g#s/../x = http://a/b/c/g#s/../x
test(base,"g#s/../x").s("http").h("a").p("/b/c/g").f("s/../x").z();
// http:g = http:g
// test(base,"http:g").s("http").p("g").z();
}
static void ip() {
header("IP addresses");
test("http://1.2.3.4:5")
.s("http").h("1.2.3.4").n(5).p("").z();
// From RFC2732
test("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html")
.s("http").h("[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]")
.n(80).p("/index.html").z();
test("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210%12]:80/index.html")
.s("http").h("[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210%12]")
.n(80).p("/index.html").z();
test("http://[1080:0:0:0:8:800:200C:417A]/index.html")
.s("http").h("[1080:0:0:0:8:800:200C:417A]").p("/index.html").z();
test("http://[1080:0:0:0:8:800:200C:417A%1]/index.html")
.s("http").h("[1080:0:0:0:8:800:200C:417A%1]").p("/index.html").z();
test("http://[3ffe:2a00:100:7031::1]")
.s("http").h("[3ffe:2a00:100:7031::1]").p("").z();
test("http://[1080::8:800:200C:417A]/foo")
.s("http").h("[1080::8:800:200C:417A]").p("/foo").z();
test("http://[::192.9.5.5]/ipng")
.s("http").h("[::192.9.5.5]").p("/ipng").z();
test("http://[::192.9.5.5%interface]/ipng")
.s("http").h("[::192.9.5.5%interface]").p("/ipng").z();
test("http://[::FFFF:129.144.52.38]:80/index.html")
.s("http").h("[::FFFF:129.144.52.38]").n(80).p("/index.html").z();
test("http://[2010:836B:4179::836B:4179]")
.s("http").h("[2010:836B:4179::836B:4179]").p("").z();
// From RFC2373
test("http://[FF01::101]")
.s("http").h("[FF01::101]").p("").z();
test("http://[::1]")
.s("http").h("[::1]").p("").z();
test("http://[::]")
.s("http").h("[::]").p("").z();
test("http://[::%hme0]")
.s("http").h("[::%hme0]").p("").z();
test("http://[0:0:0:0:0:0:13.1.68.3]")
.s("http").h("[0:0:0:0:0:0:13.1.68.3]").p("").z();
test("http://[0:0:0:0:0:FFFF:129.144.52.38]")
.s("http").h("[0:0:0:0:0:FFFF:129.144.52.38]").p("").z();
test("http://[0:0:0:0:0:FFFF:129.144.52.38%33]")
.s("http").h("[0:0:0:0:0:FFFF:129.144.52.38%33]").p("").z();
test("http://[::13.1.68.3]")
.s("http").h("[::13.1.68.3]").p("").z();
test("http://[::13.1.68.3]:")
.s("http").h("[::13.1.68.3]").p("").z();
// Error cases
test("http://[ff01:234/foo").x().z();
test("http://[ff01:234:zzz]/foo").x().z();
test("http://[foo]").x().z();
test("http://[]").x().z();
test("http://[129.33.44.55]").x().z();
test("http://[ff:ee:dd::cc:bb::aa:9:8]").x().z();
test("http://[1:2:3:4:5:6:7:8%]").x().z();
test("http://[1:2:3:4:5:6:7:8%!/]").x().z();
test("http://[1:2:3:4:5:6:7:8:9]").x().z();
test("http://[::1.2.3.300]").x().z();
test("http://[1.2.3.4:5]").x().z();
// Optional IPv6 brackets in constructors
test("http", "1:2:3:4:5:6:7:8", -1, "")
.s("http").h("[1:2:3:4:5:6:7:8]").p("").z();
test("http", "1:2:3:4:5:6:7:8%hme0", -1, "")
.s("http").h("[1:2:3:4:5:6:7:8%hme0]").p("").z();
test("http", "[1:2:3:4:5:6:7:8]", -1, "")
.s("http").h("[1:2:3:4:5:6:7:8]").p("").z();
}
static void serial() throws IOException, MalformedURLException {
header("Serialization");
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
URL u = new URL("http://java.sun.com/jdk/1.4?release#beta");
oo.writeObject(u);
oo.close();
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
try {
Object o = oi.readObject();
u.equals(o);
} catch (ClassNotFoundException x) {
x.printStackTrace();
throw new RuntimeException(x.toString());
}
}
static void tests() throws IOException, MalformedURLException {
rfc2396();
ip();
serial();
}
// -- Command-line invocation --
static void usage() {
out.println("Usage:");
out.println(" java Test -- Runs all tests in this file");
out.println(" java Test <url> -- Parses url, shows components");
out.println(" java Test <base> <url> -- Parses url and base, then resolves");
out.println(" url against base");
}
public static void main(String[] args) throws Exception {
switch (args.length) {
case 0:
tests();
out.println();
out.println("Test cases: " + testCount);
break;
case 1:
if (args[0].equals("-help")) {
usage();
break;
}
// clargs(null, args[0]);
break;
case 2:
// clargs(args[0], args[1]);
break;
default:
usage();
break;
}
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2001, 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 4451522
* @run main/othervm TestIPv6Addresses
* @summary URI and URL getHost() methods don't comform to RFC 2732
*/
import java.net.*;
public class TestIPv6Addresses {
public static void main(String[] args) {
try {
// testing InetAddress static constructors
InetAddress ia1 = InetAddress.getByName("fe80::a00:20ff:feae:45c9");
InetAddress ia2 = InetAddress.getByName("[fe80::a00:20ff:feae:45c9]");
System.out.println("InetAddress: "+ia1+" , "+ia2);
if (!ia1.equals(ia2)) {
throw new RuntimeException("InetAddress.getByName failed for"+
"literal IPv6 addresses");
}
// testing URL constructor, getHost and getAuthority
URL u1 = new URL("http", "fe80::a00:20ff:feae:45c9", 80, "/index.html");
URL u2 = new URL("http", "[fe80::a00:20ff:feae:45c9]", 80, "/index.html");
if (!u1.equals(u2)) {
throw new RuntimeException("URL constructor failed for"+
"literal IPv6 addresses");
}
if (!u1.getHost().equals(u2.getHost()) ||
!u1.getHost().equals("[fe80::a00:20ff:feae:45c9]")) {
throw new RuntimeException("URL.getHost() failed for"+
"literal IPv6 addresses");
}
if (!u1.getAuthority().equals("[fe80::a00:20ff:feae:45c9]:80")) {
throw new RuntimeException("URL.getAuthority() failed for"+
"literal IPv6 addresses");
}
// need to test URI as well
// testing SocketPermission to see whether it handles unambiguous cases
// testing getIP and getHost etc
SocketPermission sp1 =
new SocketPermission(u1.getHost()+":80-", "resolve");
SocketPermission sp2 =
new SocketPermission(ia1.getHostAddress()+":8080", "resolve");
if (!sp1.implies(sp2)) {
throw new RuntimeException("SocketPermission implies doesn't work"+
" for literal IPv6 addresses");
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
String strAddr = "::FFFF:127.0.0.1.2";
try {
InetAddress addr = InetAddress.getByName(strAddr);
} catch (UnknownHostException e) {
// expected
}
}
}

View file

@ -0,0 +1,55 @@
/*
* 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 4101492 4444213 4906983
* @summary The java.net.URL constructor allows port < 0 and port > 65535
*/
import java.net.*;
public class TestPort {
public static void main(String[] args) throws MalformedURLException {
// URLs are able to have port bigger than TCP-Port 65535 and
// to have no port (-1) at all.:
URL url = new URL("http","server",Integer.MAX_VALUE,"/path");
url = new URL("http://server:"+Integer.MAX_VALUE+"/path");
url = new URL("http://server/path");
url = new URL("http","server",-1,"/path");
try {
url = new URL("ftp", "java.sun.com", -20, "/pub/");
throw new RuntimeException("MalformedURLException not thrown!");
} catch (MalformedURLException e) {
// Everything fine. MalformedURLException expected
}
try {
url = new URL("ftp://java.sun.com:-20/pub/");
throw new RuntimeException("MalformedURLException not thrown!");
} catch (MalformedURLException e) {
// Everything fine. MalformedURLException expected
}
}
}

View file

@ -0,0 +1,51 @@
/*
* 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 4440955
* @summary toExternalForm() , toString() 's results format is
* not proper with IPv6 host nam
*/
import java.net.*;
public class TestRFC2732 {
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http", "10:100::1234", 99, "/index");
if (!u.toString().equals("http://[10:100::1234]:99/index") ||
!u.toExternalForm().equals("http://[10:100::1234]:99/index")) {
throw new Exception("Failed test for RFC 2732");
}
System.out.println("Test passed!");
} catch(Exception exp) {
throw new RuntimeException(exp.getMessage() +
"Expect: " +
"http://[10:100::1234]:99/index" +
" Got: " + u.toExternalForm());
}
}
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 2001, 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
* @bug 4482455
* @summary URI.toURL() implementation needs to be improved
*
*/
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class URIToURLTest {
public static void main(String args[]) throws Exception {
List<String> uris = new ArrayList<>();
uris.add("http://jag:cafebabe@java.sun.com:94/b/c/d?q#g");
uris.add("http://[1080:0:0:0:8:800:200C:417A]/index.html");
uris.add("http://a/b/c/d;p?q");
uris.add("mailto:mduerst@ifi.unizh.ch");
uris.add("http:comp.infosystems.www.servers.unix");
if (hasFtp())
uris.add("ftp://ftp.is.co.za/rfc/rfc1808.txt");
for (String uriStr : uris) {
URI uri = new URI(uriStr);
URL url = uri.toURL();
String scheme = uri.getScheme();
boolean schemeCheck = scheme == null? url.getProtocol() == null :
scheme.equals(url.getProtocol());
if (!schemeCheck)
throw new RuntimeException("uri.scheme is " + scheme +
" url.protocol is " +
url.getProtocol());
if (uri.isOpaque()) {
String ssp = uri.getSchemeSpecificPart();
boolean sspCheck = ssp == null? uri.getPath() == null :
ssp.equals(url.getPath());
if (!sspCheck) {
throw new RuntimeException("uri.ssp is " + ssp +
" url.path is " + url.getPath());
}
} else {
String authority = uri.getAuthority();
boolean authorityCheck = authority == null?
url.getAuthority() == null :
authority.equals(url.getAuthority());
if (!authorityCheck) {
throw new RuntimeException("uri.authority is " +
authority + " url's is " +
url.getAuthority());
}
String host = uri.getHost();
boolean hostCheck = host == null ? url.getHost() == null :
host.equals(url.getHost());
if (!hostCheck)
throw new RuntimeException("uri.host is " +
host + " url's is " +
url.getHost());
if (host != null) {
String userInfo = uri.getUserInfo();
boolean userInfoCheck = userInfo == null?
url.getUserInfo() == null :
userInfo.equals(url.getUserInfo());
if (!userInfoCheck) {
throw new RuntimeException("uri.userInfo is " + userInfo +
" url.userInfo is " +
url.getUserInfo());
}
if (uri.getPort() != url.getPort())
throw new RuntimeException("uri.port is " +
uri.getPort() + " url's is " +
url.getPort());
}
String path = uri.getPath();
boolean pathCheck = path == null? url.getPath() == null :
path.equals(url.getPath());
if (!pathCheck)
throw new RuntimeException("uri.path is " + path +
" url.path is " +
url.getPath());
String query = uri.getQuery();
boolean queryCheck = query == null? url.getQuery() == null :
query.equals(url.getQuery());
if (!queryCheck)
throw new RuntimeException("uri.query is " + query +
" url.query is " +
url.getQuery());
}
String frag = uri.getFragment();
boolean fragCheck = frag == null? url.getRef() == null :
frag.equals(url.getRef());
if (!fragCheck)
throw new RuntimeException("uri.frag is " + frag +
" url.ref is " +
url.getRef());
}
}
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,377 @@
/*
* Copyright (c) 2022, 2023, 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 8294241
* @library /test/lib
* @modules java.base/java.net:+open
* @summary Test URL::fromURI(URI, URLStreamHandler)
* @run junit/othervm URLFromURITest
*/
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.VarHandle;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import jdk.test.lib.RandomFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
public class URLFromURITest {
static final Random RAND = RandomFactory.getRandom();
record TestInput(String uri, URLStreamHandler handler) {
static TestInput withNoHandler(String uri) {
return new TestInput(uri, null);
}
TestInput withCustomHandler() {
return new TestInput(uri(), new CustomStreamHandler());
}
TestInput withUrlPrefix() {return inputWithUrlPrefix(this);}
}
static URI uriWithUrlPrefix(URI uri) {
return URI.create(stringWithUrlPrefix(uri.toString()));
}
static String stringWithUrlPrefix(String uriStr) {
if (uriStr.regionMatches(true, 0, "url:", 0, 4)) return uriStr;
return RAND.nextBoolean() ? "url:" + uriStr : "Url:" + uriStr;
}
static TestInput inputWithUrlPrefix(TestInput input) {
String uriStr = input.uri();
var handler = input.handler();
var urlUriStr = stringWithUrlPrefix(uriStr);
if (uriStr.equals(urlUriStr)) return null;
var urlURI = URI.create(urlUriStr);
try {
new URL(null, urlURI.toString(), handler);
} catch (Throwable t) {
System.err.println("skipping new URL(null, \"" + urlURI + "\", handler): " + t);
return null;
}
return new TestInput(urlUriStr, handler);
}
static Stream<String> uris() {
var uris = Stream.of(
"http://jag:cafebabe@java.sun.com:94/b/c/d?q#g",
"http://[1080:0:0:0:8:800:200C:417A]/index.html",
"http://a/b/c/d;p?q",
"mailto:mduerst@ifi.unizh.ch",
"http:comp.infosystems.www.servers.unix",
"http://j%41g:cafeb%41be@java.sun.com:94/%41/b/c/d?q#g",
"jar:file:///x.jar!/",
"jmod:/java.base",
"jmod:///java.base");
if (hasFtp()) {
uris = Stream.concat(uris,
Stream.of("ftp://ftp.is.co.za/rfc/rfc1808.txt"));
}
return uris;
}
static Stream<String> nonOverridableUris() {
return Stream.of("file:///nohost/%41/",
"file://with.host/%41/",
"file:/x/y/z",
"jrt:/java.base/java/lang/Integer.class",
"jrt:///java.base/java/lang/Integer.class");
}
static Stream<TestInput> withNoHandler() {
return Stream.concat(uris(), nonOverridableUris())
.map(TestInput::withNoHandler);
}
static Stream<TestInput> withCustomHandler() {
var withHandlers = uris()
.map(TestInput::withNoHandler)
.map(TestInput::withCustomHandler);
return Stream.concat(withHandlers, Stream.of(
new TestInput("foo:bar:baz", new CustomStreamHandler()),
new TestInput("jar:file:///x.jar!/", new CustomStreamHandler()),
new TestInput("jar:jar:file///x.jar!/bing", new CustomStreamHandler()),
new TestInput("blah://localhost:80/x/y/z", new CustomStreamHandler())
));
}
static Stream<TestInput> overridingNonOverridable() {
return nonOverridableUris().map(TestInput::withNoHandler)
.map(TestInput::withCustomHandler);
}
@Test
public void checkExceptions() {
var noscheme = URI.create("http");
var unknown = URI.create("unknown:///foo/bar");
var opaque = URI.create("opaque:opaque-path");
var jrt = URI.create("jrt:/java.base/java.lang.Integer.class");
var file = URI.create("file:/");
var unoscheme = uriWithUrlPrefix(noscheme);
var uunknown = uriWithUrlPrefix(unknown);
var uopaque = uriWithUrlPrefix(opaque);
var ujrt = uriWithUrlPrefix(jrt);
var ufile = uriWithUrlPrefix(file);
var handler = new CustomStreamHandler();
assertThrows(NullPointerException.class, () -> URL.of(null, null));
assertThrows(NullPointerException.class, () -> URL.of(null, handler));
assertThrows(IllegalArgumentException.class, () -> URL.of(noscheme, null));
assertThrows(IllegalArgumentException.class, () -> URL.of(noscheme, handler));
assertThrows(IllegalArgumentException.class, () -> URL.of(jrt, handler));
assertThrows(IllegalArgumentException.class, () -> URL.of(file, handler));
assertThrows(IllegalArgumentException.class, () -> URL.of(ujrt, handler));
assertThrows(IllegalArgumentException.class, () -> URL.of(ufile, handler));
assertThrows(MalformedURLException.class, () -> URL.of(unknown, null));
assertThrows(MalformedURLException.class, () -> URL.of(opaque, null));
assertThrows(MalformedURLException.class, () -> URL.of(uunknown, null));
assertThrows(MalformedURLException.class, () -> URL.of(uopaque, null));
assertThrows(MalformedURLException.class, () -> URL.of(unoscheme, null));
assertThrows(MalformedURLException.class, () -> URL.of(unoscheme, handler));
}
@ParameterizedTest
@MethodSource(value = "withNoHandler")
public void testWithNoHandler(TestInput input) throws Exception {
String uriStr = input.uri();
URLStreamHandler handler = input.handler();
System.err.println("testWithNoHandler: " + uriStr);
assertNull(handler, input + ": input handler");
URI uri = new URI(uriStr);
URL url = URL.of(uri, handler);
checkNoHandler(input, uri, url);
var urlInput = input.withUrlPrefix();
if (urlInput != null) {
try {
var urlURI = URI.create(input.uri());
checkNoHandler(urlInput, uri, URL.of(urlURI, null));
} catch (Throwable x) {
throw new AssertionError("Failed: " + urlInput.uri() + " with: " + x, x);
}
}
}
private void checkNoHandler(TestInput input, URI uri, URL url) throws Exception {
System.err.println("Testing: " + uri);
checkURL(input, uri, url);
URLStreamHandler urlHandler = URLAccess.getHandler(url);
assertNotNull(urlHandler, input + ": URL.handler");
assertNull(urlHandler.getClass().getClassLoader(),
input + ": URL.handler class loader");
}
@ParameterizedTest
@MethodSource(value = "withCustomHandler")
public void checkCustomHandler(TestInput input) throws Exception {
String uriStr = input.uri();
URLStreamHandler handler = input.handler();
System.err.println("testWithCustomHandler: " + input);
assertNotNull(handler, input + ": input handler");
URI uri = new URI(uriStr);
URL url = URL.of(uri, handler);
checkCustomHandler(input, uri, url, handler);
var urlInput = input.withUrlPrefix();
if (urlInput != null) {
urlInput = urlInput.withCustomHandler();
handler = urlInput.handler();
try {
var urlURI = URI.create(urlInput.uri());
checkCustomHandler(urlInput, uri, URL.of(urlURI, handler), handler);
} catch (Throwable x) {
throw new AssertionError("Failed with handler: " + urlInput.uri() + " with: " + x, x);
}
}
}
private void checkCustomHandler(TestInput input, URI uri, URL url,
URLStreamHandler handler) throws Exception {
System.err.println("Testing: " + uri);
checkURL(input, uri, url);
URLStreamHandler urlHandler = URLAccess.getHandler(url);
assertSame(handler, urlHandler, input + ": URL.handler");
URLConnection c = url.openConnection();
assertNotNull(c, input + ": opened connection");
assertEquals(CustomURLConnection.class, c.getClass(),
input + ": connection class");
assertEquals(CustomStreamHandler.class, urlHandler.getClass(),
input + ": handler class");
assertEquals(((CustomURLConnection)c).handler, handler, input + ": handler");
assertEquals(c.getURL(), url, input + ": connection url");
var customHandler = (CustomStreamHandler)urlHandler;
assertEquals(customHandler.parseURLCalled(), 1, "parseURL calls");
}
@ParameterizedTest
@MethodSource(value = "overridingNonOverridable")
public void testOverridingNonOverridable(TestInput input) throws Exception {
String uriStr = input.uri();
URLStreamHandler handler = input.handler();
System.err.println("testOverridingNonOverridable: " + input);
assertNotNull(handler, input + ": input handler");
URI uri = new URI(uriStr);
try {
URL url = URL.of(uri, handler);
throw new AssertionError("Should not be able to specify handler for: " + uriStr);
} catch (IllegalArgumentException x) {
System.err.println("Got expected exception: " + x);
}
}
private static boolean isFileBased(URI uri) {
String scheme = uri.getScheme();
boolean isJrt = "jrt".equals(scheme.toLowerCase(Locale.ROOT));
boolean isJmod = "jmod".equals(scheme.toLowerCase(Locale.ROOT));
boolean isFile = "file".equals(scheme.toLowerCase(Locale.ROOT));
return isJmod || isJrt || isFile;
}
private static void checkURL(TestInput input, URI uri, URL url) throws MalformedURLException {
String scheme = uri.getScheme();
assertEquals(scheme, url.getProtocol(), input + ": scheme");
if (uri.isOpaque()) {
String ssp = uri.getSchemeSpecificPart();
assertEquals(ssp, url.getPath(), input + ": ssp");
} else {
String authority = uri.getRawAuthority();
boolean isHierarchical = uri.toString().startsWith(scheme + "://");
boolean isFileBased = isFileBased(uri);
// Network based URLs usually follow URI, but file based
// protocol handlers have a few discrepancies in how they
// treat an absent authority:
// - URI authority is null if there is no authority, always
// - URL authority is null or empty depending on the protocol
// and on whether the URL is hierarchical or not.
if (isFileBased && authority == null) {
// jrt: takes a fastpath - so that jrt:/ is equivalent to jrt:///
if (scheme.equals("jrt")) {
authority = "";
}
if (isHierarchical) {
authority = "";
}
}
assertEquals(authority, url.getAuthority(), input + ": authority");
// Network based URLs usually follow URI, but file based
// protocol handlers have a few discrepancies in how they
// treat an absent host:
String host = uri.getHost();
if (isFileBased && host == null) {
host = "";
}
assertEquals(host, url.getHost(), input + ": host");
if (host != null) {
String userInfo = uri.getRawUserInfo();
assertEquals(userInfo, url.getUserInfo(), input + ": userInfo");
assertEquals(uri.getPort(), url.getPort(), input + ": port");
}
String path = uri.getRawPath();
assertEquals(path, url.getPath(), input + ": path");
String query = uri.getQuery();
assertEquals(query, url.getQuery(), input + ": query");
}
String frag = uri.getRawFragment();
assertEquals(frag, url.getRef(), input + ": fragment");
}
@SuppressWarnings("deprecation")
private static boolean hasFtp() {
try {
return new java.net.URL("ftp://localhost/") != null;
} catch (java.net.MalformedURLException x) {
System.err.println("FTP not supported by this runtime.");
return false;
}
}
static class CustomURLConnection extends URLConnection {
public final CustomStreamHandler handler;
CustomURLConnection(CustomStreamHandler handler, URL url) {
super(url);
this.handler = handler;
}
@Override
public void connect() throws IOException {
}
}
static class CustomStreamHandler extends URLStreamHandler {
final AtomicInteger parseURLCalled = new AtomicInteger();
@Override
protected void parseURL(URL u, String spec, int start, int limit) {
parseURLCalled.incrementAndGet();
super.parseURL(u, spec, start, limit);
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new CustomURLConnection(this, u);
}
public int parseURLCalled() {
return parseURLCalled.get();
}
}
static final class URLAccess {
static final VarHandle HANDLER;
static {
try {
Lookup lookup = MethodHandles.privateLookupIn(URL.class, MethodHandles.lookup());
HANDLER = lookup.findVarHandle(URL.class, "handler", URLStreamHandler.class);
} catch (Exception x) {
throw new ExceptionInInitializerError(x);
}
}
static URLStreamHandler getHandler(URL url) {
return (URLStreamHandler)HANDLER.get(url);
}
}
}

View file

@ -0,0 +1,38 @@
/*
* 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 4417734
* @summary Test that piece-wise URL constructor should ignore case
* of scheme.
*/
import java.net.URL;
public class UppercaseScheme {
public static void main(String args[]) throws Exception {
URL u = new URL("HTTP", "10:100::1234", 9999, "/index.html");
}
}