Java Code Examples for java.net.URLClassLoader#close()

The following examples show how to use java.net.URLClassLoader#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectionBenchmarkUniqueResolutionTest.java    From AVM with MIT License 7 votes vote down vote up
private long sameInstanceReflectionConstructorResolution(int spins) throws Exception {
    Class<?>[] classes = new Class[spins];

    for (int i = 0; i < spins; i++) {
        URLClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        classes[i] = loader.loadClass(targetClassName);
        loader.close();
    }

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        classes[i].getConstructor(String.class, Object.class, Character.class, Float[].class);
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 2
Source File: ReflectionBenchmarkUniqueResolutionTest.java    From AVM with MIT License 6 votes vote down vote up
private long sameInstanceReflectionStaticMethodResolution(int spins) throws Exception {
    Class<?>[] classes = new Class[spins];

    for (int i = 0; i < spins; i++) {
        URLClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        classes[i] = loader.loadClass(targetClassName);
        loader.close();
    }

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        classes[i].getMethod(staticMethod, Number.class, Random.class);
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 3
Source File: ReflectionBenchmarkUniqueResolutionTest.java    From AVM with MIT License 6 votes vote down vote up
private long sameInstanceReflectionInstanceFieldResolution(int spins) throws Exception {
    Class<?>[] classes = new Class[spins];

    for (int i = 0; i < spins; i++) {
        URLClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        classes[i] = loader.loadClass(targetClassName);
        loader.close();
    }

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        classes[i].getField(instanceField);
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 4
Source File: ReflectionBenchmarkUniqueResolutionTest.java    From AVM with MIT License 6 votes vote down vote up
private long sameInstanceMethodHandleInstanceFieldResolution(int spins) throws Exception {
    Class<?>[] classes = new Class[spins];

    for (int i = 0; i < spins; i++) {
        URLClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        classes[i] = loader.loadClass(targetClassName);
        loader.close();
    }

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        MethodHandles.lookup().findGetter(classes[i], instanceField, Object.class);
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 5
Source File: ClassLoaderTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeatedParentFirstPatternClass() throws Exception {
	final String className = ClassLoaderTest.class.getName();
	final String parentFirstPattern = className.substring(0, className.lastIndexOf('.'));

	final ClassLoader parentClassLoader = getClass().getClassLoader();

	// collect the libraries / class folders with RocksDB related code: the state backend and RocksDB itself
	final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();

	final URLClassLoader childClassLoader = FlinkUserCodeClassLoaders.childFirst(
			new URL[] { childCodePath }, parentClassLoader, new String[] { parentFirstPattern });

	final Class<?> clazz1 = Class.forName(className, false, parentClassLoader);
	final Class<?> clazz2 = Class.forName(className, false, childClassLoader);
	final Class<?> clazz3 = Class.forName(className, false, childClassLoader);
	final Class<?> clazz4 = Class.forName(className, false, childClassLoader);

	assertEquals(clazz1, clazz2);
	assertEquals(clazz1, clazz3);
	assertEquals(clazz1, clazz4);

	childClassLoader.close();
}
 
Example 6
Source File: ClassLoaderEnvironment.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected AutoCloseable doStart(final Class<?> clazz, final Annotation[] annotations) {
    try {
        ofNullable(Thread.currentThread().getContextClassLoader())
                .orElseGet(ClassLoader::getSystemClassLoader)
                .loadClass("org.jboss.shrinkwrap.resolver.api.maven.Maven");
    } catch (final ClassNotFoundException e) {
        throw new IllegalStateException("Don't forget to add to your dependencies:\n"
                + "  org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven:3.1.3");
    }
    final Thread thread = Thread.currentThread();
    final URLClassLoader classLoader = new URLClassLoader(Stream
            .of(rootDependencies())
            .peek(dep -> log.info("Resolving " + dep + "..."))
            .flatMap(dep -> Stream.of(Dependencies.resolve(dep)))
            .toArray(URL[]::new), Thread.currentThread().getContextClassLoader());
    final ClassLoader original = thread.getContextClassLoader();
    thread.setContextClassLoader(classLoader);
    return () -> {
        thread.setContextClassLoader(original);
        classLoader.close();
    };
}
 
Example 7
Source File: TestUrlClassLoader.java    From util4j with Apache License 2.0 6 votes vote down vote up
public static void testDir()throws Exception
	{
		File f=new File("C:/Users/Administrator/git/util4j/util4j/target/classes");
		URL url=f.toURI().toURL();
		URL[] urls=new URL[]{url};
		URLClassLoader loader=new URLClassLoader(urls);
//		loader.close();
		Class c1=loader.loadClass("net.jueb.util4j.math.CombinationUtil");
		System.out.println(c1);
		Class c2=loader.loadClass("net.jueb.util4j.math.CombinationUtil$CombinationController");
		System.out.println(c2);
		Class c3=loader.loadClass("net.jueb.util4j.math.CombinationUtil$ForEachByteIndexController");
		System.out.println(c3);
		Enumeration<URL> ss=loader.findResources("*.class");
		System.out.println(ss.hasMoreElements());
		CombinationUtil c22=(CombinationUtil) c1.newInstance();
		System.out.println(c22);
		loader.close();
		c1=loader.loadClass("net.jueb.util4j.math.CombinationUtil");
		System.out.println(c1);
	}
 
Example 8
Source File: ClassLoaderTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeatedChildFirstClassLoading() throws Exception {
	final ClassLoader parentClassLoader = getClass().getClassLoader();

	// collect the libraries / class folders with RocksDB related code: the state backend and RocksDB itself
	final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();

	final URLClassLoader childClassLoader = FlinkUserCodeClassLoaders.childFirst(
			new URL[] { childCodePath }, parentClassLoader, new String[0]);

	final String className = ClassLoaderTest.class.getName();

	final Class<?> clazz1 = Class.forName(className, false, parentClassLoader);
	final Class<?> clazz2 = Class.forName(className, false, childClassLoader);
	final Class<?> clazz3 = Class.forName(className, false, childClassLoader);
	final Class<?> clazz4 = Class.forName(className, false, childClassLoader);

	assertNotEquals(clazz1, clazz2);

	assertEquals(clazz2, clazz3);
	assertEquals(clazz2, clazz4);

	childClassLoader.close();
}
 
Example 9
Source File: ClassLoaderTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeatedParentFirstPatternClass() throws Exception {
	final String className = ClassLoaderTest.class.getName();
	final String parentFirstPattern = className.substring(0, className.lastIndexOf('.'));

	final ClassLoader parentClassLoader = getClass().getClassLoader();

	// collect the libraries / class folders with RocksDB related code: the state backend and RocksDB itself
	final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();

	final URLClassLoader childClassLoader = FlinkUserCodeClassLoaders.childFirst(
			new URL[] { childCodePath }, parentClassLoader, new String[] { parentFirstPattern });

	final Class<?> clazz1 = Class.forName(className, false, parentClassLoader);
	final Class<?> clazz2 = Class.forName(className, false, childClassLoader);
	final Class<?> clazz3 = Class.forName(className, false, childClassLoader);
	final Class<?> clazz4 = Class.forName(className, false, childClassLoader);

	assertEquals(clazz1, clazz2);
	assertEquals(clazz1, clazz3);
	assertEquals(clazz1, clazz4);

	childClassLoader.close();
}
 
Example 10
Source File: ReflectionBenchmarkUniqueResolutionTest.java    From AVM with MIT License 6 votes vote down vote up
private long sameInstanceMethodHandleConstructorResolution(int spins) throws Exception {
    Class<?>[] classes = new Class[spins];

    for (int i = 0; i < spins; i++) {
        URLClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
        classes[i] = loader.loadClass(targetClassName);
        loader.close();
    }

    long start = System.nanoTime();
    for (int i = 0; i < spins; i++) {
        MethodHandles.lookup().findConstructor(
            classes[i],
            MethodType.methodType(void.class, String.class, Object.class, Character.class, Float[].class));
    }
    long end = System.nanoTime();
    return end - start;
}
 
Example 11
Source File: FlinkUserCodeClassLoadersTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentFirstClassLoading() throws Exception {
	final ClassLoader parentClassLoader = getClass().getClassLoader();

	// collect the libraries / class folders with RocksDB related code: the state backend and RocksDB itself
	final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();

	final URLClassLoader childClassLoader1 = createParentFirstClassLoader(childCodePath, parentClassLoader);

	final URLClassLoader childClassLoader2 = createParentFirstClassLoader(childCodePath, parentClassLoader);

	final String className = FlinkUserCodeClassLoadersTest.class.getName();

	final Class<?> clazz1 = Class.forName(className, false, parentClassLoader);
	final Class<?> clazz2 = Class.forName(className, false, childClassLoader1);
	final Class<?> clazz3 = Class.forName(className, false, childClassLoader2);

	assertEquals(clazz1, clazz2);
	assertEquals(clazz1, clazz3);

	childClassLoader1.close();
	childClassLoader2.close();
}
 
Example 12
Source File: GraphElement.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Closes all classloaders associated with this graph element. 
 */
private void freeClassLoaders() {
	synchronized (classLoaders) {
		for (URLClassLoader classLoader : classLoaders) {
			try {
				classLoader.close();
			} catch (Exception e) {
				logger.warn("URLClassLoader allocated for " + this + " cannot be closed.", e);
			}
		}
		classLoaders.clear();
	}
}
 
Example 13
Source File: DynamicClassCompilerTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void jarCreationWithDependency() throws Exception {
	String dependencyName = "test.dynamic.newjar.Printer";
	String dependencyCode = 
			"package test.dynamic.newjar;" + 
			"public class Printer {" +
			"	public String print(Object object) {" +
			"		return \"An object printed by a dependency\";" + 
			"	}" + 
			"}";
	String qualifiedName = "test.dynamic.compiler.HelloWorld";
	String code = 
			"package test.dynamic.compiler;" +
			"import test.dynamic.newjar.Printer;" +
			"public class HelloWorld {" +
			"	@Override" +
			"	public String toString() {" +
			"		return new Printer().print(this);" +
			"	}" + 
			"}";
	DynamicClassCompiler compiler = new DynamicClassCompiler();
	
	Map<String, String> qualifiedNameAndContent = adHocMap(asList(dependencyName, qualifiedName), asList(dependencyCode, code));
	Map<String, byte[]> bytecodes = compiler.javaBytecodeFor(qualifiedNameAndContent);
	File jarFile = jarFileFor(bytecodes, "HelloWorldAndPrinter");
	
	URLClassLoader loader = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
	Class<?> newClass = loader.loadClass(qualifiedName);
	Object newInstance = newClass.newInstance();
	assertEquals("An object printed by a dependency", newInstance.toString());
	loader.close();
	jarFile.delete();
}
 
Example 14
Source File: ResolverImplTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void createClassLoader(@TempDir final Path temporaryFolder) throws Exception {
    final File root = temporaryFolder.toFile();
    root.mkdirs();
    final String dep = "org.apache.tomee:arquillian-tomee-codi-tests:jar:7.0.5";
    final File nestedJar = new File(root, UUID.randomUUID().toString() + ".jar");
    try (final JarOutputStream out = new JarOutputStream(new FileOutputStream(nestedJar))) {
        addDepToJar(dep, out);
    }

    final Thread thread = Thread.currentThread();
    final ClassLoader contextClassLoader = thread.getContextClassLoader();
    // component loader simulation which is always the parent of that
    // here the parent of the component is the jar containing the nested repo
    final URLClassLoader appLoader =
            new URLClassLoader(new URL[] { nestedJar.toURI().toURL() }, contextClassLoader);
    final ConfigurableClassLoader componentLoader = new ConfigurableClassLoader("test", new URL[0], appLoader,
            it -> true, it -> false, new String[0], new String[0]);
    thread.setContextClassLoader(componentLoader);
    try (final Resolver.ClassLoaderDescriptor desc =
            new ResolverImpl(null, coord -> PathFactory.get("maven2").resolve(coord))
                    .mapDescriptorToClassLoader(singletonList(dep))) {
        assertNotNull(desc);
        assertNotNull(desc.asClassLoader());
        assertEquals(singletonList(dep), desc.resolvedDependencies());
        final Properties props = new Properties();
        try (final InputStream in = desc
                .asClassLoader()
                .getResourceAsStream(
                        "META-INF/maven/org.apache.tomee/arquillian-tomee-codi-tests/pom.properties")) {
            assertNotNull(in);
            props.load(in);
        }
        assertEquals("arquillian-tomee-codi-tests", props.getProperty("artifactId"));
    } finally {
        thread.setContextClassLoader(contextClassLoader);
        appLoader.close();
    }
}
 
Example 15
Source File: MavenArtifactTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void checkValidMavenJarUrl(String url, String resource) throws Exception {
    // URLClassLoader doesn't follow redirects; find out the real URL
    // Note URLClassLoader.close was only added in Java 7; do not call it until Java 6 support is not needed!
    URL realUrl = followRedirects(new URL(url));
    URLClassLoader classLoader = new URLClassLoader(new URL[] { realUrl });
    try {
        URL innerU = classLoader.findResource(resource);
        InputStream innerUin = innerU.openConnection().getInputStream();
        innerUin.close();
    } finally {
        classLoader.close();
    }
}
 
Example 16
Source File: PatchModuleInvalidationWithRenamingFailureTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static void assertLoadable(final File jar) throws Exception {
    final URL[] urls = new URL[]{jar.toURI().toURL()};
    final URLClassLoader cl = new URLClassLoader(urls);
    Assert.assertNotNull(cl.getResource("testResource"));
    final Class<?> clazz = cl.loadClass("org.jboss.as.patching.tests.TestClass");
    final Constructor<?> constructor = clazz.getConstructor(String.class);
    final Object instance = constructor.newInstance("test");
    Assert.assertNotNull(instance);
    cl.close();
}
 
Example 17
Source File: StandardExtensionDiscoveringManager.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void closeURLClassLoader(final String instanceIdentifier, final ClassLoader classLoader) {
    if ((classLoader instanceof URLClassLoader)) {
        final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
        try {
            urlClassLoader.close();
        } catch (IOException e) {
            logger.warn("Unable to close URLClassLoader for " + instanceIdentifier);
        }
    }
}
 
Example 18
Source File: GetPropertiesCommand.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
	CommandHelpers.putComponentValuesInAttributeMap(context, inputComponents);
	UIContext uiContext = context.getUIContext();
	Map<Object, Object> map = uiContext.getAttributeMap();
	List<String> classNames = (List<String>) map.get("classNames");
	if (classNames == null || classNames.size() == 0) {
		return Results.fail("No className field provided");
	}
	Project project = Projects.getSelectedProject(getProjectFactory(), uiContext);
	// force build
	PackagingFacet packaging = project.getFacet(PackagingFacet.class);
	ProjectBuilder builder = packaging.createBuilder();
	builder.runTests(false);
	builder.addArguments("clean", "compile");
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	PrintStream stdout = new PrintStream(baos, true);
	try {
		builder.build(stdout, stdout);
	} catch (BuildException be) {
		// no point in continuing the operation
		return Results.fail("Failed to build project: " + be + "\n\n" + baos.toString());
	}
	ClassLoaderFacet classLoaderFacet = project.getFacet(ClassLoaderFacet.class);
	URLClassLoader classLoader = classLoaderFacet.getClassLoader();
	Map<String, List<Object>> answer = new HashMap<String, List<Object>>();
	for (String className : classNames) {
		List<Object> props = new ArrayList<Object>();
		Class clazz;
		try {
			clazz = classLoader.loadClass(className);
			BeanInfo beanInfo = java.beans.Introspector.getBeanInfo(clazz);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
				// ignore the class property
				if (propertyDescriptor.getName().equals("class")) {
					continue;
				}
				PropertyDTO info = new PropertyDTO(propertyDescriptor);
				props.add(info);
			}
		} catch (Exception e) {
			props.add("Failed to load class, error: " + e.getMessage());
		}
		answer.put(className, props);
	}
	classLoader.close();
	String result = toJson(answer);
	return Results.success(result);
}
 
Example 19
Source File: PluginRegistry.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public void removePlugin( Class<? extends PluginTypeInterface> pluginType, PluginInterface plugin ) {
  lock.writeLock().lock();
  try {
    URLClassLoader ucl;
    Set<PluginInterface> list = pluginMap.get( pluginType );
    if ( list != null ) {
      list.remove( plugin );
    }

    Map<PluginInterface, URLClassLoader> classLoaders = classLoaderMap.get( plugin.getPluginType() );
    if ( classLoaders != null ) {
      classLoaders.remove( plugin );
    }

    if ( !Utils.isEmpty( plugin.getClassLoaderGroup() ) ) {
      // Straight away remove the class loader for the whole group...
      //
      ucl = classLoaderGroupsMap.remove( plugin.getClassLoaderGroup() );
      if ( ucl != null && classLoaders != null ) {
        for ( PluginInterface p : inverseClassLoaderLookup.remove( ucl ) ) {
          classLoaders.remove( p );
        }
        try {
          ucl.close();
        } catch ( IOException e ) {
          e.printStackTrace();
        }
      }
    }

    if ( plugin.getPluginDirectory() != null ) {
      folderBasedClassLoaderMap.remove( plugin.getPluginDirectory().toString() );
    }
  } finally {
    lock.writeLock().unlock();
    Set<PluginTypeListener> listeners = this.listeners.get( pluginType );
    if ( listeners != null ) {
      for ( PluginTypeListener listener : listeners ) {
        listener.pluginRemoved( plugin );
      }
    }
    synchronized ( this ) {
      notifyAll();
    }
  }
}
 
Example 20
Source File: ExtractConnectorDescriptorsMojo.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"PMD.EmptyCatchBlock", "PMD.CyclomaticComplexity"})
public void execute() throws MojoExecutionException, MojoFailureException {

    ArrayNode root = new ArrayNode(JsonNodeFactory.instance);

    URLClassLoader classLoader = null;
    try {
        PluginDescriptor desc = (PluginDescriptor) getPluginContext().get("pluginDescriptor");
        List<Artifact> artifacts = desc.getArtifacts();
        ProjectBuildingRequest buildingRequest =
            new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
        buildingRequest.setRemoteRepositories(remoteRepositories);
        for (Artifact artifact : artifacts) {
            ArtifactResult result = artifactResolver.resolveArtifact(buildingRequest, artifact);
            File jar = result.getArtifact().getFile();
            classLoader = createClassLoader(jar);
            if (classLoader == null) {
                throw new IOException("Can not create classloader for " + jar);
            }
            ObjectNode entry = new ObjectNode(JsonNodeFactory.instance);
            addConnectorMeta(entry, classLoader);
            addComponentMeta(entry, classLoader);
            if (entry.size() > 0) {
                addGav(entry, artifact);
                root.add(entry);
            }
        }
        if (root.size() > 0) {
            saveCamelMetaData(root);
        }
    } catch (ArtifactResolverException | IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (classLoader != null) {
            try {
                classLoader.close();
            } catch (IOException ignored) {

            }
        }
    }
}