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,78 @@
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6460701 6431651
* @run main/othervm AddURLTest
* @summary Fixes for 6460701 & 6431651.
*/
import java.net.*;
import java.io.*;
/**
* 6460701 : URLClassLoader:addURL RI behavior inconsistent with a spec in case duplicate URLs
* 6431651 : No description for addURL(URL url) method of URLClassLoader class in case null url
*/
public class AddURLTest
{
public static void main(String[] args) throws Exception {
URL[] urls = new URL[] {new URL("http://foobar.jar") };
MyURLClassLoader ucl = new MyURLClassLoader(urls);
ucl.addURL(null);
ucl.addURL(new URL("http://foobar.jar"));
ucl.addURL(null);
ucl.addURL(new URL("http://foobar.jar"));
ucl.addURL(null);
ucl.addURL(new URL("http://foobar.jar"));
urls = ucl.getURLs();
if (urls.length != 1)
throw new RuntimeException(
"Failed: There should only be 1 url in the list of search URLs");
URL url;
for (int i=0; i<urls.length; i++) {
url = urls[i];
if (url == null || !url.equals(new URL("http://foobar.jar")))
throw new RuntimeException(
"Failed: The url should not be null and should be http://foobar.jar");
}
}
static class MyURLClassLoader extends URLClassLoader {
public MyURLClassLoader(URL[] urls) {
super(urls);
}
public void addURL(URL url) {
super.addURL(url);
}
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6827999
* @run main/othervm B6827999
* @summary Fix for 6827999
*/
import java.net.*;
import java.io.*;
/**
*/
public class B6827999
{
public static void main(String[] args) throws Exception {
URL[] urls = new URL[] {new URL("http://foobar.jar") };
MyURLClassLoader ucl = new MyURLClassLoader(urls);
ucl.addURL(new URL("http://foo/bar.jar"));
urls = ucl.getURLs();
if (urls.length != 2)
throw new RuntimeException("Failed:(1)");
ucl.close();
ucl.addURL(new URL("http://foo.bar/bar.jar"));
if (ucl.getURLs().length != 2) {
throw new RuntimeException("Failed:(2)");
}
}
static class MyURLClassLoader extends URLClassLoader {
public MyURLClassLoader(URL[] urls) {
super(urls);
}
public void addURL(URL url) {
super.addURL(url);
}
}
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 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 6896088
* @run main/othervm B6896088
* @summary URLClassLoader.close() apparently not working for JAR URLs on Windows
*/
import java.net.*;
import java.io.*;
import java.nio.file.Path;
public class B6896088 {
public static void main(String[] args) throws Exception {
String dir = System.getProperty ("test.classes");
File jarf = new File (dir, "foo.jar");
FileOutputStream fos = new FileOutputStream (jarf);
fos.write(bytes(nums));
fos.close();
// Create URL using JAR protocol
String jarName = (jarf.toURI()).toString();
URL url = new URL("jar", "", jarName + "!/");
// Create URLClassLoader from the URL
URLClassLoader loader = new URLClassLoader(new URL[]{url});
Class c = loader.loadClass("Foo");
// Close the URLClassLoader so we can delete/update the jar file
loader.close();
// Now try to delete the jar file
if (jarf.delete() && !jarf.exists()) {
System.out.println(jarf.getName()+" File Deleted");
} else {
System.out.println(jarf.getName()+" File Not Deleted");
throw new RuntimeException ("File not deleted");
}
}
static byte[] bytes (int[] i) {
byte[] buf = new byte [i.length];
for (int j=0; j<i.length; j++) {
buf[j] = (byte)i[j];
}
return buf;
}
/* contents of foo.jar */
static final int nums[] = {
0x50,0x4b,0x03,0x04,0x14,0x00,0x08,0x08,0x08,0x00,0xc8,0x61,
0x90,0x3d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x09,0x00,0x04,0x00,0x4d,0x45,0x54,0x41,0x2d,0x49,
0x4e,0x46,0x2f,0xfe,0xca,0x00,0x00,0x03,0x00,0x50,0x4b,0x07,
0x08,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x50,0x4b,0x03,0x04,0x14,0x00,0x08,0x08,0x08,0x00,0xc8,
0x61,0x90,0x3d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x4d,0x45,0x54,0x41,0x2d,
0x49,0x4e,0x46,0x2f,0x4d,0x41,0x4e,0x49,0x46,0x45,0x53,0x54,
0x2e,0x4d,0x46,0xf3,0x4d,0xcc,0xcb,0x4c,0x4b,0x2d,0x2e,0xd1,
0x0d,0x4b,0x2d,0x2a,0xce,0xcc,0xcf,0xb3,0x52,0x30,0xd4,0x33,
0xe0,0xe5,0x72,0x2e,0x4a,0x4d,0x2c,0x49,0x4d,0xd1,0x75,0xaa,
0x04,0x09,0x98,0xeb,0x19,0xe8,0x66,0xe6,0x95,0xa4,0x16,0xe5,
0x25,0xe6,0x28,0x68,0xf8,0x17,0x25,0x26,0xe7,0xa4,0x2a,0x38,
0xe7,0x17,0x15,0xe4,0x17,0x25,0x96,0x00,0x35,0x69,0xf2,0x72,
0xf1,0x72,0x01,0x00,0x50,0x4b,0x07,0x08,0x4c,0xd8,0x5e,0x68,
0x49,0x00,0x00,0x00,0x4a,0x00,0x00,0x00,0x50,0x4b,0x03,0x04,
0x14,0x00,0x08,0x08,0x08,0x00,0xbd,0x61,0x90,0x3d,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x00,
0x00,0x00,0x46,0x6f,0x6f,0x2e,0x63,0x6c,0x61,0x73,0x73,0x3b,
0xf5,0x6f,0xd7,0x3e,0x06,0x06,0x06,0x63,0x06,0x5e,0x2e,0x06,
0x66,0x06,0x2e,0x76,0x06,0x6e,0x76,0x06,0x1e,0x46,0x06,0x36,
0x9b,0xcc,0xbc,0xcc,0x12,0x3b,0x46,0x06,0x66,0x0d,0xcd,0x30,
0x46,0x06,0x16,0xe7,0xfc,0x94,0x54,0x46,0x06,0x7e,0x9f,0xcc,
0xbc,0x54,0xbf,0xd2,0xdc,0xa4,0xd4,0xa2,0x90,0xc4,0xa4,0x1c,
0xa0,0x08,0x57,0x70,0x7e,0x69,0x51,0x72,0xaa,0x5b,0x26,0x88,
0xc3,0xe1,0x96,0x9f,0xaf,0x97,0x95,0x58,0x96,0xc8,0xc3,0xc0,
0xc2,0xc0,0x0a,0xd4,0x0b,0xe4,0x33,0x32,0x08,0x80,0x44,0xf4,
0x73,0x12,0xf3,0xd2,0xf5,0xfd,0x93,0xb2,0x52,0x93,0x4b,0x18,
0x14,0x19,0x98,0x80,0x76,0x81,0x00,0x23,0x10,0x02,0x95,0x02,
0x49,0x36,0x20,0x4f,0x16,0xcc,0x67,0x60,0x60,0xd5,0xda,0xce,
0xc0,0xb8,0x11,0x2c,0xcd,0x0e,0x24,0xd9,0xc0,0x82,0x20,0x29,
0x0e,0x20,0xcd,0xc4,0xc0,0x09,0x00,0x50,0x4b,0x07,0x08,0x3e,
0x0a,0xdc,0x88,0x98,0x00,0x00,0x00,0xb4,0x00,0x00,0x00,0x50,
0x4b,0x01,0x02,0x14,0x00,0x14,0x00,0x08,0x08,0x08,0x00,0xc8,
0x61,0x90,0x3d,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x09,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4d,0x45,0x54,
0x41,0x2d,0x49,0x4e,0x46,0x2f,0xfe,0xca,0x00,0x00,0x50,0x4b,
0x01,0x02,0x14,0x00,0x14,0x00,0x08,0x08,0x08,0x00,0xc8,0x61,
0x90,0x3d,0x4c,0xd8,0x5e,0x68,0x49,0x00,0x00,0x00,0x4a,0x00,
0x00,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x3d,0x00,0x00,0x00,0x4d,0x45,0x54,0x41,
0x2d,0x49,0x4e,0x46,0x2f,0x4d,0x41,0x4e,0x49,0x46,0x45,0x53,
0x54,0x2e,0x4d,0x46,0x50,0x4b,0x01,0x02,0x14,0x00,0x14,0x00,
0x08,0x08,0x08,0x00,0xbd,0x61,0x90,0x3d,0x3e,0x0a,0xdc,0x88,
0x98,0x00,0x00,0x00,0xb4,0x00,0x00,0x00,0x09,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc8,0x00,
0x00,0x00,0x46,0x6f,0x6f,0x2e,0x63,0x6c,0x61,0x73,0x73,0x50,
0x4b,0x05,0x06,0x00,0x00,0x00,0x00,0x03,0x00,0x03,0x00,0xb4,
0x00,0x00,0x00,0x97,0x01,0x00,0x00,0x00,0x00,0x00
};
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 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.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @test
* @bug 7050028
* @summary ISE "zip file closed" from JarURLConnection.getInputStream on JDK 7 when !useCaches
* @run main/othervm B7050028
*/
public class B7050028 {
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
private B7050028() {}
}

View file

@ -0,0 +1,83 @@
/*
* 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 4151665
* @modules jdk.httpserver
* @library /test/lib
* @summary Test for FileNotFoundException when loading bogus class
*/
import java.io.InputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLClassLoader;
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 ClassLoad {
public static void main(String[] args) throws Exception {
boolean error = true;
// Start a dummy server to return 404
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(
InetAddress.getLoopbackAddress(), 0), 0);
HttpHandler handler = new HttpHandler() {
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
while (is.read() != -1);
t.sendResponseHeaders (404, -1);
t.close();
}
};
server.createContext("/", handler);
server.start();
// Client request
try {
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(server.getAddress().getPort())
.toURL();
String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
ClassLoader loader = new URLClassLoader(new URL[] { url });
System.out.println(url);
Class c = loader.loadClass(name);
System.out.println("Loaded class \"" + c.getName() + "\".");
} catch (ClassNotFoundException ex) {
System.out.println(ex);
error = false;
} finally {
server.stop(0);
}
if (error)
throw new RuntimeException("No ClassNotFoundException generated");
}
}

View file

@ -0,0 +1,150 @@
/*
* 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 4110602
* @author Benjamin Renaud
* @summary check that URLClassLoader correctly interprets Class-Path
*
* This test ensures that a manually constructed URLClassLoader is
* able to:
*
* 1. load a class
* 2. resolve Class-Path dependencies
* 3. have that class use a dependent class in a different JAR file
*/
import java.util.jar.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class ClassPathTest {
JarFile jarFile;
Manifest manifest;
Attributes mainAttributes;
Map map;
URLClassLoader ucl;
static class TestException extends RuntimeException {
TestException(Throwable t) {
super("URLClassLoader ClassPathTest failed with: " + t);
}
}
public ClassPathTest() {
File local = new File(System.getProperty("test.src", "."),
"jars/class_path_test.jar");
String jarFileName = local.getPath();
try {
jarFile = new JarFile(jarFileName);
}
catch (IOException e) {
System.err.println("Could not find jar file " + jarFileName);
throw new TestException(e);
}
try {
URL url = getUrl(new File(jarFileName));
System.out.println("url: " + url);
ucl = new URLClassLoader(new URL[] { url });
// Moved this inside try block, as it may raise IOException.
// (maddox)
manifest = jarFile.getManifest();
}
catch (Exception e) {
throw new TestException(e);
}
//manifest = jarFile.getManifest();
mainAttributes = manifest.getMainAttributes();
map = manifest.getEntries();
Iterator it = map.entrySet().iterator();
Class clazz = null;
while (it.hasNext()) {
Map.Entry e = (Map.Entry)it.next();
Attributes a = (Attributes)e.getValue();
Attributes.Name an = new Attributes.Name("Class-Path");
if (a.containsKey(an)) {
String val = a.getValue(an);
if (val != null)
System.out.println("Class-Path: " + val);
}
if (a.containsKey(new Attributes.Name("Java-Bean"))) {
String beanClassName = nameToClassName((String)e.getKey());
System.out.println("JavaBean Class: " + beanClassName);
try {
clazz = ucl.loadClass(beanClassName);
}
catch (Throwable t) {
throw new TestException(t);
} if (clazz != null) {
try {
System.out.println("instantiating " + beanClassName);
clazz.newInstance();
System.out.println("done instantiating " +
beanClassName);
} catch (Throwable t2) {
throw new TestException(t2);
}
}
}
}
}
String nameToClassName(String key) {
String key2 = key.replace('/', File.separatorChar);
int li = key2.lastIndexOf(".class");
key2 = key2.substring(0, li);
return key2;
}
private static URL getUrl(File file) {
String name;
try {
name = file.getCanonicalPath();
} catch (IOException e) {
name = file.getAbsolutePath();
}
name = name.replace(File.separatorChar, '/');
if (!name.startsWith("/")) {
name = "/" + name;
}
try {
return new URL( "file:" + name);
} catch (MalformedURLException e) {
throw new TestException(e);
}
}
public static void main(String args[]) {
new ClassPathTest();
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8262277
* @summary Test if URLClassLoader throws IllegalArgumentException when getting
* or finding resources.
*/
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
public class FindResourceDoesNotThrowException {
public static void main(String[] args) throws Exception {
// URL ends in slash, does not start with file: or jar:
URL url = new URL("https://127.0.0.1/");
// resource name is not a valid url component
String resource = "c:/windows";
try (URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url})) {
if (urlClassLoader.findResource(resource) != null) {
throw new RuntimeException("findResource should return null");
}
if (urlClassLoader.getResource(resource) != null) {
throw new RuntimeException("getResource should return null");
}
if (urlClassLoader.findResources(resource).hasMoreElements()) {
throw new RuntimeException("findResources should return an empty enumeration");
}
if (urlClassLoader.getResources(resource).hasMoreElements()) {
throw new RuntimeException("getResources should return an empty enumeration");
}
}
}
private FindResourceDoesNotThrowException() {}
}

View file

@ -0,0 +1,73 @@
/*
* 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.
*/
import java.net.*;
import java.io.*;
/*
* @test
* @summary Regression test for URLClassLoader getURLs() and addURL() methods.
* See RFE 4102580: Need URLClassLoader.getURLs() method
*/
public class GetURLsTest {
static final String TEST_DIR = System.getProperty("test.src", ".");
public static void main(String[] args) throws Exception {
File testJars = new File(TEST_DIR, "jars");
MyURLClassLoader ucl =
new MyURLClassLoader(new URL[] { new File(".").toURL() });
p("initial urls = ", ucl.getURLs());
URL u = ucl.getResource("GetURLsTest.java");
if (u != null) {
p("found resource = " + u);
}
ucl.addURL(new File(testJars, "class_path_test.jar").toURL());
p("new urls = ", ucl.getURLs());
Class c = ucl.loadClass("Foo");
p("found class = " + c);
}
static class MyURLClassLoader extends URLClassLoader {
public MyURLClassLoader(URL[] urls) {
super(urls);
}
public void addURL(URL url) {
super.addURL(url);
}
}
static void p(String s, URL[] urls) {
System.out.print(s);
if (urls.length > 0) {
for (int i = 0; i < urls.length - 1; i++) {
System.out.print(urls[i] + " ");
}
}
System.out.println(urls[urls.length - 1]);
}
static void p(String s) {
System.out.println(s);
}
}

View file

@ -0,0 +1,321 @@
/*
* Copyright (c) 2002, 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 4636331
* @modules jdk.httpserver
* @library /test/lib
* @summary Check that URLClassLoader with HTTP paths lookups produce the expected http requests
* @run junit HttpTest
*/
import java.net.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HttpTest {
// HTTP server used to track requests
static HttpServer server;
// RequestLog for capturing requests
static class RequestLog {
List<Request> log = new ArrayList<>();
// Add a request to the log
public synchronized void capture(String method, URI uri) {
log.add(new Request(method, uri));
}
// Clear requests
public synchronized void clear() {
log.clear();
}
public synchronized List<Request> requests() {
return List.copyOf(log);
}
}
// Represents a single request
record Request(String method, URI path) {}
// Request log for this test
static RequestLog log = new RequestLog();
// Handlers specific to tests
static Map<URI, HttpHandler> handlers = new ConcurrentHashMap<>();
// URLClassLoader with HTTP URL class path
private static URLClassLoader loader;
@BeforeAll
static void setup() throws Exception {
server = HttpServer.create();
server.bind(new InetSocketAddress(
InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/", e -> {
// Capture request in the log
log.capture(e.getRequestMethod(), e.getRequestURI());
// Check for custom handler
HttpHandler custom = handlers.get(e.getRequestURI());
if (custom != null) {
custom.handle(e);
} else {
// Successful responses echo the request path in the body
byte[] response = e.getRequestURI().getPath()
.getBytes(StandardCharsets.UTF_8);
e.sendResponseHeaders(200, response.length);
try (var out = e.getResponseBody()) {
out.write(response);
}
}
e.close();
});
server.start();
int port = server.getAddress().getPort();
// Create class loader with two HTTP URLs
URL[] searchPath = new URL[] {
getHttpUri("/dir1/", port),
getHttpUri("/dir2/", port)
};
loader = new URLClassLoader(searchPath);
}
// Create an HTTP URL for the given path and port using the loopback address
private static URL getHttpUri(String path, int port) throws Exception {
return URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.path(path).toURL();
}
// Add redirect handler for a given path
private static void redirect(String path, String target) {
handlers.put(URI.create(path), e -> {
e.getResponseHeaders().set("Location", target);
e.sendResponseHeaders(301, 0);
});
}
// Return 404 not found for a given path
private static void notFound(String path) {
handlers.put(URI.create(path), e ->
e.sendResponseHeaders(404, 0));
}
@AfterAll
static void shutdown() {
server.stop(2000);
}
@BeforeEach
void reset() {
synchronized (log) {
log.clear();
}
handlers.clear();
}
// Check that getResource does single HEAD request
@Test
void getResourceSingleHead() {
URL url = loader.getResource("foo.gif");
// Expect one HEAD
assertRequests(e -> e
.request("HEAD", "/dir1/foo.gif")
);
}
// Check that getResource follows redirects
@Test
void getResourceShouldFollowRedirect() {
redirect("/dir1/foo.gif", "/dir1/target.gif");
URL url = loader.getResource("foo.gif");
// Expect extra HEAD for redirect target
assertRequests(e -> e
.request("HEAD", "/dir1/foo.gif")
.request("HEAD", "/dir1/target.gif")
);
/*
* Note: Long-standing behavior is that URLClassLoader:getResource
* returns a URL for the requested resource, not the location redirected to
*/
assertEquals("/dir1/foo.gif", url.getPath());
}
// Check that getResource treats a redirect to a not-found resource as a not-found resource
@Test
void getResourceRedirectTargetNotFound() {
redirect("/dir1/foo.gif", "/dir1/target.gif");
notFound("/dir1/target.gif");
URL url = loader.getResource("foo.gif");
// Expect extra HEAD for redirect target and next URL in search path
assertRequests(e -> e
.request("HEAD", "/dir1/foo.gif")
.request("HEAD", "/dir1/target.gif")
.request("HEAD", "/dir2/foo.gif")
);
// Should find URL for /dir2
assertEquals("/dir2/foo.gif", url.getPath());
}
// Check that getResourceAsStream does one HEAD and one GET request
@Test
void getResourceAsStreamSingleGet() throws IOException {
// Expect content from the first path
try (var in = loader.getResourceAsStream("foo2.gif")) {
assertEquals("/dir1/foo2.gif",
new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
// Expect one HEAD, one GET
assertRequests( e -> e
.request("HEAD", "/dir1/foo2.gif")
.request("GET", "/dir1/foo2.gif")
);
}
// Check that getResourceAsStream follows redirects
@Test
void getResourceAsStreamFollowRedirect() throws IOException {
redirect("/dir1/foo.gif", "/dir1/target.gif");
// Expect content from the redirected location
try (var in = loader.getResourceAsStream("foo.gif")) {
assertEquals("/dir1/target.gif",
new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
/*
* Note: Long standing behavior of URLClassLoader::getResourceAsStream
* is to use HEAD during the findResource resource discovery and to not
* "remember" the HEAD redirect location when performing the GET. This
* explains why we observe two redirects here, one for HEAD, one for GET.
*/
assertRequests( e -> e
.request("HEAD", "/dir1/foo.gif")
.request("HEAD", "/dir1/target.gif")
.request("GET", "/dir1/foo.gif")
.request("GET", "/dir1/target.gif")
);
}
// getResourceAsStream on a 404 should try next path
@Test
void getResourceTryNextPath() throws IOException {
// Make the first path return 404
notFound("/dir1/foo.gif");
// Expect content from the second path
try (var in = loader.getResourceAsStream("foo.gif")) {
assertEquals("/dir2/foo.gif",
new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
// Expect two HEADs, one GET
assertRequests(e -> e
.request("HEAD", "/dir1/foo.gif")
.request("HEAD", "/dir2/foo.gif")
.request("GET", "/dir2/foo.gif")
);
}
// Check that getResources only does HEAD requests
@Test
void getResourcesOnlyHead() throws IOException {
Collections.list(loader.getResources("foos.gif"));
// Expect one HEAD for each path
assertRequests(e -> e
.request("HEAD", "/dir1/foos.gif")
.request("HEAD", "/dir2/foos.gif")
);
}
// Check that getResources skips 404 URL
@Test
void getResourcesShouldSkipFailedHead() throws IOException {
// Make first path fail with 404
notFound("/dir1/foos.gif");
List<URL> resources = Collections.list(loader.getResources("foos.gif"));
// Expect one HEAD for each path
assertRequests(e -> e
.request("HEAD", "/dir1/foos.gif")
.request("HEAD", "/dir2/foos.gif")
);
// Expect a single URL to be returned
assertEquals(1, resources.size());
}
// Utils for asserting requests
static class Expect {
List<Request> requests = new ArrayList<>();
Expect request(String method, String path) {
requests.add(new Request(method, URI.create(path)));
return this;
}
}
static void assertRequests(Consumer<Expect> e) {
// Collect expected requests
Expect exp = new Expect();
e.accept(exp);
List<Request> expected = exp.requests;
// Actual requests
List<Request> requests = log.requests();
// Verify expected number of requests
assertEquals(expected.size(), requests.size(), "Unexpected request count");
// Verify expected requests in order
for (int i = 0; i < expected.size(); i++) {
Request ex = expected.get(i);
Request req = requests.get(i);
// Verify method
assertEquals(ex.method, req.method,
String.format("Request %s has unexpected method %s", i, ex.method)
);
// Verify path
assertEquals(ex.path, req.path,
String.format("Request %s has unexpected request URI %s", i, ex.path)
);
}
}
}

View file

@ -0,0 +1,148 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import jdk.test.lib.util.JarUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
/*
* @test
* @bug 8338445
* @summary verify that the jdk.internal.loader.URLClassPath closes the JarFile
* instances that it no longer uses for loading
* @library /test/lib
* @build jdk.test.lib.util.JarUtils
* @comment This test expects MalformedURLException for some specific URLs.
* We use othervm to prevent interference from other tests which
* might have installed custom URLStreamHandler(s)
* @run junit/othervm JarLoaderCloseTest
*/
public class JarLoaderCloseTest {
private static final String RESOURCE_NAME = "foo-bar.txt";
private static final String RESOURCE_CONTENT = "Hello world";
private static final Path TEST_SCRATCH_DIR = Path.of(".");
@BeforeAll
static void beforeAll() throws Exception {
// create a file which will be added to the JAR file that gets tested
Files.writeString(TEST_SCRATCH_DIR.resolve(RESOURCE_NAME), RESOURCE_CONTENT);
}
/*
* Creates a JAR file with a manifest which has a Class-Path entry value with malformed URLs.
* Then uses a URLClassLoader backed by the JAR file in its classpath, loads some resource,
* closes the URLClassLoader and then expects that the underlying JAR file can be deleted
* from the filesystem.
*/
@ParameterizedTest
@ValueSource(strings = {
"C:\\foo\\bar\\hello/world.jar lib2.jar",
"C:/hello/world/foo.jar",
"lib4.jar C:\\bar\\foo\\world/hello.jar"
})
public void testMalformedClassPathEntry(final String classPathValue) throws Exception {
final Manifest manifest = createManifestWithClassPath(classPathValue);
final Path jar = Files.createTempFile(TEST_SCRATCH_DIR, "8338445", ".jar");
// create the JAR file with the given manifest and an arbitrary file
JarUtils.createJarFile(jar, manifest, TEST_SCRATCH_DIR, Path.of(RESOURCE_NAME));
System.out.println("created jar at " + jar + " with manifest:");
manifest.write(System.out);
final URL[] urlClassPath = new URL[]{jar.toUri().toURL()};
// Create a URLClassLoader backed by the JAR file and load a non-existent resource just to
// exercise the URLClassPath code of loading the jar and parsing the Class-Path entry.
// Then close the classloader. After the classloader is closed
// issue a delete on the underlying JAR file on the filesystem. The delete is expected
// to succeed.
try (final URLClassLoader cl = new URLClassLoader(urlClassPath)) {
try (final InputStream is = cl.getResourceAsStream("non-existent.txt")) {
assertNull(is, "unexpectedly found a resource in classpath "
+ Arrays.toString(urlClassPath));
}
}
// now delete the JAR file and verify the delete worked
Files.delete(jar);
assertFalse(Files.exists(jar), jar + " exists even after being deleted");
}
/*
* Creates a JAR file with a manifest which has a Class-Path entry value with URLs
* that are parsable but point to files that don't exist on the filesystem.
* Then uses a URLClassLoader backed by the JAR file in its classpath, loads some resource,
* closes the URLClassLoader and then expects that the underlying JAR file can be deleted
* from the filesystem.
*/
@ParameterizedTest
@ValueSource(strings = {
"/home/me/hello/world.jar lib9.jar",
"lib10.jar"
})
public void testParsableClassPathEntry(final String classPathValue) throws Exception {
final Manifest manifest = createManifestWithClassPath(classPathValue);
final Path jar = Files.createTempFile(TEST_SCRATCH_DIR, "8338445", ".jar");
// create the JAR file with the given manifest and an arbitrary file
JarUtils.createJarFile(jar, manifest, TEST_SCRATCH_DIR, Path.of(RESOURCE_NAME));
System.out.println("created jar at " + jar + " with manifest:");
manifest.write(System.out);
final URL[] urlClassPath = new URL[]{jar.toUri().toURL()};
// Create a URLClassLoader backed by the JAR file and load a resource
// and verify the resource contents.
// Then close the classloader. After the classloader is closed
// issue a delete on the underlying JAR file on the filesystem. The delete is expected
// to succeed.
try (final URLClassLoader cl = new URLClassLoader(urlClassPath)) {
try (final InputStream is = cl.getResourceAsStream(RESOURCE_NAME)) {
assertNotNull(is, RESOURCE_NAME + " not located by classloader in classpath "
+ Arrays.toString(urlClassPath));
final String content = new String(is.readAllBytes(), US_ASCII);
assertEquals(RESOURCE_CONTENT, content, "unexpected content in " + RESOURCE_NAME);
}
}
// now delete the JAR file and verify the delete worked
Files.delete(jar);
assertFalse(Files.exists(jar), jar + " exists even after being deleted");
}
private static Manifest createManifestWithClassPath(final String classPathValue) {
final Manifest manifest = new Manifest();
final Attributes mainAttributes = manifest.getMainAttributes();
mainAttributes.putValue("Manifest-Version", "1.0");
mainAttributes.putValue("Class-Path", classPathValue);
return manifest;
}
}

View file

@ -0,0 +1,175 @@
/*
* Copyright (c) 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
* @bug 7179567
* @summary Test that URLClassLoader public constructors and factory methods
* throw NullPointerException when appropriate.
*
* Tests whether URLClassLoader public constructors and factory methods throw
* appropriate NullPointerExceptions for 1) a null URL array parameter, and
* 2) a non-null URL array containing a null element.
*/
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarFile;
public class NullURLTest {
JarFile jarFile;
public static void main(String[] args) throws Throwable {
new NullURLTest();
}
NullURLTest() throws Throwable {
File local = new File(System.getProperty("test.src", "."), "jars");
String path = "jar:file:"
+ local.getPath()
+ "/class_path_test.jar!/Foo.class";
URL validURL = new URL(path);
URL[] validURLArray = new URL[] { validURL, validURL };
URL[] invalidURLArray = new URL[] { validURL, null };
int failures = 0;
URLClassLoader loader;
try {
loader = new URLClassLoader(validURLArray);
} catch (Throwable t) {
System.err.println("URLClassLoader(validURLArray) threw " + t);
failures++;
}
try {
loader = new URLClassLoader(null);
System.err.println("URLClassLoader(null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = new URLClassLoader(invalidURLArray);
System.err.println("URLClassLoader(invalidURLArray) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = new URLClassLoader(validURLArray, null);
} catch (Throwable t) {
System.err.println("URLClassLoader(validURLArray, null) threw " + t);
failures++;
}
try {
loader = new URLClassLoader(null, null);
System.err.println("URLClassLoader(null, null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = new URLClassLoader(invalidURLArray, null);
System.err.println("URLClassLoader(invalidURLArray, null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = new URLClassLoader(validURLArray, null, null);
} catch (Throwable t) {
System.err.println("URLClassLoader(validURLArray, null, null) threw " + t);
failures++;
}
try {
loader = new URLClassLoader((URL[])null, null, null);
System.err.println("URLClassLoader(null, null, null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = new URLClassLoader(invalidURLArray, null, null);
System.err.println("URLClassLoader(invalidURLArray, null, null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = URLClassLoader.newInstance(validURLArray);
} catch (Throwable t) {
System.err.println("URLClassLoader.newInstance(validURLArray) threw " + t);
failures++;
}
try {
loader = URLClassLoader.newInstance(null);
System.err.println("URLClassLoader.newInstance(null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = URLClassLoader.newInstance(invalidURLArray);
System.err.println("URLClassLoader.newInstance(invalidURLArray) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = URLClassLoader.newInstance(validURLArray, null);
} catch (Throwable t) {
System.err.println("URLClassLoader.newInstance(validURLArray, null) threw " + t);
failures++;
}
try {
loader = URLClassLoader.newInstance(null, null);
System.err.println("URLClassLoader.newInstance(null, null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
try {
loader = URLClassLoader.newInstance(invalidURLArray, null);
System.err.println("URLClassLoader.newInstance(invalidURLArray, null) did not throw NPE");
failures++;
} catch (NullPointerException e) {
// expected
}
if (failures != 0) {
throw new Exception("URLClassLoader NullURLTest had "+failures+" failures!");
}
}
}

View file

@ -0,0 +1,171 @@
/*
* Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8264048
*
* @run main/othervm RemoveJar true true testpkg.Test testpkg.Test testjar/
* @run main/othervm RemoveJar true true testpkg.Test testpkg.Missing testjar/
* @run main/othervm RemoveJar true true testpkg.Missing testpkg.Test testjar/
* @run main/othervm RemoveJar true true testpkg.Missing testpkg.Missing testjar/
*
* @run main/othervm RemoveJar true false testpkg.Test testpkg.Test testjar/
* @run main/othervm RemoveJar true false testpkg.Test testpkg.Missing testjar/
* @run main/othervm RemoveJar true false testpkg.Missing testpkg.Test testjar/
* @run main/othervm RemoveJar true false testpkg.Missing testpkg.Missing testjar/
*
* @run main/othervm RemoveJar false true testpkg.Test testpkg.Test testjar/
* @run main/othervm RemoveJar false true testpkg.Test testpkg.Missing testjar/
* @run main/othervm RemoveJar false true testpkg.Missing testpkg.Test testjar/
* @run main/othervm RemoveJar false true testpkg.Missing testpkg.Missing testjar/
*
* @run main/othervm RemoveJar false false testpkg.Test testpkg.Test testjar/
* @run main/othervm RemoveJar false false testpkg.Test testpkg.Missing testjar/
* @run main/othervm RemoveJar false false testpkg.Missing testpkg.Test testjar/
* @run main/othervm RemoveJar false false testpkg.Missing testpkg.Missing testjar/
*
* @run main/othervm RemoveJar true true testpkg.Test testpkg.Test badpath
*
* @summary URLClassLoader.close() doesn't close cached JAR file on Windows when load() fails
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;
import java.util.zip.ZipException;
import java.util.spi.ToolProvider;
public class RemoveJar {
private final static String TEST_PKG = "testpkg";
private final static String JAR_DIR = "testjar/" + TEST_PKG;
private final static String FILE_NAME = "testjar.jar";
private final static ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final static PrintStream out = new PrintStream(baos);
private final static ToolProvider JAR_TOOL = ToolProvider.findFirst("jar")
.orElseThrow(() ->
new RuntimeException("jar tool not found")
);
private static void buildJar() throws IOException {
// create dir
mkdir(JAR_DIR);
// create file
Path path = Paths.get(JAR_DIR);
String src = "package " + TEST_PKG + ";\n" +
"class Test {}\n";
Files.write(Paths.get(JAR_DIR + "/Test.java"), src.getBytes());
// compile class
compile(JAR_DIR + "/Test.java");
// package jar
jar("-cf testjar.jar " + JAR_DIR);
}
public static void main(String args[]) throws Exception {
buildJar();
URLClassLoader loader = null;
URL url = null;
Path path = Paths.get(FILE_NAME);
boolean useCacheFirst = Boolean.parseBoolean(args[0]);
boolean useCacheSecond = Boolean.parseBoolean(args[1]);
String firstClass = args[2];
String secondClass = args[3];
String subPath = args[4];
try {
String path_str = path.toUri().toURL().toString();
URLConnection.setDefaultUseCaches("jar", useCacheFirst);
url = new URL("jar", "", path_str + "!/" + subPath);
loader = new URLClassLoader(new URL[]{url});
loader.loadClass(firstClass);
} catch (Exception e) {
System.err.println("EXCEPTION: " + e);
}
try {
URLConnection.setDefaultUseCaches("jar", useCacheSecond);
loader.loadClass(secondClass);
} catch (Exception e) {
System.err.println("EXCEPTION: " + e);
} finally {
loader.close();
Files.delete(path);
}
}
private static Stream<Path> mkpath(String... args) {
return Arrays.stream(args).map(d -> Paths.get(".", d.split("/")));
}
private static void mkdir(String cmdline) {
System.out.println("mkdir -p " + cmdline);
mkpath(cmdline.split(" +")).forEach(p -> {
try {
Files.createDirectories(p);
} catch (IOException x) {
throw new UncheckedIOException(x);
}
});
}
private static void jar(String cmdline) throws IOException {
System.out.println("jar " + cmdline);
baos.reset();
// the run method catches IOExceptions, we need to expose them
ByteArrayOutputStream baes = new ByteArrayOutputStream();
PrintStream err = new PrintStream(baes);
PrintStream saveErr = System.err;
System.setErr(err);
int rc = JAR_TOOL.run(out, err, cmdline.split(" +"));
System.setErr(saveErr);
if (rc != 0) {
String s = baes.toString();
if (s.startsWith("java.util.zip.ZipException: duplicate entry: ")) {
throw new ZipException(s);
}
throw new IOException(s);
}
}
/* run javac <args> */
private static void compile(String... args) {
if (com.sun.tools.javac.Main.compile(args) != 0) {
throw new RuntimeException("javac failed: args=" + Arrays.toString(args));
}
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 1998, 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 4128326 4127567
* @summary Test URL parsing
*
*/
import java.net.*;
import java.io.*;
public class URLParsing {
public static void main(String[] args) throws Exception {
File local = new File(System.getProperty("test.src", "."), "jars");
String path = "jar:file:"
+ local.getPath()
+ "/class_path_test.jar!/Foo.java";
URL aURL = new URL(path);
URL testURL = new URL(aURL, "foo/../Foo.java");
InputStream in = testURL.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String firstLine = reader.readLine();
if (!firstLine.startsWith("public class Foo {"))
throw new RuntimeException("Jar or File parsing failure.");
}
}

View file

@ -0,0 +1,216 @@
/*
* Copyright (c) 2009, 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 4167874
* @modules java.logging
* jdk.httpserver
* jdk.compiler
* @library ../../../../com/sun/net/httpserver
* /test/lib
* @build jdk.test.lib.compiler.CompilerUtils
* jdk.test.lib.util.FileUtils
* jdk.test.lib.util.JarUtils
* jdk.test.lib.Platform
* FileServerHandler
* @run main/othervm CloseTest
* @summary URL-downloaded jar files can consume all available file descriptors
*/
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import jdk.test.lib.compiler.CompilerUtils;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.JarUtils;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class CloseTest extends Common {
private static final String WORK_DIR = System.getProperty("user.dir")
+ "/";
//
// needs two jar files test1.jar and test2.jar with following structure
//
// com/foo/TestClass
// com/foo/TestClass1
// com/foo/Resource1
// com/foo/Resource2
//
// and a directory hierarchy with the same structure/contents
public static void main(String args[]) throws Exception {
setup();
startHttpServer(WORK_DIR + "serverRoot/");
String testjar = WORK_DIR + "test.jar";
copyFile(WORK_DIR + "test1.jar", testjar);
test(testjar, 1);
// repeat test with different implementation
// of test.jar (whose TestClass.getValue() returns 2
copyFile(WORK_DIR + "test2.jar", testjar);
test(testjar, 2);
// repeat test using a directory of files
String testdir = WORK_DIR + "testdir/";
rm_minus_rf(new File(testdir));
copyDir(WORK_DIR + "test1/", testdir);
test(testdir, 1);
testdir = WORK_DIR + "testdir/";
rm_minus_rf(new File(testdir));
copyDir(WORK_DIR + "test2/", testdir);
test(testdir, 2);
getHttpServer().stop(3);
}
// create a loader on jarfile (or directory), plus a http loader
// load a class , then look for a resource
// also load a class from http loader
// then close the loader
// check further new classes/resources cannot be loaded
// check jar (or dir) can be deleted
// check existing classes can be loaded
// check boot classes can be loaded
static void test(String name, int expectedValue) throws Exception {
URL url = new URL("file", null, name);
URL url2 = getServerURL();
System.out.println("Doing tests with URL: " + url + " and " + url2);
URL[] urls = new URL[2];
urls[0] = url;
urls[1] = url2;
URLClassLoader loader = new URLClassLoader(urls);
Class testclass = loadClass("com.foo.TestClass", loader, true);
Class class2 = loadClass("Test", loader, true); // from http
class2.newInstance();
Object test = testclass.newInstance();
Method method = testclass.getDeclaredMethods()[0]; // int getValue();
int res = (Integer) method.invoke(test);
if (res != expectedValue) {
throw new RuntimeException("wrong value from getValue() [" + res +
"/" + expectedValue + "]");
}
// should find /resource1
URL u1 = loader.findResource("com/foo/Resource1");
if (u1 == null) {
throw new RuntimeException("can't find com/foo/Resource1 in test1.jar");
}
loader.close();
// should NOT find /resource2 even though it is in jar
URL u2 = loader.findResource("com/foo/Resource2");
if (u2 != null) {
throw new RuntimeException("com/foo/Resource2 unexpected in test1.jar");
}
// load tests
loadClass("com.foo.TestClass1", loader, false);
loadClass("com.foo.TestClass", loader, true);
loadClass("java.util.ArrayList", loader, true);
// now check we can delete the path
rm_minus_rf(new File(name));
System.out.println(" ... OK");
}
static HttpServer httpServer;
static HttpServer getHttpServer() {
return httpServer;
}
static URL getServerURL() throws Exception {
int port = httpServer.getAddress().getPort();
return URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(port)
.path("/")
.toURL();
}
static void startHttpServer(String docroot) throws Exception {
httpServer = HttpServer.create(
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0),
10);
HttpContext ctx = httpServer.createContext(
"/", new FileServerHandler(docroot)
);
httpServer.start();
}
/**
* Prepare jars files for the tests
*/
private static void setup () throws IOException {
String[] tests = new String[]{"test1", "test2"};
Path workDir = Paths.get(WORK_DIR);
Path testSrc = Paths.get(System.getProperty("test.src"));
for (String test : tests) {
Path testSrcDir = testSrc.resolve(test);
Path testTargetDir = workDir.resolve(test);
// Compile sources for corresponding test
CompilerUtils.compile(testSrcDir, testTargetDir);
// Copy all resources
Path packages = Paths.get("com", "foo");
Path copySrcDir = testSrcDir.resolve(packages);
Path copyTargetDir = testTargetDir.resolve(packages);
Files.createDirectories(copyTargetDir);
Path res1 = Paths.get("Resource1");
Path res2 = Paths.get("Resource2");
Files.copy(copySrcDir.resolve(res1), copyTargetDir.resolve(res1),
REPLACE_EXISTING);
Files.copy(copySrcDir.resolve(res2), copyTargetDir.resolve(res2),
REPLACE_EXISTING);
// Create jar
JarUtils.createJarFile(workDir.resolve(test + ".jar"), testTargetDir);
}
// Copy and compile server test class
Path serverRoot = Paths.get("serverRoot");
Path targetDir = workDir.resolve(serverRoot);
Path file = Paths.get("Test.java");
Files.createDirectories(targetDir);
Files.copy(testSrc.resolve(serverRoot).resolve(file),
targetDir.resolve(file), REPLACE_EXISTING);
CompilerUtils.compile(targetDir, targetDir);
}
}

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2011, 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.
*/
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import jdk.test.lib.util.FileUtils;
import static java.nio.file.StandardCopyOption.*;
public class Common {
static void copyFile (String src, String dst) {
copyFile (new File(src), new File(dst));
}
static void copyDir (String src, String dst) {
copyDir (new File(src), new File(dst));
}
static void copyFile (File src, File dst) {
try {
if (!src.isFile()) {
throw new RuntimeException ("File not found: " + src.toString());
}
Files.copy(src.toPath(), dst.toPath(), REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException (e);
}
}
static void rm_minus_rf (File path) throws IOException, InterruptedException {
if (!path.exists())
return;
FileUtils.deleteFileTreeWithRetry(path.toPath());
}
static void copyDir (File src, File dst) {
if (!src.isDirectory()) {
throw new RuntimeException ("Dir not found: " + src.toString());
}
if (dst.exists()) {
throw new RuntimeException ("Dir exists: " + dst.toString());
}
dst.mkdir();
String[] names = src.list();
File[] files = src.listFiles();
for (int i=0; i<files.length; i++) {
String f = names[i];
if (files[i].isDirectory()) {
copyDir (files[i], new File (dst, f));
} else {
copyFile (new File (src, f), new File (dst, f));
}
}
}
/* expect is true if you expect to find it, false if you expect not to */
static Class loadClass (String name, URLClassLoader loader, boolean expect){
try {
Class clazz = Class.forName (name, true, loader);
if (!expect) {
throw new RuntimeException ("loadClass: "+name+" unexpected");
}
return clazz;
} catch (ClassNotFoundException e) {
if (expect) {
throw new RuntimeException ("loadClass: " +name + " not found");
}
}
return null;
}
}

View file

@ -0,0 +1,141 @@
/*
* Copyright (c) 2011, 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 6899919
* @library /test/lib
* @modules jdk.compiler
* @build jdk.test.lib.compiler.CompilerUtils
* jdk.test.lib.util.FileUtils
* jdk.test.lib.util.JarUtils
* jdk.test.lib.Platform
* @run main/othervm GetResourceAsStream
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import jdk.test.lib.compiler.CompilerUtils;
import jdk.test.lib.util.JarUtils;
public class GetResourceAsStream extends Common {
private static final String WORK_DIR = System.getProperty("user.dir");
/*
* We simply test various scenarios with class/resource files
* and make sure the files can be deleted after closing
* the loader. Therefore, the test will only really be verified
* on Windows. It will still run correctly on other platforms
*/
public static void main (String args[]) throws Exception {
setup();
/* the jar we copy for each test */
File srcfile = new File(WORK_DIR, "foo.jar");
/* the jar we use for the test */
File testfile = new File(WORK_DIR, "test.jar");
copyFile(srcfile, testfile);
test(testfile, false, false);
copyFile(srcfile, testfile);
test(testfile, true, false);
copyFile(srcfile, testfile);
test(testfile, true, true);
// repeat test using a directory of files
File testdir = new File(WORK_DIR, "testdir");
File srcdir = new File(WORK_DIR, "test3");
copyDir(srcdir, testdir);
test(testdir, true, false);
}
// create a loader on jarfile (or directory)
// load a class , then look for a resource
// then close the loader
// check further new classes/resources cannot be loaded
// check jar (or dir) can be deleted
static void test (File file, boolean loadclass, boolean readall)
throws Exception
{
URL[] urls = new URL[] {file.toURI().toURL()};
System.out.println ("Doing tests with URL: " + urls[0]);
URLClassLoader loader = new URLClassLoader (urls);
if (loadclass) {
Class testclass = loadClass ("com.foo.TestClass", loader, true);
}
InputStream s = loader.getResourceAsStream ("hello.txt");
s.read();
if (readall) {
while (s.read() != -1) ;
s.close();
}
loader.close ();
// should not find bye.txt now
InputStream s1 = loader.getResourceAsStream("bye.txt");
if (s1 != null) {
throw new RuntimeException ("closed loader returned resource");
}
// now check we can delete the path
rm_minus_rf (file);
System.out.println (" ... OK");
}
/**
* Prepare jars files for the tests
*/
private static void setup () throws IOException {
Path classes = Paths.get(WORK_DIR);
Path testSrc = Paths.get(System.getProperty("test.src"),
"test1", "com", "foo", "TestClass.java");
Path targetDir = classes.resolve("test3");
Path testTarget = targetDir.resolve("TestClass.java");
Files.createDirectories(targetDir);
Files.copy(testSrc, testTarget, StandardCopyOption.REPLACE_EXISTING);
// Compile sources for corresponding test
CompilerUtils.compile(targetDir, targetDir);
// Prepare txt files
Files.write(targetDir.resolve("hello.txt"), "Hello world".getBytes(),
StandardOpenOption.CREATE);
Files.write(targetDir.resolve("bye.txt"), "Bye world".getBytes(),
StandardOpenOption.CREATE);
// Create jar
JarUtils.createJarFile(classes.resolve("foo.jar"), targetDir);
}
}

View file

@ -0,0 +1,24 @@
test1 and test2 contain two different implementations of the same
classes. They are compiled and placed into two different target directories
and two jar files test1.jar and test2.jar.
The same class is in both jars/directories, but returns a different result
from the TestClass.getValue() method. The test does the following
1. copy test1.jar to a working directory and call it test.jar
2. load class and invoke method (checking result)
3. close the loader
4. delete test.jar (check delete succeeds)
5. copy test2.jar to same dir and repeat the test
6. The two tests are then repeated by copying the directories
test1 and test2.
The loader also includes a http:// URL in its search path and a http
server is used to serve the required class.
serverRoot is used as the root directory for the http server.

View file

@ -0,0 +1,28 @@
/*
* Copyright (c) 2009, 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.
*/
public class Test {
public Test () {
System.out.println ("Test created");
}
}

View file

@ -0,0 +1 @@
Hello World

View file

@ -0,0 +1 @@
Hello World Again

View file

@ -0,0 +1,38 @@
/*
* Copyright (c) 2009, 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 com.foo;
public class TestClass {
public int getValue () {
return 1;
}
}
/*
public class TestClass {
public int getValue () {
return 2;
}
}
*/

View file

@ -0,0 +1,26 @@
/*
* Copyright (c) 2009, 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 com.foo;
public class TestClass1 {}

View file

@ -0,0 +1 @@
Hello World

View file

@ -0,0 +1 @@
Hello World Again

View file

@ -0,0 +1,38 @@
/*
* Copyright (c) 2009, 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 com.foo;
/*
public class TestClass {
public int getValue () {
return 1;
}
}
*/
public class TestClass {
public int getValue () {
return 2;
}
}

View file

@ -0,0 +1,26 @@
/*
* Copyright (c) 2009, 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 com.foo;
public class TestClass1 {}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 2016, 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 8153665
* @summary Test two URLClassLoader define Package object of the same name
* @library /test/lib
* @build jdk.test.lib.compiler.CompilerUtils
* @modules jdk.compiler
* @run testng SplitPackage
*/
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.jar.Manifest;
import jdk.test.lib.compiler.CompilerUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class SplitPackage {
private static final Path SRC_DIR = Paths.get(System.getProperty("test.src", "."));
private static final Path FOO_DIR = Paths.get("foo");
private static final Path BAR_DIR = Paths.get("bar");
@BeforeTest
private void setup() throws Exception {
Files.createDirectory(BAR_DIR);
Path pkgDir = Paths.get("p");
// compile classes in package p
assertTrue(CompilerUtils.compile(SRC_DIR.resolve(pkgDir), BAR_DIR));
// move p.Foo to a different directory
Path foo = pkgDir.resolve("Foo.class");
Files.createDirectories(FOO_DIR.resolve(pkgDir));
Files.move(BAR_DIR.resolve(foo), FOO_DIR.resolve(foo),
StandardCopyOption.REPLACE_EXISTING);
}
@Test
public void test() throws Exception {
URLClassLoader loader1 = new URLClassLoader(new URL[] {
FOO_DIR.toUri().toURL()
});
Loader loader2 = new Loader(new URL[] {
BAR_DIR.toUri().toURL()
}, loader1);
Class<?> foo = Class.forName("p.Foo", true, loader2);
Class<?> bar = Class.forName("p.Bar", true, loader2);
Class<?> baz = Class.forName("p.Baz", true, loader2);
Package pForFoo = loader1.getDefinedPackage("p");
Package pForBar = loader2.getDefinedPackage("p");
assertEquals(pForFoo.getName(), pForBar.getName());
assertTrue(pForFoo != pForBar);
try {
loader2.defineSplitPackage("p");
} catch (IllegalArgumentException e) {
}
}
static class Loader extends URLClassLoader {
Loader(URL[] urls, URLClassLoader parent) {
super(urls, parent);
}
public Package defineSplitPackage(String name) {
Manifest manifest = new Manifest();
return super.definePackage(name, manifest, null);
}
}
}

View file

@ -0,0 +1,27 @@
/*
* 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.
*/
package p;
public class Bar { }

View file

@ -0,0 +1,27 @@
/*
* 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.
*/
package p;
public class Baz { }

View file

@ -0,0 +1,27 @@
/*
* 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.
*/
package p;
public class Foo { }

Binary file not shown.

View file

@ -0,0 +1,42 @@
/*
* Copyright (c) 2004, 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.*;
import java.io.*;
public class Test {
public static void main (String[] args) throws Exception {
test1(args[0]);
}
public static void test1 (String s) throws Exception {
URLClassLoader cl = new URLClassLoader (new URL[] {
new URL ("file:" + s)
});
Class clazz = Class.forName ("Test\u00a3", true, cl);
InputStream is = clazz.getResourceAsStream ("Test\u00a3.class");
is.read();
is = clazz.getResourceAsStream ("Rest\u00a3.class");
is.read();
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 5103449
* @summary REGRESSION: getResourceAsStream is broken in JDK1.5.0-rc
* @library /test/lib
* @build jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* Test
* @run main/othervm TestDriver
*/
import jdk.test.lib.process.ProcessTools;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class TestDriver {
private static final String ARCHIVE_NAME = "test.jar";
private static final String TEST_NAME = "Test";
public static void main(String[] args)
throws Throwable {
Path userDir = Paths.get(System.getProperty("user.dir"));
String basename = userDir.getFileName().toString();
setup(userDir);
ProcessBuilder[] tests = new ProcessBuilder[]{
ProcessTools.createTestJavaProcessBuilder(
TEST_NAME,
"./" + ARCHIVE_NAME
),
ProcessTools.createTestJavaProcessBuilder(
"-cp", ".",
TEST_NAME, "./" + ARCHIVE_NAME
),
ProcessTools.createTestJavaProcessBuilder(
"-cp", "..",
TEST_NAME, "../" + ARCHIVE_NAME
).directory(userDir.resolve("tmp").toFile()),
ProcessTools.createTestJavaProcessBuilder(
"-cp", basename,
TEST_NAME, basename + "/" + ARCHIVE_NAME
).directory(userDir.resolve("..").toFile())};
for (ProcessBuilder test : tests) {
runTest(test);
}
}
private static void setup(Path userDir) throws IOException {
Path src = Paths.get(System.getProperty("test.src"));
Path testJar = src.resolve(ARCHIVE_NAME);
Path testClass = Paths.get(System.getProperty("test.classes"),
TEST_NAME + ".class");
Files.copy(testJar, userDir.resolve(ARCHIVE_NAME), REPLACE_EXISTING);
Files.copy(testClass, userDir.resolve(TEST_NAME + ".class"),
REPLACE_EXISTING);
Files.createDirectories(userDir.resolve("tmp"));
}
private static void runTest(ProcessBuilder pb) throws Exception {
System.out.println("Testing with command: [" + pb.command() + "]");
ProcessTools.executeProcess(pb)
.outputTo(System.out)
.errorTo(System.err)
.shouldHaveExitValue(0);
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 1999, 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.
*/
public class CheckSealed {
public static void main(String[] argv) throws Exception {
boolean fail = true;
try {
if ("1".equals(argv[0])) {
test1();
test2();
} else if ("2".equals(argv[0])) {
test2();
test1();
}
} catch (java.lang.SecurityException e) {
fail = false;
}
if (fail) {
throw new Exception("Sealing violation undetected.");
}
}
private static void test1() {
p.A.hello();
}
private static void test2() {
p.B.hello();
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4244970
* @summary Test to see if sealing violation is detected correctly
* @library /test/lib
* @build jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* @run main CheckSealedTest
*/
import jdk.test.lib.JDKToolFinder;
import jdk.test.lib.process.ProcessTools;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static jdk.test.lib.process.ProcessTools.createTestJavaProcessBuilder;
import static jdk.test.lib.process.ProcessTools.executeCommand;
public class CheckSealedTest {
private static final String ARCHIVE_NAME = "b.jar";
private static final String TEST_NAME = "CheckSealed";
public static void main(String[] args)
throws Throwable {
String baseDir = System.getProperty("user.dir") + File.separator;
String javac = JDKToolFinder.getTestJDKTool("javac");
setup(baseDir);
String srcDir = System.getProperty("test.src");
String cp = srcDir + File.separator + "a" + File.pathSeparator
+ srcDir + File.separator + "b.jar" + File.pathSeparator
+ ".";
// Compile
ProcessTools.executeCommand(javac, "-cp", cp, "-d", ".",
srcDir + File.separator + TEST_NAME + ".java");
List<String[]> allCMDs = List.of(
// Run test the first time
new String[]{
"-cp", cp, TEST_NAME, "1"
},
// Run test the second time
new String[]{
"-cp", cp, TEST_NAME, "2"
}
);
for (String[] cmd : allCMDs) {
executeCommand(createTestJavaProcessBuilder(cmd))
.outputTo(System.out)
.errorTo(System.out)
.shouldHaveExitValue(0);
}
}
private static void setup(String baseDir) throws IOException {
Path testJar = Paths.get(System.getProperty("test.src"), ARCHIVE_NAME);
Files.copy(testJar, Paths.get(baseDir, ARCHIVE_NAME), REPLACE_EXISTING);
}
}

View file

@ -0,0 +1,17 @@
#
# This makefile is only used to update b.jar and directory a,
# which are checked in to SCCS.
JBIN=../../../../../build/solaris/bin
all: b.jar
b.jar: classes
$(JBIN)/jar cmf manifest b.jar -C b p/B.class
classes:
$(JBIN)/javac -sourcepath a:b ?/p/*.java
clean:
rm -rf b.jar ?/p/*.class

View file

@ -0,0 +1,33 @@
/*
* 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.
*/
package p;
public class A {
public static void hello() {
System.out.println("A");
}
}

Binary file not shown.

View file

@ -0,0 +1,33 @@
/*
* 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.
*/
package p;
public class B {
public static void hello() {
System.out.println("B");
}
}

View file

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Sealed: true