Search in sources :

Example 51 with URLClassLoader

use of java.net.URLClassLoader in project druid by druid-io.

the class InitializationTest method test06GetClassLoaderForExtension.

@Test
public void test06GetClassLoaderForExtension() throws IOException {
    final File some_extension_dir = temporaryFolder.newFolder();
    final File a_jar = new File(some_extension_dir, "a.jar");
    final File b_jar = new File(some_extension_dir, "b.jar");
    final File c_jar = new File(some_extension_dir, "c.jar");
    a_jar.createNewFile();
    b_jar.createNewFile();
    c_jar.createNewFile();
    final URLClassLoader loader = Initialization.getClassLoaderForExtension(some_extension_dir);
    final URL[] expectedURLs = new URL[] { a_jar.toURI().toURL(), b_jar.toURI().toURL(), c_jar.toURI().toURL() };
    final URL[] actualURLs = loader.getURLs();
    Arrays.sort(actualURLs, new Comparator<URL>() {

        @Override
        public int compare(URL o1, URL o2) {
            return o1.getPath().compareTo(o2.getPath());
        }
    });
    Assert.assertArrayEquals(expectedURLs, actualURLs);
}
Also used : URLClassLoader(java.net.URLClassLoader) File(java.io.File) URL(java.net.URL) Test(org.junit.Test)

Example 52 with URLClassLoader

use of java.net.URLClassLoader in project druid by druid-io.

the class InitializationTest method testExtensionsWithSameDirName.

@Test
public void testExtensionsWithSameDirName() throws Exception {
    final String extensionName = "some_extension";
    final File tmpDir1 = temporaryFolder.newFolder();
    final File tmpDir2 = temporaryFolder.newFolder();
    final File extension1 = new File(tmpDir1, extensionName);
    final File extension2 = new File(tmpDir2, extensionName);
    Assert.assertTrue(extension1.mkdir());
    Assert.assertTrue(extension2.mkdir());
    final File jar1 = new File(extension1, "jar1.jar");
    final File jar2 = new File(extension2, "jar2.jar");
    Assert.assertTrue(jar1.createNewFile());
    Assert.assertTrue(jar2.createNewFile());
    final ClassLoader classLoader1 = Initialization.getClassLoaderForExtension(extension1);
    final ClassLoader classLoader2 = Initialization.getClassLoaderForExtension(extension2);
    Assert.assertArrayEquals(new URL[] { jar1.toURL() }, ((URLClassLoader) classLoader1).getURLs());
    Assert.assertArrayEquals(new URL[] { jar2.toURL() }, ((URLClassLoader) classLoader2).getURLs());
}
Also used : URLClassLoader(java.net.URLClassLoader) File(java.io.File) Test(org.junit.Test)

Example 53 with URLClassLoader

use of java.net.URLClassLoader in project hive by apache.

the class ClassNameCompleter method getClassNames.

public static String[] getClassNames() throws IOException {
    Set urls = new HashSet();
    for (ClassLoader loader = Thread.currentThread().getContextClassLoader(); loader != null; loader = loader.getParent()) {
        if (!(loader instanceof URLClassLoader)) {
            continue;
        }
        urls.addAll(Arrays.asList(((URLClassLoader) loader).getURLs()));
    }
    // Now add the URL that holds java.lang.String. This is because
    // some JVMs do not report the core classes jar in the list of
    // class loaders.
    Class[] systemClasses = new Class[] { String.class, javax.swing.JFrame.class };
    for (int i = 0; i < systemClasses.length; i++) {
        URL classURL = systemClasses[i].getResource("/" + systemClasses[i].getName().replace('.', '/') + clazzFileNameExtension);
        if (classURL != null) {
            URLConnection uc = classURL.openConnection();
            if (uc instanceof JarURLConnection) {
                urls.add(((JarURLConnection) uc).getJarFileURL());
            }
        }
    }
    Set classes = new HashSet();
    for (Iterator i = urls.iterator(); i.hasNext(); ) {
        URL url = (URL) i.next();
        try {
            File file = new File(url.getFile());
            if (file.isDirectory()) {
                Set files = getClassFiles(file.getAbsolutePath(), new HashSet(), file, new int[] { 200 });
                classes.addAll(files);
                continue;
            }
            if (!isJarFile(file)) {
                continue;
            }
            JarFile jf = new JarFile(file);
            for (Enumeration e = jf.entries(); e.hasMoreElements(); ) {
                JarEntry entry = (JarEntry) e.nextElement();
                if (entry == null) {
                    continue;
                }
                String name = entry.getName();
                if (isClazzFile(name)) {
                    /* only use class file */
                    classes.add(name);
                } else if (isJarFile(name)) {
                    classes.addAll(getClassNamesFromJar(name));
                } else {
                    continue;
                }
            }
        } catch (IOException e) {
            throw new IOException(String.format("Error reading classpath entry: %s", url), e);
        }
    }
    // now filter classes by changing "/" to "." and trimming the
    // trailing ".class"
    Set classNames = new TreeSet();
    for (Iterator i = classes.iterator(); i.hasNext(); ) {
        String name = (String) i.next();
        classNames.add(name.replace('/', '.').substring(0, name.length() - 6));
    }
    return (String[]) classNames.toArray(new String[classNames.size()]);
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) Enumeration(java.util.Enumeration) JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) TreeSet(java.util.TreeSet) URLClassLoader(java.net.URLClassLoader) Iterator(java.util.Iterator) URLClassLoader(java.net.URLClassLoader) JarFile(java.util.jar.JarFile) File(java.io.File) HashSet(java.util.HashSet)

Example 54 with URLClassLoader

use of java.net.URLClassLoader in project weave by continuuity.

the class WeaveLauncher method createClassLoader.

private static URLClassLoader createClassLoader(File dir, boolean useClassPath) {
    try {
        List<URL> urls = new ArrayList<URL>();
        urls.add(dir.toURI().toURL());
        urls.add(new File(dir, "classes").toURI().toURL());
        urls.add(new File(dir, "resources").toURI().toURL());
        File libDir = new File(dir, "lib");
        File[] files = libDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.getName().endsWith(".jar")) {
                    urls.add(file.toURI().toURL());
                }
            }
        }
        if (useClassPath) {
            InputStream is = ClassLoader.getSystemResourceAsStream("classpath");
            if (is != null) {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                    String line = reader.readLine();
                    if (line != null) {
                        for (String path : line.split(":")) {
                            urls.addAll(getClassPaths(path));
                        }
                    }
                } finally {
                    is.close();
                }
            }
        }
        return new URLClassLoader(urls.toArray(new URL[0]));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) JarInputStream(java.util.jar.JarInputStream) InputStream(java.io.InputStream) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) File(java.io.File) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 55 with URLClassLoader

use of java.net.URLClassLoader in project weave by continuuity.

the class WeaveLauncher method main.

/**
   * Main method to unpackage a jar and run the mainClass.main() method.
   * @param args args[0] is the path to jar file, args[1] is the class name of the mainClass.
   *             The rest of args will be passed the mainClass unmodified.
   */
public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.out.println("Usage: java " + WeaveLauncher.class.getName() + " [jarFile] [mainClass] [use_classpath]");
        return;
    }
    File file = new File(args[0]);
    final File targetDir = createTempDir("weave.launcher");
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            System.out.println("Cleanup directory " + targetDir);
            deleteDir(targetDir);
        }
    });
    System.out.println("UnJar " + file + " to " + targetDir);
    unJar(file, targetDir);
    // Create ClassLoader
    URLClassLoader classLoader = createClassLoader(targetDir, Boolean.parseBoolean(args[2]));
    Thread.currentThread().setContextClassLoader(classLoader);
    System.out.println("Launch class with classpath: " + Arrays.toString(classLoader.getURLs()));
    Class<?> mainClass = classLoader.loadClass(args[1]);
    Method mainMethod = mainClass.getMethod("main", String[].class);
    String[] arguments = Arrays.copyOfRange(args, 3, args.length);
    System.out.println("Launching main: " + mainMethod + " " + Arrays.toString(arguments));
    mainMethod.invoke(mainClass, new Object[] { arguments });
    System.out.println("Main class completed.");
    System.out.println("Launcher completed");
}
Also used : URLClassLoader(java.net.URLClassLoader) Method(java.lang.reflect.Method) File(java.io.File)

Aggregations

URLClassLoader (java.net.URLClassLoader)1351 URL (java.net.URL)872 File (java.io.File)514 Test (org.junit.Test)317 IOException (java.io.IOException)256 ArrayList (java.util.ArrayList)202 MalformedURLException (java.net.MalformedURLException)186 Method (java.lang.reflect.Method)177 InvocationTargetException (java.lang.reflect.InvocationTargetException)68 JarFile (java.util.jar.JarFile)54 InputStream (java.io.InputStream)50 HashSet (java.util.HashSet)49 HashMap (java.util.HashMap)44 URISyntaxException (java.net.URISyntaxException)41 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)35 Path (java.nio.file.Path)33 QuickTest (com.hazelcast.test.annotation.QuickTest)32 Test (org.junit.jupiter.api.Test)28 URI (java.net.URI)27 List (java.util.List)27