Java Code Examples for java.net.URLClassLoader

The following are top voted examples for showing how to use java.net.URLClassLoader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: elasticsearch_my   File: TikaImpl.java   Source Code and License 8 votes vote down vote up
static PermissionCollection getRestrictedPermissions() {
    Permissions perms = new Permissions();
    // property/env access needed for parsing
    perms.add(new PropertyPermission("*", "read"));
    perms.add(new RuntimePermission("getenv.TIKA_CONFIG"));

    // add permissions for resource access:
    // classpath
    addReadPermissions(perms, JarHell.parseClassPath());
    // plugin jars
    if (TikaImpl.class.getClassLoader() instanceof URLClassLoader) {
        addReadPermissions(perms, ((URLClassLoader)TikaImpl.class.getClassLoader()).getURLs());
    }
    // jvm's java.io.tmpdir (needs read/write)
    perms.add(new FilePermission(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "-",
                                 "read,readlink,write,delete"));
    // current hacks needed for POI/PDFbox issues:
    perms.add(new SecurityPermission("putProviderProperty.BC"));
    perms.add(new SecurityPermission("insertProvider"));
    perms.add(new ReflectPermission("suppressAccessChecks"));
    // xmlbeans, use by POI, needs to get the context classloader
    perms.add(new RuntimePermission("getClassLoader"));
    perms.setReadOnly();
    return perms;
}
 
Example 2
Project: plugin-prov   File: TerraformUtilsTest.java   Source Code and License 6 votes vote down vote up
private void checkCommands(final String os, final String... command) throws ReflectiveOperationException {
	final URL[] urLs = ((URLClassLoader) Main.class.getClassLoader()).getURLs();
	ThreadClassLoaderScope scope = null;
	try {
		System.setProperty("os.name", os);
		final URLClassLoader urlClassLoader = new URLClassLoader(urLs, null);
		scope = new ThreadClassLoaderScope(urlClassLoader);
		final Object terra = urlClassLoader.loadClass("org.ligoj.app.plugin.prov.terraform.TerraformUtils").newInstance();
		final Object mock = MethodUtils.invokeStaticMethod(urlClassLoader.loadClass("org.mockito.Mockito"), "mock",
				urlClassLoader.loadClass("org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource"));
		FieldUtils.writeField(terra, "configuration", mock, true);
		Assert.assertEquals(Arrays.asList(command),
				((ProcessBuilder) MethodUtils.invokeMethod(terra, true, "newBuilder", new Object[] { new String[] { "terraform" } }))
						.command());
	} finally {
		IOUtils.closeQuietly(scope);
	}
}
 
Example 3
Project: libmanager   File: BungeeCordLibraryManager.java   Source Code and License 6 votes vote down vote up
@Override
public LibraryResolver getLibraryResolver(Object realm) {
    if (!(realm instanceof Plugin))
        throw new IllegalArgumentException("Only realms of type " + Plugin.class.getName() + " are supported");
    Plugin plugin = (Plugin) realm;
    String name = plugin.getDescription().getName();
    ClassLoader classLoader = realm.getClass().getClassLoader();
    if (!(classLoader instanceof URLClassLoader))
        throw new UnsupportedOperationException("Plugin " + name + " was not loaded by a URLClassLoader");
    return libraryResolvers.computeIfAbsent(name, n -> new ClassLoaderLibraryResolver(
            repositorySystem,
            createSession(),
            remoteRepositorySupplier,
            (URLClassLoader) classLoader,
            plugin.getLogger()
    ));
}
 
Example 4
Project: incubator-netbeans   File: TestUtilities.java   Source Code and License 6 votes vote down vote up
@CheckForNull
public static Path getJRTFS() throws IOException {
    final File java9 = getJava9Home();
    if (java9 == null) {
        return null;
    }
    final File jrtFsProvider = new File(java9,"jrt-fs.jar"); //NOI18N
    if (jrtFsProvider.exists() && jrtFsProvider.isFile() && jrtFsProvider.canRead()) {
        final ClassLoader cl = new URLClassLoader(new URL[]{
            BaseUtilities.toURI(jrtFsProvider).toURL()
        });
        final ServiceLoader<FileSystemProvider> sl = ServiceLoader.load(FileSystemProvider.class, cl);
        FileSystemProvider jrtp = null;
        for (FileSystemProvider fsp : sl) {
            if ("jrt".equals(fsp.getScheme())) {    //NOI18N
                jrtp = fsp;
                break;
            }
        }
        if (jrtp != null) {
            return jrtp.getPath(URI.create("jrt:/"));   //NOI18N
        }
    }
    return null;
}
 
Example 5
Project: jdk8u-jdk   File: TestDaemonThread.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {


    try {
        URL u = this.getClass().getClassLoader().getResource("DummyClass.class");
        String path = u.getPath();
        String parent = u.getPath().substring(0, path.lastIndexOf('/')+1);
        URL parentURL = new URL(u, parent);
        System.out.println(parentURL);
        /* Load lots of class by creating multiple classloaders */
        for(;;) {
            ClassLoader cl = new URLClassLoader(new URL[] {parentURL}, null);
            cl.loadClass("DummyClass");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Project: hadoop   File: TestMRCJCJobConf.java   Source Code and License 6 votes vote down vote up
/**
 * Given a path with a jar, make a classloader with that jar on the
 * classpath, and check that findContainingJar can correctly
 * identify the path of the jar.
 */
private void testJarAtPath(String path) throws Exception {
  File jar = new File(path).getAbsoluteFile();
  assertTrue(jar.exists());

  URL urls[] = new URL[] {
    jar.toURI().toURL()
  };

  ClassLoader cl = new URLClassLoader(urls);
  Class clazz = Class.forName(CLASSNAME, true, cl);
  assertNotNull(clazz);

  String containingJar = ClassUtil.findContainingJar(clazz);
  assertEquals(jar.getAbsolutePath(), containingJar);
}
 
Example 7
Project: incubator-netbeans   File: MultiURLClassLoaderTest.java   Source Code and License 6 votes vote down vote up
/** This method is called before the actual test method to allow
     * the benchmark to prepare accordingly to informations available
     * through {@link #getIterationCount}, {@link #getArgument} and {@link #getName}.
     * This method can use assertions to signal failure of the test.
     * @throws Exception This method can throw any exception which is treated as a error in the testing code
     * or testing enviroment.
     */
    protected void setUp() throws Exception {
        int size = getIntValue(CLASS_NO_KEY);
        
        FileObject[] fileObjects = mfstest.setUpFileObjects(size);
        FileWrapper[] wrappers = mfstest.getFileWrappers();
        
        URLClassLoader[] parents = new URLClassLoader[wrappers.length];
        for (int i = 0; i < parents.length; i++) {
            parents[i] = new URLClassLoader(new URL[] { wrappers[i].getMnt().toURL() });
        }
        
//        MultiURLClassLoader multicloader = new MultiURLClassLoader(new URL[] {}, parents);
        ClassLoader multicloader = new ProxyClassLoader(parents);
        
        instanceObjects = fileObjects2InstanceDataObjects(fileObjects);
        setClassLoader(instanceObjects, multicloader);
    }
 
Example 8
Project: dubbo2   File: JdkCompiler.java   Source Code and License 6 votes vote down vote up
public JdkCompiler(){
    options = new ArrayList<String>();
    options.add("-target");
    options.add("1.6");
    StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader instanceof URLClassLoader 
            && (! loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> files = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                files.add(new File(url.getFile()));
            }
            manager.setLocation(StandardLocation.CLASS_PATH, files);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
        public ClassLoaderImpl run() {
            return new ClassLoaderImpl(loader);
        }
    });
    javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
 
Example 9
Project: smart-testing   File: LoaderVersionExtractorTestNgTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_should_load_testng_version() throws MalformedURLException {
    // given
    File junitFile = Maven
        .resolver()
        .resolve("org.testng:testng:" + testNgVersion)
        .withoutTransitivity()
        .asSingleFile();

    URL[] junitUrl = {junitFile.toURI().toURL()};
    URLClassLoader urlClassLoader = new URLClassLoader(junitUrl);

    // when
    String junitVersion =
        LoaderVersionExtractor.getVersionFromClassLoader(LoaderVersionExtractor.LIBRARY_TEST_NG, urlClassLoader);

    // then
    assertThat(junitVersion).isEqualTo(testNgVersion);
}
 
Example 10
Project: iwant-demo   File: Iwant.java   Source Code and License 6 votes vote down vote up
public static ClassLoader classLoader(ClassLoader parent,
		List<File> locations) {
	URL[] urls = new URL[locations.size()];
	for (int i = 0; i < locations.size(); i++) {
		File location = locations.get(i);
		URL asUrl = fileToUrl(location);
		// TODO own type so we don't need to slash back and forth
		asUrl = withTrailingSlashIfDir(asUrl);
		urls[i] = asUrl;
	}
	if (parent != null) {
		return new URLClassLoader(urls, parent);
	} else {
		return new URLClassLoader(urls);
	}
}
 
Example 11
Project: openjdk-jdk10   File: LeakTest.java   Source Code and License 6 votes vote down vote up
private static WeakReference<ClassLoader>
        testShadow(Class<?> originalTestClass) throws Exception {
    String[] cpaths = System.getProperty("test.classes", ".")
                            .split(File.pathSeparator);
    URL[] urls = new URL[cpaths.length];
    for (int i=0; i < cpaths.length; i++) {
        urls[i] = Paths.get(cpaths[i]).toUri().toURL();
    }

    URLClassLoader shadowLoader =
            new ShadowClassLoader(urls, originalTestClass.getClassLoader().getParent());
    System.out.println("Shadow loader is " + shadowLoader);
    String className = originalTestClass.getName();
    Class<?> testClass = Class.forName(className, false, shadowLoader);
    if (testClass.getClassLoader() != shadowLoader) {
        throw new IllegalArgumentException("Loader didn't work: " +
                testClass.getClassLoader() + " != " + shadowLoader);
    }
    Method main = testClass.getMethod("main", String[].class);
    main.invoke(null, (Object) new String[0]);
    return new WeakReference<ClassLoader>(shadowLoader);
}
 
Example 12
Project: plugin-prov   File: TerraformResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void toFile() throws IOException {
	ThreadClassLoaderScope scope = null;
	try {
		final PluginsClassLoader classLoader = Mockito.mock(PluginsClassLoader.class);
		scope = new ThreadClassLoaderScope(new URLClassLoader(new URL[0], classLoader));
		final File file = new File("");
		final Subscription entity = new Subscription();
		entity.setId(15);
		Mockito.when(classLoader.toFile(entity, "15", "some")).thenReturn(file);
		Assert.assertSame(file, resource.toFile(entity, "some"));
		Assert.assertNotNull(PluginsClassLoader.getInstance());
	} finally {
		IOUtils.closeQuietly(scope);
	}
}
 
Example 13
Project: AgentWorkbench   File: Runner.java   Source Code and License 6 votes vote down vote up
private static void addURLs(URL[] jars) throws Exception {
    URLClassLoader loader =
        (URLClassLoader)Thread.currentThread().getContextClassLoader();

    //bypass protected access.
    Method addURL =
        URLClassLoader.class.getDeclaredMethod("addURL",
                                               new Class[] {
                                                   URL.class
                                               });

    addURL.setAccessible(true); //pound sand.

    for (int i=0; i<jars.length; i++) {
        addURL.invoke(loader, new Object[] { jars[i] });
    }
}
 
Example 14
Project: openjdk-jdk10   File: B7050028.java   Source Code and License 6 votes vote down vote up
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()));
}
 
Example 15
Project: Re-Collector   File: DriverLoader.java   Source Code and License 6 votes vote down vote up
/**
 * 加载对应路径jar包里的对应驱动
 *
 * @param fname 对应路径  如: lib4/ojdbc14.jar
 * @param dname 驱动名  如: oracle.jdbc.driver.OracleDriver
 * @return 加载到的驱动    java.sql.Driver
 * @throws Exception
 * @author tangxr
 */
public static Driver getDriverLoaderByName(String fname, String dname) throws Exception {
    if (null == fname || "".equals(fname)) {
        LOG.error("对应的驱动路径不存在,请确认.");
        return null;
    }
    if (null == dname || "".equals(dname)) {
        LOG.error("对应的驱动类的名字不存在.");
        return null;
    }
    File file = new File(fname);
    if (!file.exists()) {
        LOG.error("对应的驱动jar不存在.");
        return null;
    }
    URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()});
    loader.clearAssertionStatus();

    return (Driver) loader.loadClass(dname).newInstance();

}
 
Example 16
Project: manifold   File: CompilationTest.java   Source Code and License 6 votes vote down vote up
@Test
@Ignore("Causes problems with gradle test invocation")
public void testCompilation() throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
  List<IDirectory> sourcePath = new ArrayList<>( ManifoldHost.getGlobalModule().getSourcePath() );
  sourcePath.add( ManifoldHost.getFileSystem().getIDirectory( JavacTask.class.getProtectionDomain().getCodeSource().getLocation() ) );
  ClassLoader cl = new URLClassLoader( sourcePath.stream().map( e ->
                                                                {
                                                                  try
                                                                  {
                                                                    return e.toURI().toURL();
                                                                  }
                                                                  catch( MalformedURLException e1 )
                                                                  {
                                                                    throw new RuntimeException( e1 );
                                                                  }
                                                                } ).toArray( URL[]::new ), null );
  Class<?> cls = Class.forName( Tests.class.getName(), true, cl );
  cls.newInstance();
}
 
Example 17
Project: ipack   File: MissingEntryException.java   Source Code and License 6 votes vote down vote up
public String getDebugMsg()
{
    if (debugMsg == null)
    {
        debugMsg = "Can not find entry " + key + " in resource file " + resource + " for the locale " + locale + ".";
        if (loader instanceof URLClassLoader)
        {
            URL[] urls = ((URLClassLoader) loader).getURLs();
            debugMsg += " The following entries in the classpath were searched: ";
            for (int i = 0; i != urls.length; i++)
            {
                debugMsg += urls[i] + " ";
            }
        }
    }
    return debugMsg;
}
 
Example 18
Project: jdk8u-jdk   File: JdiLoadedByCustomLoader.java   Source Code and License 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // create files from given arguments and tools.jar
    File f1 = new File(args[0]);
    String home = System.getProperty("java.home");
    String tools = ".." + File.separatorChar + "lib" +
        File.separatorChar + "tools.jar";
    File f2 = (new File(home, tools)).getCanonicalFile();

    // create class loader
    URL[] urls = { f1.toURL(), f2.toURL() };
    URLClassLoader cl = new URLClassLoader(urls);

    // load ListConnectors using the class loader
    // and then invoke the list method.
    Class c = Class.forName("ListConnectors", true, cl);
    Method m = c.getDeclaredMethod("list");
    Object o = c.newInstance();
    m.invoke(o);
}
 
Example 19
Project: lams   File: ClasspathUtilsTest.java   Source Code and License 6 votes vote down vote up
public void testGetClasspathComponentsFromClassLoader() throws MalformedURLException
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try
    {
        File file = new File("/some/package/dir");
        URL[] urls = new URL[] { file.toURL() };            
        // assert my package can't be found yet
        List components = ClasspathUtils.getClasspathComponents();
        Collections.sort(components);
        assertTrue(Collections.binarySearch(components, file.getPath()) < 0);
        // test my package is found
        URLClassLoader ucl = new URLClassLoader(urls, classLoader);
        Thread.currentThread().setContextClassLoader(ucl);
        components = ClasspathUtils.getClasspathComponents();
        Collections.sort(components);
        assertTrue( Collections.binarySearch(components, file.getAbsolutePath()) >= 0);
    }
    finally
    {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}
 
Example 20
Project: uavstack   File: PackageHelper.java   Source Code and License 6 votes vote down vote up
private static void getClassNameFromClsLoader(List<String> fileNames, boolean childPackage, String packagePath,
        URL url, ClassLoader cl) {

    List<String> tempFileNames = null;
    if (url != null) {
        String type = url.getProtocol();
        if ("file".equals(type)) {
            tempFileNames = getClassNameByFile(url.getPath(), childPackage);
        }
        else if ("jar".equals(type)) {
            tempFileNames = getClassNameByJar(url.getPath(), childPackage);
        }
    }
    else {
        tempFileNames = getClassNameByJars(((URLClassLoader) cl).getURLs(), packagePath, childPackage);
    }

    if (tempFileNames != null) {
        fileNames.addAll(tempFileNames);
    }
}
 
Example 21
Project: openjdk-jdk10   File: VersionHelper.java   Source Code and License 5 votes vote down vote up
/**
 * @param className A non-null fully qualified class name.
 * @param codebase  A non-null, space-separated list of URL strings.
 */
public Class<?> loadClass(String className, String codebase)
        throws ClassNotFoundException, MalformedURLException {

    ClassLoader parent = getContextClassLoader();
    ClassLoader cl =
            URLClassLoader.newInstance(getUrlArray(codebase), parent);

    return loadClass(className, cl);
}
 
Example 22
Project: openjdk-jdk10   File: ClassLoader_loadClass01.java   Source Code and License 5 votes vote down vote up
public static String test(int i) throws ClassNotFoundException {
    final URLClassLoader classLoader = new URLClassLoader(new URL[0], String.class.getClassLoader());
    if (i == 0) {
        return classLoader.loadClass("java.lang.String").toString();
    } else if (i == 1) {
        return classLoader.loadClass("[Ljava.lang.String;").toString();
    } else if (i == 2) {
        return classLoader.loadClass("java.lang.String[]").toString();
    }
    return null;
}
 
Example 23
Project: gradle-circle-style   File: CircleStylePluginTests.java   Source Code and License 5 votes vote down vote up
private static String pluginClasspath() {
    URLClassLoader classloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    List<String> classpath = new ArrayList<>();
    for (URL url : classloader.getURLs()) {
        classpath.add(url.getFile());
    }
    return Joiner.on(':').join(classpath);
}
 
Example 24
Project: util4j   File: BufferBuilderDemo.java   Source Code and License 5 votes vote down vote up
/**
 * 获取源码目录下指定包下的类
 * @param root
 * @param pkg
 * @return
 * @throws Exception
 */
public List<Class<?>> getClassInfo(String root,String pkg) throws Exception
{
	List<Class<?>> list=new ArrayList<Class<?>>();
	String suffix=".java";
	File rootDir=new File(root);
	Set<File> files=FileUtil.findFileByDirAndSub(rootDir,suffix);
	URLClassLoader loader=new URLClassLoader(new URL[]{rootDir.toURI().toURL()});
	try {
		// 获取路径长度
		int clazzPathLen = rootDir.getAbsolutePath().length() + 1;
		for(File file:files)
		{
			String className = file.getAbsolutePath();
			className = className.substring(clazzPathLen, className.length() - suffix.length());
			className = className.replace(File.separatorChar, '.');
			try {
				Class<?> clazz=loader.loadClass(className);
				String pkgName=clazz.getPackage().getName();
				if(pkgName.equals(pkg))
				{
					list.add(clazz);
				}
			} catch (Exception e) {
			}
		}
	} finally {
		loader.close();
	}
	return list;
}
 
Example 25
Project: guava-mock   File: ClassPathTest.java   Source Code and License 5 votes vote down vote up
@AndroidIncompatible // Android forbids null parent ClassLoader
// https://github.com/google/guava/issues/2152
public void testClassPathEntries_URLClassLoader_pathWithSpace() throws Exception {
  URL url = new URL("file:///c:/Documents and Settings/");
  URLClassLoader classloader = new URLClassLoader(new URL[] {url}, null);
  assertThat(ClassPath.Scanner.getClassPathEntries(classloader))
      .containsExactly(new File("/c:/Documents and Settings/"), classloader);
}
 
Example 26
Project: gradle-clojure   File: ClojureWorker.java   Source Code and License 5 votes vote down vote up
public static ClojureRuntime get() {
  String[] classpathElements = System.getProperty("shim.classpath").split(File.pathSeparator);
  URL[] classpathUrls = Arrays.stream(classpathElements)
      .map(Paths::get)
      .map(Path::toUri)
      .map(safe(URI::toURL))
      .toArray(size -> new URL[size]);

  URLClassLoader loader = new ClojureWorkerClassLoader(classpathUrls, ClojureWorker.class.getClassLoader());
  ClojureRuntimeShim shim = ClojureRuntimeShim.newRuntime(loader, "gradle-clojure");
  return new ClojureRuntime(loader, shim);
}
 
Example 27
Project: Hydrazine   File: ModuleManager.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a module extracted from a jar file.
 * @param path the filename of the module
 * @return a module
 * @throws Exception if something goes wrong, an exception is thrown
 */
public Module getModuleFromJar(String path) throws Exception
{
	Module m = null;
	
	JarFile modFile = new JarFile(path);
	Manifest mf = modFile.getManifest();
	Attributes attr = mf.getMainAttributes();
	String mainClass = attr.getValue(Attributes.Name.MAIN_CLASS);
	URLClassLoader classLoader = new URLClassLoader(new URL[]{ new File(path).toURI().toURL() });
	Class c = classLoader.loadClass(mainClass);
	
	Class[] interfaces = c.getInterfaces();
	
	classLoader.close();
	
	boolean isPlugin = false;
	
	for(int i = 0; i < interfaces.length && !isPlugin; i++)
	{
		if(interfaces[i].getName().equals("com.github.hydrazine.module.Module"))
		{
			isPlugin = true;
		}
	}
	
	if(isPlugin)
	{
		m = (Module) c.newInstance();
	}
	else
	{
		System.out.println(Hydrazine.warnPrefix + "\"" + path +  "\" isn't a valid module. You should remove it from the directory.");
	}
	
	modFile.close();
	
	return m;
}
 
Example 28
Project: android-perftracking   File: ClassProvider.java   Source Code and License 5 votes vote down vote up
public ClassProvider(String classpath) {
  try {
    ArrayList<URL> urls = new ArrayList<URL>();
    for (String path : classpath.split(File.pathSeparator)) {
      urls.add(Paths.get(path).toFile().toURI().toURL());
    }
    _classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
  } catch (Exception e) {
    throw new RuntimeException("Failed to create class loader");
  }
}
 
Example 29
Project: kestrel   File: KestrelRunnerBase.java   Source Code and License 5 votes vote down vote up
/**
 * Add a library URL.
 * 
 * @param url URL to add. If this URL is already in the list, it is not added.
 * 
 * @throws NullPointerException If <code>url</code> is <code>null</code>.
 */
public void addLibraryURL(URL url)
		throws NullPointerException {
	
	if (url == null)
		throw new NullPointerException("Cannot add library URL: null");
	
	if (libraryUrlList.contains(url))
		return;
	
	libraryUrlList.add(url);
	loader = new URLClassLoader(libraryUrlList.toArray(new URL[0]));
	
	return;
}
 
Example 30
Project: guava-mock   File: FinalizableReferenceQueue.java   Source Code and License 5 votes vote down vote up
/** Creates a class loader with the given base URL as its classpath. */
URLClassLoader newLoader(URL base) {
  // We use the bootstrap class loader as the parent because Finalizer by design uses
  // only standard Java classes. That also means that FinalizableReferenceQueueTest
  // doesn't pick up the wrong version of the Finalizer class.
  return new URLClassLoader(new URL[] {base}, null);
}
 
Example 31
Project: FridaAndroidTracer   File: FridaAndroidTracer.java   Source Code and License 5 votes vote down vote up
private static ClassLoader loadJars(String[] jarFiles) {
    URL[] urls = Stream.of(jarFiles)
            .map(name -> {
                try {
                    return new File(name).toURI().toURL();
                } catch (MalformedURLException e) {
                    System.out.println("Fail to load jar file: " + name);
                    e.printStackTrace();
                    return null;
                }
            })
            .toArray(URL[]::new);
    return URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
}
 
Example 32
Project: EvoMaster   File: ClassScanner.java   Source Code and License 5 votes vote down vote up
private static void searchInCurrentClassLoaderIfUrlOne(List<String> prefixes, Set<ClassName> names) {

        ClassLoader loader = ClassScanner.class.getClassLoader();

        while (loader != null) {
            if (loader instanceof URLClassLoader) {
                URLClassLoader urlLoader = (URLClassLoader) loader;
                for (URL url : urlLoader.getURLs()) {
                    try {
                        URI uri = url.toURI();

                        File file = new File(uri);
                        String path = file.getAbsolutePath();

                        if(file.isDirectory()){
                            scanDirectory(prefixes, names, file, path);
                        } else if(path.endsWith(".jar")){
                            scanJar(prefixes, names, path);
                        }

                    } catch (Exception e) {
                        SimpleLogger.error("Error while parsing URL " + url);
                        continue;
                    }
                }
            }

            loader = loader.getParent();
        }
    }
 
Example 33
Project: MaxSim   File: ClassUnloadCommon.java   Source Code and License 5 votes vote down vote up
public static ClassLoader newClassLoader() {
    try {
        return new URLClassLoader(new URL[] {
            Paths.get(System.getProperty("test.classes",".") + File.separatorChar + "classes").toUri().toURL(),
        }, null);
    } catch (MalformedURLException e){
        throw new RuntimeException("Unexpected URL conversion failure", e);
    }
}
 
Example 34
Project: angel   File: ConfUtils.java   Source Code and License 5 votes vote down vote up
private static void loadJar(String jarFile) throws IOException {
  URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Class<? extends URLClassLoader> sysclass = URLClassLoader.class;
  try {
    Method method = sysclass.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(sysloader, new File(jarFile).toURI().toURL());
  } catch (Throwable t) {
    throw new IOException("Error, could not add URL to system classloader", t);
  }
}
 
Example 35
Project: imagingbook-common   File: FileUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Lists (to System.out) the paths where classes are loaded from.
 */
public static void printClassPath() {
	ClassLoader cl = ClassLoader.getSystemClassLoader();
	URL[] urls = ((URLClassLoader) cl).getURLs();
	for (URL url : urls) {
		System.out.println(url.getPath());
	}
}
 
Example 36
Project: OpenJSharp   File: Options.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the <tt>META-INF/sun-jaxb.episode</tt> file to add as a binding customization.
 */
public void scanEpisodeFile(File jar) throws BadCommandLineException {
    try {
        URLClassLoader ucl = new URLClassLoader(new URL[]{jar.toURL()});
        Enumeration<URL> resources = ucl.findResources("META-INF/sun-jaxb.episode");
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            addBindFile(new InputSource(url.toExternalForm()));
        }
    } catch (IOException e) {
        throw new BadCommandLineException(
                Messages.format(Messages.FAILED_TO_LOAD,jar,e.getMessage()), e);
    }
}
 
Example 37
Project: Java-9-Programming-By-Example   File: ClassLister.java   Source Code and License 5 votes vote down vote up
private void listClasses(URLClassLoader loader) {
    URL[] urls = loader.getURLs();
    for (final URL url : urls) {
        log.info("Listing classes for URL {}", url);
        listClasses(loader, url);
    }
}
 
Example 38
Project: GitHub   File: ProxyProcessor.java   Source Code and License 5 votes vote down vote up
private static Processor createClassLoaderDelegate() {
  try {
    if (cachedProxyClassLoader == null) {
      cachedProxyClassLoader = new ProxyClassLoader(
          ((URLClassLoader) ProxyProcessor.class.getClassLoader()).getURLs(),
          Thread.currentThread().getContextClassLoader());
    }
    return (Processor) cachedProxyClassLoader.loadClass(DELEGATE_CLASS).newInstance();
  } catch (Throwable ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 39
Project: minsx-java-example   File: Main.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws Exception {

    URL url = new URL("file:E:/JavaJars/OtherJar/runner.jar");
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
    Class<?> clazz = urlClassLoader.loadClass("com.example.Runner");
    //Runnable runnable = (Runnable) clazz.newInstance();
    //runnable.run();
    Method method = clazz.getMethod("run");
    method.invoke(clazz.newInstance());
    urlClassLoader.close();

}
 
Example 40
Project: openjdk-jdk10   File: TestHumongousNonArrayAllocation.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
        IllegalAccessException, IOException {

    if (args.length != 1) {
        throw new Error("Test Bug: Expected class name wasn't provided as command line argument");
    }
    G1SampleClass sampleClass = G1SampleClass.valueOf(args[0]);

    Path wrkDir = Files.createTempDirectory(Paths.get(""), CLASS_NAME_PREFIX);
    URL[] url = {wrkDir.toUri().toURL()};
    URLClassLoader urlLoader = new URLClassLoader(url);

    Object sampleObject;
    try {
        sampleObject = sampleClass.getCls(urlLoader, wrkDir, CLASS_NAME_PREFIX).newInstance();
    } catch (Throwable throwable) {
        throw new AssertionError("Test Bug: Cannot create object of provided class", throwable);
    }

    boolean isHumongous = WB.g1IsHumongous(sampleObject);
    boolean shouldBeHumongous = (sampleClass.expectedInstanceSize() > (WB.g1RegionSize() / 2));

    // Sanity check
    Asserts.assertEquals(WB.getObjectSize(sampleObject), sampleClass.expectedInstanceSize(),
            String.format("Test Bug: Object of class %s is expected to take %d bytes but it takes %d.",
                    sampleClass.name(), sampleClass.expectedInstanceSize(), WB.getObjectSize(sampleObject)));

    // Test check
    Asserts.assertEquals(isHumongous, shouldBeHumongous,
            String.format("Object of class %s is expected to be %shumongous but it is not",
                    sampleClass.name(), (shouldBeHumongous ? "" : "non-")));
}
 
Example 41
Project: JavaShell   File: Runner.java   Source Code and License 5 votes vote down vote up
public static void run(String s, String[] imports) throws Exception {
	
	File dataFolder = JavaShell.getInstance().getDataFolder();
	File runtimeFolder = new File(dataFolder + File.separator + "runtime");
	File javaFile = new File(runtimeFolder + File.separator + "run.java");
		
	PrintWriter pw = new PrintWriter(javaFile);
	pw.println("import org.bukkit.*;");
	
	if (imports != null) {
		for (String string : imports) pw.println("import " + string + ";");
	}
	
	pw.println("public class run {");
	pw.print("public static void main(){" + s + "}}");
	pw.close();
	
	String[] args = new String[] {
			"-cp", "." + File.pathSeparator + FileScanner.paths,
			"-d", runtimeFolder.getAbsolutePath() + File.separator,
			javaFile.getAbsolutePath()
	};
	
	int compileStatus = Main.compile(args);
	
	if (compileStatus != 1) {
		URL[] urls = new URL[] { runtimeFolder.toURI().toURL() };
		URLClassLoader ucl = new URLClassLoader(urls);
		Object o = ucl.loadClass("run").newInstance();
		o.getClass().getMethod("main").invoke(o);
		ucl.close();
	} else {
		throw new Exception("JavaShell compilation failure");			
	}
	
	javaFile.delete();
	File classFile = new File(runtimeFolder + File.separator + "run.class");
	classFile.delete();
}
 
Example 42
Project: JavaShell   File: JarUtils.java   Source Code and License 5 votes vote down vote up
public static void addClassPath(final URL url) throws IOException {
	final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
	final Class<URLClassLoader> sysclass = URLClassLoader.class;
	try {
		final Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
		method.setAccessible(true);
		method.invoke(sysloader, new Object[] { url });
	} catch (final Throwable t) {
		t.printStackTrace();
		throw new IOException("Error adding " + url + " to system classloader");
	}
}
 
Example 43
Project: monarch   File: ClassPathLoaderTest.java   Source Code and License 5 votes vote down vote up
private static void exploreClassLoader(ClassLoader cl, int indent) {
  String prefix = "";
  for (int i = 0; i < indent; i++) {
    prefix += "\t";
  }
  System.out.println(prefix + "ClassLoader toString() = " + cl);

  Class<?> clazz = cl.getClass();
  System.out.println(prefix + "ClassLoader getClass().getName() = " + clazz.getName());
  exploreClassLoaderSuperClass(prefix, clazz);

  try {
    URL[] urls = ((URLClassLoader) cl).getURLs();
    StringBuilder sb = new StringBuilder(prefix).append("ClassLoader getURLs = [");
    for (int i = 0; i < urls.length; i++) {
      if (i > 0)
        sb.append(", ");
      sb.append(urls[i].toString());
    }
    sb.append("]");
    System.out.println(sb.toString());
  } catch (Exception e) {
    System.out.println(prefix + "ClassLoader is not a URLClassLoader");
  }

  ClassLoader parent = cl.getParent();
  if (parent != null) {
    System.out.println(prefix + "ClassLoader has parent...");
    exploreClassLoader(parent, ++indent);
  }
}
 
Example 44
Project: incubator-netbeans   File: NBJRTFileSystem.java   Source Code and License 5 votes vote down vote up
@CheckForNull
public static NBJRTFileSystem create(File jdkHome) {
    final File jrtFsJar = NBJRTUtil.getNIOProvider(jdkHome);
    if (jrtFsJar == null) {
        return null;
    }
    try {
        final URLClassLoader jrtFsLoader = new URLClassLoader(
                new URL[] {BaseUtilities.toURI(jrtFsJar).toURL()},
                ClassLoader.getSystemClassLoader());
        final FileSystem fs = FileSystems.newFileSystem(
                URI.create(String.format("%s:/", //NOI18N
                        PROTOCOL)),
                Collections.singletonMap(PROP_JAVA_HOME, jdkHome.getAbsolutePath()),
                jrtFsLoader);
        if (fs == null) {
            throw new IllegalStateException(String.format(
                "No %s provider.",  //NOI18N
                PROTOCOL));
        }
        return new NBJRTFileSystem(jdkHome, fs);
    } catch (IOException ex) {
        throw new IllegalStateException(
            String.format(
                "Cannot create %s NIO FS for: %s",  //NOI18N
                PROTOCOL,
                jdkHome.getAbsolutePath()),
            ex);
    }
}
 
Example 45
Project: incubator-netbeans   File: ModuleFactoryAlienTest.java   Source Code and License 5 votes vote down vote up
public void testAlienCanDependOnNetBeans() throws Exception {
    MockModuleInstaller installer = new MockModuleInstaller();
    MockEvents ev = new MockEvents();
    ModuleManager mgr = new ModuleManager(installer, ev);
    mgr.mutexPrivileged().enterWriteAccess();
    HashSet<Module> both = null;
    try {
        String mfBar = "AlienName: org.bar\n" +
            "AlienExport: org.bar\n" +
            "AlienImport: org.foo\n" +
            "\n\n";

        File j1 = new File(jars, "simple-module.jar");
        File j2 = changeManifest(new File(jars, "depends-on-simple-module.jar"), mfBar);
        Module m1 = mgr.create(j1, null, false, false, false);
        Module m2 = mgr.create(j2, null, false, false, false);
        HashSet<Module> b = new HashSet<Module>(Arrays.asList(m1, m2));
        mgr.enable(b);
        both = b;

        AlienModule am = (AlienModule)m2;
        am.loader.l = new URLClassLoader(new URL[] { Utilities.toURI(am.jar).toURL() }, m1.getClassLoader());

        assertFalse("Finish without exception", m2.provides("false"));


        Class<?> clazz = m2.getClassLoader().loadClass("org.bar.SomethingElse");
        Class<?> sprclass = m2.getClassLoader().loadClass("org.foo.Something");

        assertEquals("Correct parent is used", sprclass, clazz.getSuperclass());
    } finally {
        if (both != null) {
            mgr.disable(both);
        }
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
 
Example 46
Project: openjdk-jdk10   File: Test6823354.java   Source Code and License 5 votes vote down vote up
static void loadandrunclass(String classname) throws Exception {
    Class<?> cl = Class.forName(classname);
    URLClassLoader apploader = (URLClassLoader) cl.getClassLoader();
    ClassLoader loader = new URLClassLoader(apploader.getURLs(), apploader.getParent());
    Class<?> c = loader.loadClass(classname);
    Runnable r = (Runnable) c.newInstance();
    r.run();
}
 
Example 47
Project: incubator-netbeans   File: NbBundleProcessorTest.java   Source Code and License 5 votes vote down vote up
public void testFieldUsage() throws Exception {
    AnnotationProcessorTestUtils.makeSource(src, "p.C",
            "public class C {",
            "@org.openide.util.NbBundle.Messages(\"k=v\")",
            "public static final Object X = new Object() {public String toString() {return Bundle.k();}};",
            "}");
    assertTrue(AnnotationProcessorTestUtils.runJavac(src, null, dest, null, null));
    ClassLoader l = new URLClassLoader(new URL[] {Utilities.toURI(dest).toURL()});
    assertEquals("v", l.loadClass("p.C").getField("X").get(null).toString());
}
 
Example 48
Project: openjdk-jdk10   File: ProxyClassAccess.java   Source Code and License 5 votes vote down vote up
static void testProxyClass2() {
    URLClassLoader loader = new URLClassLoader(new URL[0]);
    P proxy = (P) Proxy.newProxyInstance(loader,
            new Class<?>[] { R.class, P.class }, handler);
    proxy.bar();
    proxy.barArrays();
}
 
Example 49
Project: dremio-oss   File: TestClassCompilers.java   Source Code and License 5 votes vote down vote up
@Test
public void testJDKCompilation() throws IOException, ClassTransformationException, CompileException, ClassNotFoundException {
  try(URLClassLoader classLoader = new URLClassLoader(new URL[] { classes.toURI().toURL()}, null)) {
    JDKClassCompiler jdkClassCompiler = JDKClassCompiler.newInstance(classLoader);
    testCompilation(jdkClassCompiler);
  };
}
 
Example 50
Project: QDrill   File: ITTestShadedJar.java   Source Code and License 5 votes vote down vote up
@Test
public void executeJdbcAllQuery() throws Exception {

  // print class path for debugging
  System.out.println("java.class.path:");
  System.out.println(System.getProperty("java.class.path"));

  final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
  method.setAccessible(true);
  method.invoke(loader, getJdbcUrl());

  Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
  try {
    Driver driver = (Driver) clazz.newInstance();
    try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null);
        Statement s = c.createStatement();
        ResultSet result = s.executeQuery("select * from (VALUES 1)");) {
      while (result.next()) {
        System.out.println(result.getObject(1));
      }
    }
  } catch (Exception ex) {
    throw ex;
  }

}
 
Example 51
Project: guava-mock   File: ClassPathTest.java   Source Code and License 5 votes vote down vote up
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_withGrandParent() throws Exception {
  URL url = new URL("file:/a");
  URLClassLoader grandParent = new URLClassLoader(new URL[] {url}, null);
  ClassLoader parent = new ClassLoader(grandParent) {};
  assertThat(ClassPath.Scanner.getClassPathEntries(new ClassLoader(parent) {}))
      .containsExactly(new File("/a"), grandParent);
}
 
Example 52
Project: guava-mock   File: ClassPathTest.java   Source Code and License 5 votes vote down vote up
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_URLClassLoader_withParent() throws Exception {
  URL url1 = new URL("file:/a");
  URL url2 = new URL("file:/b");
  URLClassLoader parent = new URLClassLoader(new URL[] {url1}, null);
  URLClassLoader child = new URLClassLoader(new URL[] {url2}, parent) {};
  assertThat(ClassPath.Scanner.getClassPathEntries(child))
      .containsExactly(new File("/a"), parent, new File("/b"), child)
      .inOrder();
}
 
Example 53
Project: jdk8u-jdk   File: Versions.java   Source Code and License 5 votes vote down vote up
public static void main(String [] args) throws Exception {
    String classVersion   = getProperty("java.class.version");
    String javaVersion    = getProperty("java.version");
    String VMVersion      = getProperty("java.vm.version");
    String runtimeVersion = getProperty("java.runtime.version");
    String specVersion    = getProperty("java.specification.version");

    if (! (javaVersion.startsWith(specVersion) &&
           runtimeVersion.startsWith(specVersion)))
        throw new Exception("Invalid version-related system properties");

    //----------------------------------------------------------------
    // Check that java.class.version is correct.
    // Injecting a larger major or minor version number into a
    // .class file should result in UnsupportedClassVersionError.
    //----------------------------------------------------------------
    String[] versions = classVersion.split("\\.");
    int majorVersion = Integer.parseInt(versions[0]);
    int minorVersion = Integer.parseInt(versions[1]);
    System.out.printf("majorVersion=%s%n",majorVersion);
    System.out.printf("minorVersion=%s%n",minorVersion);

    // Look in ".", and *not* in CLASSPATH
    cl = new URLClassLoader(new URL[]{new File("./").toURL()}, null);

    checkClassVersion(majorVersion    , minorVersion    , true );
    checkClassVersion(majorVersion + 1, minorVersion    , false);
    checkClassVersion(majorVersion    , minorVersion + 1, false);
}
 
Example 54
Project: openjdk-jdk10   File: XMLReaderFactoryTest.java   Source Code and License 5 votes vote down vote up
public void testService() throws Exception {
    ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
    try {
        URL[] classUrls = { SERVICE_DIR.toUri().toURL() };
        URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());

        // set TCCL and try locating the provider
        Thread.currentThread().setContextClassLoader(loader);
        XMLReader reader = XMLReaderFactory.createXMLReader();
        assertEquals(reader.getClass().getName(), "xp3.XMLReaderImpl");
    } finally {
        Thread.currentThread().setContextClassLoader(clBackup);
    }
}
 
Example 55
Project: incubator-netbeans   File: Selenium2ServerSupport.java   Source Code and License 5 votes vote down vote up
private static void initializeServer() throws Exception {
      URLClassLoader urlClassLoader = getSeleniumServerClassLoader();
      Class seleniumServer = urlClassLoader.loadClass("org.openqa.selenium.server.SeleniumServer"); //NOI18N
      Class remoteControlConfiguration = urlClassLoader.loadClass(
              "org.openqa.selenium.server.RemoteControlConfiguration"); //NOI18N

      Object remoteControlConfigurationInstance = remoteControlConfiguration.newInstance();
      int port = getPrefs().getInt(PORT, PORT_DEFAULT);
      remoteControlConfiguration.getMethod("setPort", int.class).invoke(
          remoteControlConfigurationInstance, port); //NOI18N
      boolean runInSingleWindow = getPrefs().getBoolean(SINGLE_WINDOW, SINGLE_WINDOW_DEFAULT);
      remoteControlConfiguration.getMethod("setSingleWindow", Boolean.TYPE).invoke( //NOI18N
              remoteControlConfigurationInstance, runInSingleWindow);
String firefoxProfileDir = getPrefs().get(FIREFOX_PROFILE_TEMPLATE_DIR, ""); //NOI18N
if (!firefoxProfileDir.isEmpty()) {
		File ffProfileDir = new File(firefoxProfileDir);
		if (ffProfileDir.exists()) {
			remoteControlConfiguration.getMethod("setFirefoxProfileTemplate", File.class).invoke( //NOI18N
				remoteControlConfigurationInstance, ffProfileDir);
		}
}
      String userExtensionsString = getPrefs().get(USER_EXTENSION_FILE, ""); //NOI18N
      if (!userExtensionsString.isEmpty()) {
          File userExtensionFile = new File(userExtensionsString);
          if (userExtensionFile.exists()) {
              remoteControlConfiguration.getMethod("setUserExtensions", File.class).invoke( //NOI18N
                      remoteControlConfigurationInstance, userExtensionFile);
          }
      }
      
      server = seleniumServer.getConstructor(remoteControlConfiguration).
              newInstance(remoteControlConfigurationInstance);
  }
 
Example 56
Project: guava-mock   File: ClassPathTest.java   Source Code and License 5 votes vote down vote up
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_withParentAndGrandParent() throws Exception {
  URL url1 = new URL("file:/a");
  URL url2 = new URL("file:/b");
  URLClassLoader grandParent = new URLClassLoader(new URL[] {url1}, null);
  URLClassLoader parent = new URLClassLoader(new URL[] {url2}, grandParent);
  assertThat(ClassPath.Scanner.getClassPathEntries(new ClassLoader(parent) {}))
      .containsExactly(new File("/a"), grandParent, new File("/b"), parent);
}
 
Example 57
Project: openjdk-jdk10   File: ReflectionTest.java   Source Code and License 5 votes vote down vote up
private static Class<?> loadClass(String className, ClassLoader parentClassLoader, File... destDirs) {
    try {
        List<URL> list = new ArrayList<>();
        for (File f : destDirs) {
            list.add(new URL("file:" + f.toString().replace("\\", "/") + "/"));
        }
        return Class.forName(className, true, new URLClassLoader(
                list.toArray(new URL[list.size()]), parentClassLoader));
    } catch (ClassNotFoundException | MalformedURLException e) {
        throw new RuntimeException("Error loading class " + className, e);
    }
}
 
Example 58
Project: openjdk-jdk10   File: OptionsVerifierTest.java   Source Code and License 5 votes vote down vote up
@Override
public void close() throws IOException {
    for (Object e : entries.values()) {
        if (e instanceof URLClassLoader) {
            ((URLClassLoader) e).close();
        }
    }
}
 
Example 59
Project: lazycat   File: WebappLoader.java   Source Code and License 5 votes vote down vote up
private boolean buildClassPath(ServletContext servletContext, StringBuilder classpath, ClassLoader loader) {
	if (loader instanceof URLClassLoader) {
		URL repositories[] = ((URLClassLoader) loader).getURLs();
		for (int i = 0; i < repositories.length; i++) {
			String repository = repositories[i].toString();
			if (repository.startsWith("file://"))
				repository = utf8Decode(repository.substring(7));
			else if (repository.startsWith("file:"))
				repository = utf8Decode(repository.substring(5));
			else if (repository.startsWith("jndi:"))
				repository = servletContext.getRealPath(repository.substring(5));
			else
				continue;
			if (repository == null)
				continue;
			if (classpath.length() > 0)
				classpath.append(File.pathSeparator);
			classpath.append(repository);
		}
	} else {
		String cp = getClasspath(loader);
		if (cp == null) {
			log.info("Unknown loader " + loader + " " + loader.getClass());
		} else {
			if (classpath.length() > 0)
				classpath.append(File.pathSeparator);
			classpath.append(cp);
		}
		return false;
	}
	return true;
}
 
Example 60
Project: dremio-oss   File: JDKClassCompiler.java   Source Code and License 5 votes vote down vote up
private JDKClassCompiler(JavaCompiler compiler, ClassLoader classLoader) {
  this.compiler = compiler;
  this.listener = new DremioDiagnosticListener();
  this.fileManager = new DremioJavaFileManager(compiler.getStandardFileManager(listener, null, UTF_8));

  ImmutableList.Builder<String> compilerOptionsBuilder = ImmutableList.builder();
  // Provides the application classpath to the compiler
  //
  // Javac cannot use the classloader directly so we need to convert it back
  // to a list of paths, if possible.
  //
  // Note that Maven surefire plugin encodes application classpath in META-INF/MANIFEST.MF
  // so using JavaFileManager#setLocation(Location, Iterable<File>) would not work as it
  // doesn't expand the classpath recursively, unlike the Java compiler '-classpath' option.
  // Unfortunately, Java compiler (jdk7) only handles relative paths, whereas
  // URLClassLoader supports both relative and absolute paths. Of course, surefire plugin uses
  // absolute paths, which causes the compiler not to found any of the classes :(
  // As surefire also sets "java.class.path" with the expanded version of the classpath (which seems
  // a reasonable thing to do since this is a well-known system property), we can let the java compiler
  // use its default behaviour if we detect the use of the plugin.
  String surefireRealClassPath = System.getProperty("surefire.real.class.path");
  if (surefireRealClassPath != null && classLoader == ClassLoader.getSystemClassLoader()) {
    logger.debug("Surefire detected. Compiler will automatically use the following classpath: {}", System.getProperty("java.class.path"));
  } else if (classLoader instanceof URLClassLoader) {
    List<String> files = getClassPath((URLClassLoader) classLoader);
    if (!files.isEmpty()) {
      compilerOptionsBuilder.add("-classpath", Joiner.on(File.pathSeparator).join(files));
    }
  } else if (classLoader != null) {
    // the class loader cannot be converted back to a list of urls
    // let's fall back to the default behavior of the compiler to rely on
    // standard system properties with the classpath being set.
    logger.warn(
        "Provided classLoader for compilation is not a URLClassLoader (was: {}). You might have compilation issues.",
        classLoader.getClass().getName());
  }

  this.defaultCompilerOptions = compilerOptionsBuilder.build();
}