@Override public ClassLoader run() { return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parent); } });
URL[] url={new URL("file://foo")}; URLClassLoader loader = new URLClassLoader(url);
/** * Creates a classloader respecting the classpath option. * * @return the classloader. */ protected synchronized ClassLoader createClassloader() { URL[] urls = classpath.stream().map(path -> { File file = new File(path); try { return file.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }).toArray(URL[]::new); return new URLClassLoader(urls, this.getClass().getClassLoader()); }
public CompilerClassWriter(String classPath, PrintWriter perr) { super(ClassWriter.COMPUTE_FRAMES); List<URL> urls = new ArrayList<>(); for(String e : classPath.split(File.pathSeparator)) { File f = new File(e); try { urls.add(f.toURI().toURL()); } catch (MalformedURLException ex) { perr.printf("%s is not a valid classpath entry\n", e); } } cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader()); }
/** * Add new elements to the classpath. * * @param newPaths * Array of classpath elements */ public static ClassLoader addToClassPath(ClassLoader cloader, String[] newPaths) throws Exception { URLClassLoader loader = (URLClassLoader) cloader; List<URL> curPath = Arrays.asList(loader.getURLs()); ArrayList<URL> newPath = new ArrayList<>(curPath.size()); // get a list with the current classpath components for (URL onePath : curPath) { newPath.add(onePath); } curPath = newPath; for (String onestr : newPaths) { URL oneurl = urlFromPathString(onestr); if (oneurl != null && !curPath.contains(oneurl)) { curPath.add(oneurl); } } return new URLClassLoader(curPath.toArray(new URL[0]), loader); }
/** * Create a parent ClassLoader for Groovy to use as parent ClassLoader * when loading and compiling templates. */ protected ClassLoader createTemplateClassLoader() throws IOException { String[] paths = StringUtils.commaDelimitedListToStringArray(getResourceLoaderPath()); List<URL> urls = new ArrayList<>(); for (String path : paths) { Resource[] resources = getApplicationContext().getResources(path); if (resources.length > 0) { for (Resource resource : resources) { if (resource.exists()) { urls.add(resource.getURL()); } } } } ClassLoader classLoader = getApplicationContext().getClassLoader(); Assert.state(classLoader != null, "No ClassLoader"); return (!urls.isEmpty() ? new URLClassLoader(urls.toArray(new URL[0]), classLoader) : classLoader); }
protected URLClassLoader createClassLoader() throws DependencyResolutionRequiredException, MalformedURLException { List<URL> urls = appendElements(project.getRuntimeClasspathElements()); urls.addAll(appendElements(project.getTestClasspathElements())); return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); }
@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); }
private void run() { Handler.init(); try (JarFile jarFile = new JarFile(currentJarFile())) { String mainClassName = mainClassName(jarFile); List<URL> jarsInJar = jarFile.stream() .filter(FIND_JAR_FILES_UNDER_LIB_FOLDER) .map(jarEntry -> Handler.toOneJarUrl(jarEntry.getName())) .collect(Collectors.toList()); List<URL> urls = new ArrayList<>(); urls.addAll(additionalJarsInLibsDirectoryInCWD()); urls.addAll(jarsInJar); ClassLoader jcl = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(jcl); Class<?> mainClass = jcl.loadClass(mainClassName); mainClass.getMethod("main", String[].class).invoke(null, new Object[]{args}); } catch (IOException | ReflectiveOperationException e) { e.printStackTrace(); System.exit(1); } }
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader(); // Add the conf dir to the classpath // Chain the current thread classloader URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new File("mtFile").toURL()}, currentThreadClassLoader); // Replace the thread classloader - assumes // you have permissions to do so Thread.currentThread().setContextClassLoader(urlClassLoader);
static WebAppContext newWebAppContext() throws MalformedURLException { final WebAppContext handler = new WebAppContext(); handler.setContextPath("/"); handler.setBaseResource(Resource.newResource(webAppRoot())); handler.setClassLoader(new URLClassLoader( new URL[] { Resource.newResource(new File(webAppRoot(), "WEB-INF" + File.separatorChar + "lib" + File.separatorChar + "hello.jar")).getURI().toURL() }, JettyService.class.getClassLoader())); handler.addBean(new ServletContainerInitializersStarter(handler), true); handler.setAttribute( "org.eclipse.jetty.containerInitializers", Collections.singletonList(new ContainerInitializer(new JettyJasperInitializer(), null))); return handler; }
public static void addJarToContextLoader(File jar) throws MalformedURLException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader instanceof MutableURLClassLoader) { ((MutableURLClassLoader) loader).addURL(jar.toURI().toURL()); } else { URLClassLoader newLoader = new URLClassLoader(new URL[]{jar.toURI().toURL()}, loader); Thread.currentThread().setContextClassLoader(newLoader); } }
private ClassLoader toClassLoader(FileCollection runtimeClasspath) { List<URL> urls = new ArrayList<URL>(); for ( File file : runtimeClasspath ) { try { urls.add( file.toURI().toURL() ); logger.debug( "Adding classpath entry for " + file.getAbsolutePath() ); } catch (MalformedURLException e) { throw new GradleException( "Unable to resolve classpath entry to URL : " + file.getAbsolutePath(), e ); } } return new URLClassLoader( urls.toArray( new URL[urls.size()] ), Enhancer.class.getClassLoader() ); }
public Class<TBase> getThriftClass() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { final Class<TBase> thrift; if (jarPath != null) { File jar = new File(jarPath); URLClassLoader child = new URLClassLoader( new URL[]{jar.toURI().toURL()}, this.getClass().getClassLoader() ); thrift = (Class<TBase>) Class.forName(thriftClassName, true, child); } else { thrift = (Class<TBase>) Class.forName(thriftClassName); } thrift.newInstance(); return thrift; }
/** * Add new elements to the classpath. * * @param newPaths Map of classpath elements and corresponding timestamp * @return locally accessible files corresponding to the newPaths */ public static List<String> addToClassPath(Map<String, Long> newPaths, Configuration conf, File localTmpDir) throws Exception { URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); List<URL> curPath = Lists.newArrayList(loader.getURLs()); List<String> localNewPaths = new ArrayList<>(); boolean newPathAdded = false; for (Map.Entry<String, Long> entry : newPaths.entrySet()) { URL newUrl = urlFromPathString(entry.getKey(), entry.getValue(), conf, localTmpDir); localNewPaths.add(newUrl.toString()); if (newUrl != null && !curPath.contains(newUrl)) { curPath.add(newUrl); LOG.info("Added jar[" + newUrl + "] to classpath."); newPathAdded = true; } } if (newPathAdded) { URLClassLoader newLoader = new URLClassLoader(curPath.toArray(new URL[curPath.size()]), loader); Thread.currentThread().setContextClassLoader(newLoader); } return localNewPaths; }
/** * Create a parent ClassLoader for Groovy to use as parent ClassLoader * when loading and compiling templates. */ protected ClassLoader createTemplateClassLoader() throws IOException { String[] paths = StringUtils.commaDelimitedListToStringArray(getResourceLoaderPath()); List<URL> urls = new ArrayList<>(); for (String path : paths) { Resource[] resources = getApplicationContext().getResources(path); if (resources.length > 0) { for (Resource resource : resources) { if (resource.exists()) { urls.add(resource.getURL()); } } } } ClassLoader classLoader = getApplicationContext().getClassLoader(); Assert.state(classLoader != null, "No ClassLoader"); return (!urls.isEmpty() ? new URLClassLoader(urls.toArray(new URL[0]), classLoader) : classLoader); }
public ClassLoader build(final Module baseModule) { if (baseModule == null) { return getClass().getClassLoader(); } final Project project = baseModule.getProject(); final List<URL> outputPaths = new ArrayList<>(); final Set<Module> transitiveDependencies = new HashSet<>(); ModuleUtil.getDependencies(baseModule, transitiveDependencies); for (Module moduleInScope : transitiveDependencies) { if (LOG.isDebugEnabled()) { LOG.debug("Adding module to classpath: " + moduleInScope.getName()); } outputPaths.addAll(ModulePaths.compilerOutputPathsFor(moduleInScope)); outputPaths.addAll(ModulePaths.libraryPathsFor(moduleInScope)); } if (LOG.isDebugEnabled()) { LOG.debug("Creating class-loader with URLs: " + outputPaths); } URL[] effectiveClasspath = outputPaths.toArray(new URL[outputPaths.size()]); if (wantsCopyLibs()) { final Optional<File> tempDir = new TempDirProvider().forCopiedLibraries(project); if (tempDir.isPresent()) { final Path t = Paths.get(tempDir.get().toURI()); effectiveClasspath = new ClasspathStabilizer(project, t).stabilize(outputPaths); } } return new URLClassLoader(effectiveClasspath, getClass().getClassLoader()); }
@Override public ClassLoader run() { return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parentClassloader); } });
@AndroidIncompatible // Android forbids null parent ClassLoader public void testClassPathEntries_duplicateUri_parentWins() throws Exception { URL url = new URL("file:/a"); URLClassLoader parent = new URLClassLoader(new URL[] {url}, null); URLClassLoader child = new URLClassLoader(new URL[] {url}, parent) {}; assertThat(ClassPath.Scanner.getClassPathEntries(child)) .containsExactly(new File("/a"), parent); }
/** * */ private static boolean isConfigResolvable(String configPath, File libDirPathFile) { List<URL> urls = new ArrayList<>(); URLClassLoader parentLoader = (URLClassLoader) SpringContextProcessor.class.getClassLoader(); urls.addAll(Arrays.asList(parentLoader.getURLs())); urls.addAll(SpringContextFactory.gatherAdditionalClassPathUrls(libDirPathFile.getAbsolutePath())); boolean resolvable = false; try (URLClassLoader throwawayCl = new URLClassLoader(urls.toArray(new URL[] {}), null)) { resolvable = throwawayCl.findResource(configPath) != null; } catch (IOException e) { // ignore since it can only happen on CL.close() } return resolvable; } }