protected static boolean addToClasspath(String jar) { Method method; URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = sysLoader.getURLs(); log0(lvl, "before adding to classpath: " + jar); for (int i = 0; i < urls.length; i++) { log0(lvl, "%d: %s", i, urls[i]); } Class sysclass = URLClassLoader.class; try { jar = FileManager.slashify(new File(jar).getAbsolutePath(), false); if (Settings.isWindows()) { jar = "/" + jar; } URL u = (new URI("file", jar, null)).toURL(); method = sysclass.getDeclaredMethod("addURL", new Class[] {URL.class}); method.setAccessible(true); method.invoke(sysLoader, new Object[] {u}); } catch (Exception ex) { log0(-1, ex.getMessage()); return false; } urls = sysLoader.getURLs(); log0(lvl, "after adding to classpath"); for (int i = 0; i < urls.length; i++) { log0(lvl, "%d: %s", i, urls[i]); } return true; }
/** Maybe connect, if not keep track of the problem. */ private synchronized void tryToConnect() { if (connected || exception != null) { return; } try { URLClassLoader l; String cnb = url.getHost(); if (cnb.isEmpty()) { l = globalClassLoader.get(); } else { l = classLoaderMap.get().get(cnb); if (l == null) { throw new IOException("no loader for " + cnb); } } String path = url.getPath().substring(1); URL u = l.getResource(path); if (u == null) { throw new FileNotFoundException(path + " in " + Arrays.toString(l.getURLs())); } real = u.openConnection(); real.connect(); connected = true; } catch (IOException ioe) { exception = ioe; } }
protected List<URL> getResources(String relPath, ClassLoader... classLoaders) { List<URL> answer = new ArrayList<URL>(); for (ClassLoader classLoader : classLoaders) { try { Enumeration<URL> resources = classLoader.getResources(relPath); while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url != null) { answer.add(url); } } } catch (IOException e) { LOG.warn( "Failed to load resources for path " + relPath + " from class loader " + classLoader + ". Reason: " + e, e); } // Lets add all the parent class loaders... if (classLoader instanceof URLClassLoader) { URLClassLoader loader = (URLClassLoader) classLoader; answer.addAll(Arrays.asList(loader.getURLs())); } } return answer; }
public static void loadJARs(Iterable<Path> jars) { ClassLoader cl = IoUtil.class.getClassLoader(); if (!(cl instanceof URLClassLoader)) { throw noAddURL("Not loaded by URLClassLoader", null); } @SuppressWarnings("resource") // Leave open so classes can be loaded. URLClassLoader urlClassLoader = (URLClassLoader) cl; Method addURL; try { addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); addURL.setAccessible(true); } catch (SecurityException | NoSuchMethodException e) { throw noAddURL("Method addURL not available", e); } Set<URL> have = Sets.newHashSet(Arrays.asList(urlClassLoader.getURLs())); for (Path path : jars) { try { URL url = path.toUri().toURL(); if (have.add(url)) { addURL.invoke(cl, url); } } catch (MalformedURLException | IllegalArgumentException | IllegalAccessException e) { throw noAddURL("addURL " + path + " failed", e); } catch (InvocationTargetException e) { throw noAddURL("addURL " + path + " failed", e.getCause()); } } }
public static String toString(ClassLoader loader) { if (loader instanceof URLClassLoader) { URLClassLoader ul = (URLClassLoader) loader; return "URLClassLoader" + Arrays.asList(ul.getURLs()).toString(); } return String.valueOf(loader); }
/** * Handle notification of the creation of a new classloader. * * @param logger the logging channel * @param label the classloader label * @param category the classloader category * @param classloader the new classloader to report */ private static void classloaderConstructed( Logger logger, String label, Category category, ClassLoader classloader) { if (logger.isTraceEnabled()) { int id = System.identityHashCode(classloader); StringBuffer buffer = new StringBuffer(); buffer.append("new "); buffer.append(category.toString()); buffer.append(" classloader for " + label); buffer.append("\n id: " + id); ClassLoader parent = classloader.getParent(); if (null != parent) { int pid = System.identityHashCode(parent); buffer.append("\n extends: " + pid); } if (classloader instanceof URLClassLoader) { URLClassLoader loader = (URLClassLoader) classloader; URL[] urls = loader.getURLs(); if (urls.length == 1) { buffer.append("\n contains: 1 entry"); } else { buffer.append("\n contains: " + urls.length + " entries"); } for (int i = 0; i < urls.length; i++) { URL url = urls[i]; buffer.append("\n [" + (i + 1) + "] " + url.toString()); } } logger.trace(buffer.toString()); } }
/** Method used to initialize classpath for compiles. */ private void initClassPath() { URL[] urls = parentClassLoader.getURLs(); StringBuffer cpath = new StringBuffer(); String sep = System.getProperty("path.separator"); for (int i = 0; i < urls.length; i++) { // Tomcat 4 can use URL's other than file URL's, // a protocol other than file: will generate a // bad file system path, so only add file: // protocol URL's to the classpath. if (urls[i].getProtocol().equals("file")) { cpath.append((String) urls[i].getFile() + sep); } } cpath.append(options.getScratchDir() + sep); String cp = (String) context.getAttribute(Constants.SERVLET_CLASSPATH); if (cp == null || cp.equals("")) { cp = options.getClassPath(); } classpath = cpath.toString() + cp; if (log.isDebugEnabled()) { log.debug("Compilation classpath initialized: " + getClassPath()); } }
private ClassLoader addToClassPath(ClassLoader classLoader, String[] newPaths) throws ExecutorException { URLClassLoader loader = (URLClassLoader) classLoader; List<URL> curPath = Arrays.asList(loader.getURLs()); List<URL> newPath = Lists.newArrayList(); for (URL onePath : curPath) { newPath.add(onePath); } curPath = newPath; if (newPaths != null) { for (String onestr : newPaths) { if (StringUtils.indexOf(onestr, FILE_PREFIX) == 0) { onestr = StringUtils.substring(onestr, CQLConst.I_7); } URL oneurl = getFileURL(onestr); if (!curPath.contains(oneurl)) { curPath.add(oneurl); } } } return new URLClassLoader(curPath.toArray(new URL[0]), loader); }
public NationClassLoader(URL[] urls, Vector nations) { super(urls); for (int i = 0; i < urls.length; i++) { file = urls[i].getFile(); fileTmp = new File(file); System.out.println( "NationClassLoader - Does " + fileTmp.toString() + " exists : " + fileTmp.exists()); name = file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")); runtimeObject = null; try { jarLoader = URLClassLoader.newInstance(new URL[] {urls[i]}); System.out.println( "NationClassLoader - JARloader trying : " + jarLoader.getURLs()[0].toString()); runtimeObject = jarLoader.loadClass(name + "/" + name).newInstance(); } catch (Exception e) { System.err.println("NationClassLoader - Stinking error : " + e); } if (runtimeObject != null) { natFile = (nationFile2) runtimeObject; nations.addElement(natFile); } } }
private static Stream<String> apps() { if (cl instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader) cl; return Stream.of(ucl.getURLs()) .map(propagating(url -> Paths.get(url.toURI()))) .flatMap( propagating( path -> { if (Files.isRegularFile(path)) { return zipContents(path); } else if (Files.isDirectory(path)) { return Files.walk(path) .map(subpath -> path.relativize(subpath)) .map(subpath -> subpath.toString()) .filter(subpath -> subpath.endsWith(".class")) .map(Scanner::toClassName); } else { return Stream.empty(); } })) .filter(x -> !x.startsWith("com.cakemanny.app.")) .filter(implementsInterface(App.class)); } else { return Stream.empty(); } }
public void testWithNoPackage() throws Exception { RecorderLocator.clearRecorders(); final URLClassLoader ourClassLoader = (URLClassLoader) BlockingClassLoader.class.getClassLoader(); final BlockingClassLoader blockingClassLoader = new BlockingClassLoader( ourClassLoader, Arrays.<String>asList(AnotherClass.class.getName())); final NoPackageURLClassLoader cl = new NoPackageURLClassLoader(ourClassLoader.getURLs(), blockingClassLoader); final Class<?> noPackageClass = cl.loadClass(AnotherClass.class.getName()); final Method noPackageMethod = noPackageClass.getMethod("getOne"); assertEquals(1, noPackageMethod.invoke(null)); m_recorderStubFactory.assertNoMoreCalls(); final Object result = m_instrumenter.createInstrumentedProxy(null, m_recorder, noPackageClass); assertSame(noPackageClass, result); m_recorderStubFactory.assertNoMoreCalls(); assertEquals(1, noPackageMethod.invoke(null)); m_recorderStubFactory.assertSuccess("start"); m_recorderStubFactory.assertSuccess("end", true); m_recorderStubFactory.assertNoMoreCalls(); }
/** Initializes the cache. */ protected void initialize() { String part; File file; URLClassLoader sysLoader; URL[] urls; m_Cache = new Hashtable<String, HashSet<String>>(); sysLoader = (URLClassLoader) getClass().getClassLoader(); urls = sysLoader.getURLs(); for (URL url : urls) { if (VERBOSE) System.out.println("Classpath-part: " + part); file = null; part = url.toString(); if (part.startsWith("file:")) { part = part.replace(" ", "%20"); try { file = new File(new java.net.URI(part)); } catch (URISyntaxException e) { e.printStackTrace(); } } else { file = new File(part); } if (file == null) { System.err.println("Skipping: " + part); continue; } // find classes if (file.isDirectory()) initFromDir(file); else if (file.exists()) initFromJar(file); } }
/** March through the classloaders to find one that can return urls. */ @SuppressWarnings("resource") private URL[] getUrls() { Set<URL> urlSet = new HashSet<URL>(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); while (true) { if (cl == null) { return urlSet.toArray(new URL[urlSet.size()]); } if (!(cl instanceof URLClassLoader)) { cl = cl.getParent(); continue; } URLClassLoader ucl = (URLClassLoader) cl; URL[] urls = ucl.getURLs(); urlSet.addAll(Arrays.asList(urls)); if (cl == ClassLoader.getSystemClassLoader()) { return urlSet.toArray(new URL[urlSet.size()]); } cl = cl.getParent(); } }
/** * Builds a {@link java.util.Vector} containing Strings which each name a file who's name matches * the pattern set by setPattern(String). The classpath is searched recursively, so use with * caution. * * @return Vector<String> containing matching filenames */ public Vector<String> findMatches() { Vector<String> matches = new Vector<String>(); URLClassLoader cl = getURLClassLoader(); if (cl == null) { throw new XWorkException("unable to attain an URLClassLoader"); } URL[] parentUrls = cl.getURLs(); compiledPattern = (int[]) patternMatcher.compilePattern(pattern); for (URL url : parentUrls) { if (!"file".equals(url.getProtocol())) { continue; } URI entryURI; try { entryURI = url.toURI(); } catch (URISyntaxException e) { continue; } File entry = new File(entryURI); Vector<String> results = checkEntries(entry.list(), entry, ""); if (results != null) { matches.addAll(results); } } return matches; }
public PathRewritingClassLoader(String prefix, URLClassLoader parent) { super(parent.getURLs(), parent); this.prefix = prefix + "/"; _ucp = new URLClassPath(getURLs()); _acc = AccessController.getContext(); }
/** * @see * org.overlord.commons.dev.server.discovery.IModuleDiscoveryStrategy#discover(org.overlord.commons.dev.server.discovery.ModuleDiscoveryContext) */ @Override public DevServerModule discover(ModuleDiscoveryContext context) { URLClassLoader urlCL = (URLClassLoader) getClass().getClassLoader(); TreeSet<URL> sortedURLs = new TreeSet<URL>( new Comparator<URL>() { @Override public int compare(URL o1, URL o2) { return o1.toExternalForm().compareTo(o2.toExternalForm()); } }); sortedURLs.addAll(Arrays.asList(urlCL.getURLs())); String moduleUrl = null; // Look for something that looks like a maven path String groupIdAsPath = groupId.replace('.', '/'); for (URL url : sortedURLs) { String urlstr = url.toExternalForm(); if (urlstr.contains(groupIdAsPath) && urlstr.contains("/" + artifactId + "-")) { // $NON-NLS-1$ //$NON-NLS-2$ moduleUrl = urlstr; break; } } if (moduleUrl == null) return null; debug("Module URL: " + moduleUrl); // $NON-NLS-1$ try { String pathToWar = moduleUrl.replace("-classes.jar", ".war"); // $NON-NLS-1$ //$NON-NLS-2$ URL warUrl = new URL(pathToWar); File war = new File(warUrl.toURI()); debug("WAR: " + war); // $NON-NLS-1$ if (war.isFile()) { File workDir = new File(context.getTargetDir(), war.getName()); debug("Work Dir: " + workDir); // $NON-NLS-1$ DevServerModule module = new DevServerModule(); module.setInIDE(false); module.setWorkDir(workDir); module.setModuleDir(workDir); module.clean(); workDir.mkdirs(); try { org.overlord.commons.dev.server.util.ArchiveUtils.unpackToWorkDir(war, workDir); } catch (IOException e) { throw new RuntimeException(e); } return module; } } catch (Exception e) { throw new RuntimeException(e); } return null; }
private static void purgeCode(String mainClass, URL newUrl) { Class<?> clazz1 = null; for (Class<?> clazz : externalListenerClasses) { if (mainClass.equals(clazz.getCanonicalName())) { clazz1 = clazz; break; } } if (clazz1 == null) { return; } externalListenerClasses.remove(clazz1); ExternalListener remove = null; for (ExternalListener list : externalListeners) { if (list.getClass().equals(clazz1)) { remove = list; break; } } RendererConfiguration.resetAllRenderers(); if (remove != null) { externalListeners.remove(remove); remove.shutdown(); LooksFrame frame = (LooksFrame) PMS.get().getFrame(); frame.getPt().removePlugin(remove); } for (int i = 0; i < 3; i++) { System.gc(); } URLClassLoader cl = (URLClassLoader) clazz1.getClassLoader(); URL[] urls = cl.getURLs(); for (URL url : urls) { String mainClass1 = getMainClass(url); if (mainClass1 == null || !mainClass.equals(mainClass1)) { continue; } File f = url2file(url); File f1 = url2file(newUrl); if (f1 == null || f == null) { continue; } if (!f1.getName().equals(f.getName())) { addToPurgeFile(f); } } }
private static void appendEntries(StringBuffer buffer, URLClassLoader classloader) { URL[] urls = classloader.getURLs(); for (int i = 0; i < urls.length; i++) { buffer.append("\n "); URL url = urls[i]; String spec = url.toString(); buffer.append(spec); } buffer.append("\n"); }
/** * Méthode. * * @param l URLClassLaoder * @return Liste de string */ private List<String> getAlreadyLoadedJar(final URLClassLoader l) { final List<String> alreadyLoadedJars = new ArrayList<String>(); final URL[] urls = l.getURLs(); if (urls != null) { for (final URL url : urls) { alreadyLoadedJars.add(url.getPath()); } } return alreadyLoadedJars; }
private void listClassloader(String indent, ClassLoader uc) { if (uc != null) { if (uc instanceof URLClassLoader) { URLClassLoader urlC = (URLClassLoader) uc; getLog().debug(indent + "Classloader : " + uc + " " + Arrays.toString(urlC.getURLs())); } else { getLog().debug(indent + "Classloader : " + uc); } listClassloader(indent + " ", uc.getParent()); } }
/** * Make a different ClassLoader that loads the same URLs as this one, and use it to compile an * {@code @AutoJson} class. If Velocity loads its managers using the context class loader, and * that loader is still the original one that loaded this test, then it will find the original * copy of the Velocity classes rather than the one from the new loader, and fail. * * <p>This test assumes that the test class was loaded by a URLClassLoader and that that loader's * URLs also include the Velocity classes. */ public void testClassLoaderHack() throws Exception { URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader(); URLClassLoader newLoader = new URLClassLoader(myLoader.getURLs(), myLoader.getParent()); String velocityClassName = Velocity.class.getName(); Class<?> myVelocity = myLoader.loadClass(velocityClassName); Class<?> newVelocity = newLoader.loadClass(velocityClassName); assertThat(myVelocity).isNotEqualTo(newVelocity); Runnable test = (Runnable) newLoader.loadClass(RunInClassLoader.class.getName()).newInstance(); assertThat(test.getClass()).isNotEqualTo(RunInClassLoader.class); test.run(); }
public String getClasspath() { // this assumes we run in Maven StringBuilder buf = new StringBuilder(); URLClassLoader ucl = (URLClassLoader) getClass().getClassLoader(); for (URL url : ucl.getURLs()) { if (buf.length() > 0) { buf.append(File.pathSeparatorChar); } buf.append(FileUtils.toFile(url)); // assume all of them are file URLs } return buf.toString(); }
private static void addAllClassPathEntries( TreeLogger logger, ClassLoader classLoader, List<ClassPathEntry> classPath) { // URL is expensive in collections, so we use URI instead // See: http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html Set<URI> seenEntries = new HashSet<URI>(); for (; classLoader != null; classLoader = classLoader.getParent()) { if (classLoader instanceof URLClassLoader) { URLClassLoader urlClassLoader = (URLClassLoader) classLoader; URL[] urls = urlClassLoader.getURLs(); for (URL url : urls) { URI uri; try { // XXX >>> Instantiations // probably bug in GWT: having gwt-user.jar somewhere in path with spaces, url.toURI() // complains on invalid character String urlString = url.toExternalForm(); urlString = StringUtils.replace(urlString, " ", "%20"); urlString = StringUtils.replace(urlString, "file://Users/", "file:/Users/"); try { url = new URL(urlString); } catch (MalformedURLException e) { // ignore } // XXX <<< Instantiations uri = url.toURI(); } catch (URISyntaxException e) { logger.log(TreeLogger.WARN, "Error processing classpath URL '" + url + "'", e); continue; } if (seenEntries.contains(uri)) { continue; } seenEntries.add(uri); Throwable caught; try { ClassPathEntry entry = createEntryForUrl(logger, url); if (entry != null) { classPath.add(entry); } continue; } catch (AccessControlException e) { logger.log(TreeLogger.DEBUG, "Skipping URL due to access restrictions: " + url); continue; } catch (URISyntaxException e) { caught = e; } catch (IOException e) { caught = e; } logger.log(TreeLogger.WARN, "Error processing classpath URL '" + url + "'", caught); } } } }
/** * get class pathes from all url ClassLoaders * * @param ucl URL Class Loader * @param pathes Hashmap with allpathes */ private static void getClassPathesFromClassLoader(URLClassLoader ucl, ArrayList pathes) { ClassLoader pcl = ucl.getParent(); // parent first if (pcl instanceof URLClassLoader) getClassPathesFromClassLoader((URLClassLoader) pcl, pathes); ResourceProvider frp = ResourcesImpl.getFileResourceProvider(); // get all pathes URL[] urls = ucl.getURLs(); for (int i = 0; i < urls.length; i++) { Resource file = frp.getResource(urls[i].getPath()); if (file.exists()) pathes.add(ResourceUtil.getCanonicalResourceEL(file)); } }
public void testEquals_classloader_equal() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("BLUE").get(null); assertEquals(true, blue1.equals(blue2)); } }
public void testCompareTo_classloader_different() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("RED").get(null); assertTrue(((Comparable) blue1).compareTo(blue2) != 0); } }
public static void main(String[] args) throws Exception { Class thisClass = MethodResultTest.class; Class exoticClass = Exotic.class; String exoticClassName = Exotic.class.getName(); ClassLoader testClassLoader = thisClass.getClassLoader(); if (!(testClassLoader instanceof URLClassLoader)) { System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader); System.exit(1); } URLClassLoader tcl = (URLClassLoader) testClassLoader; URL[] urls = tcl.getURLs(); ClassLoader shadowLoader = new ShadowLoader( urls, testClassLoader, new String[] { exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName() }); Class cl = shadowLoader.loadClass(exoticClassName); if (cl == exoticClass) { System.out.println( "TEST INVALID: Shadow class loader loaded " + "same class as test class loader"); System.exit(1); } Thread.currentThread().setContextClassLoader(shadowLoader); ObjectName on = new ObjectName("a:b=c"); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); mbs.createMBean(Thing.class.getName(), on); final String[] protos = {"rmi", "iiop", "jmxmp"}; boolean ok = true; for (int i = 0; i < protos.length; i++) { try { ok &= test(protos[i], mbs, on); System.out.println(); } catch (Exception e) { System.out.println("TEST FAILED WITH EXCEPTION:"); e.printStackTrace(System.out); ok = false; } } if (ok) System.out.println("Test passed"); else { System.out.println("TEST FAILED"); System.exit(1); } }
public static void printClassPath(boolean single) { ClassLoader cl = ClassLoader.getSystemClassLoader(); URLClassLoader urlcl = (URLClassLoader) cl; URL[] urls = urlcl.getURLs(); if (single) { String cp = System.getProperty("java.class.path"); System.out.println(cp); } else { for (URL url : urls) { String file = url.getFile(); System.out.println(file); } } }
public static void nailMain(NGContext context) throws Exception { String[] args = context.getArgs(); if (args.length == 0) { URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = sysLoader.getURLs(); for (int i = 0; i < urls.length; ++i) { context.out.println(urls[i]); } } else { for (int i = 0; i < args.length; ++i) { File file = new File(args[i]); addToSystemClassLoader(file.toURL()); } } }
private List<File> classPath(ClassLoader cl) { List<File> paths = new LinkedList<File>(); if (cl == null) { return paths; } if (cl instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader) cl; URL[] urls = ucl.getURLs(); if (urls != null) { for (URL url : urls) { paths.add(new File(url.getFile())); } } } return paths; }