1/*
2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * Portions Copyright (c) 2013 IBM Corporation
26 */
27
28/* @test
29 * @bug 7183373
30 * @summary URLClassLoader fails to close handles to Jar files opened during
31 *          getResource()
32 */
33
34import java.io.*;
35import java.net.*;
36import java.util.zip.*;
37
38public class JarLoaderTest {
39    public static void main(String[] args) throws Exception {
40        // Create a JAR file
41        File f = new File("urlcl" + 1 + ".jar");
42        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
43
44        // add a file
45        zos.putNextEntry(new ZipEntry("TestResource"));
46        byte[] b = "This is a test resource".getBytes();
47        zos.write(b, 0, b.length);
48        zos.close();
49
50        // Load the file using cl.getResource()
51        URLClassLoader cl = new URLClassLoader(new URL[] { new URL("jar:" +
52            f.toURI().toURL() + "!/")}, null);
53        cl.getResource("TestResource");
54
55        // Close the class loader - this should free up all of its Closeables,
56        // including the JAR file
57        cl.close();
58
59        // Try to delete the JAR file
60        f.delete();
61
62        // Check to see if the file was deleted
63        if (f.exists()) {
64            System.out.println(
65                "Test FAILED: Closeables failed to close handle to jar file");
66            // Delete the jar using a workaround
67            for (URL u : cl.getURLs()) {
68                if (u.getProtocol().equals("jar")) {
69                    ((JarURLConnection)u.openConnection()).getJarFile().close();
70                }
71                f.delete();
72            }
73            throw new RuntimeException("File could not be deleted");
74        } else {
75            System.out.println("Test PASSED");
76        }
77    }
78}
79