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

The following examples show how to use java.net.URLClassLoader#getURLs() . 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: JavassistUtil.java    From Bukkit-Connect with GNU General Public License v3.0 6 votes vote down vote up
public static ClassPool getClassPool() {
	ClassPool classPool = ClassPool.getDefault();
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	if (classLoader instanceof URLClassLoader) {
		URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
		for (URL url : urlClassLoader.getURLs()) {
			try {
				// assume files
				String path = Paths.get(url.toURI()).toString();
				classPool.appendClassPath(path);
			} catch (Exception exception) {
				exception.printStackTrace();
			}
		}
	}
	return classPool;
}
 
Example 2
Source File: DynamicClassLoader.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private void buildParentClassPath(ArrayList<String> cp)
{
  ClassLoader parent = getParent();

  if (parent instanceof DynamicClassLoader)
    ((DynamicClassLoader) parent).buildClassPath(cp);
  else {
    cp.addAll(getClassPathList());

    for (; parent != null; parent = parent.getParent()) {
      // XXX: should be reverse order
      if (parent instanceof URLClassLoader) {
        URLClassLoader urlLoader = (URLClassLoader) parent;

        for (URL url : urlLoader.getURLs()) {
          String urlString = url.toString();
          if (urlString.startsWith("file:"))
            urlString = urlString.substring("file:".length());

          if (! cp.contains(urlString))
            cp.add(urlString);
        }
      }
    }
  }
}
 
Example 3
Source File: ClassPath.java    From beakerx with Apache License 2.0 6 votes vote down vote up
static Map<URI, ClassLoader> getClassPathEntries(
        ClassLoader classloader) {
  Map<URI, ClassLoader> entries = new HashMap<>();
  // Search parent first, since it's the order ClassLoader#loadClass() uses.
  ClassLoader parent = classloader.getParent();
  if (parent != null) {
    entries.putAll(getClassPathEntries(parent));
  }
  if (classloader instanceof URLClassLoader) {
    URLClassLoader urlClassLoader = (URLClassLoader) classloader;
    for (URL entry : urlClassLoader.getURLs()) {
      URI uri;
      try {
        uri = entry.toURI();
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
      }
      if (!entries.containsKey(uri)) {
        entries.put(uri, classloader);
      }
    }
  }
  return new HashMap<>(entries);
}
 
Example 4
Source File: ClasspathUtil.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void addUrl(URLClassLoader classLoader, Iterable<URL> classpathElements) {
    try {
        Set<URI> original = new HashSet<URI>();
        for (URL url : classLoader.getURLs()) {
            original.add(url.toURI());
        }
        JavaMethod<URLClassLoader, Object> method = JavaReflectionUtil.method(URLClassLoader.class, Object.class, "addURL", URL.class);
        for (URL classpathElement : classpathElements) {
            if (original.add(classpathElement.toURI())) {
                method.invoke(classLoader, classpathElement);
            }
        }
    } catch (Throwable t) {
        throw new RuntimeException(String.format("Could not add URLs %s to class path for ClassLoader %s", classpathElements, classLoader), t);
    }
}
 
Example 5
Source File: ClassloaderUtil.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add URL to CLASSPATH
 * @param u URL
 * @throws IOException if something goes wrong when adding a url
 */
public static void addURL(URL u) throws IOException {
  ClassloaderUtil clu = new ClassloaderUtil();
  //        URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  URLClassLoader sysLoader = (URLClassLoader) clu.getClass().getClassLoader();
  URL urls[] = sysLoader.getURLs();
  for (int i = 0; i < urls.length; i++) {
    if (urls[i].toString().toLowerCase().equals(u.toString().toLowerCase())) {
      System.err.println("URL " + u + " is already in the CLASSPATH");
      return;
    }
  }
  Class<?> sysclass = URLClassLoader.class;
  try {
    Method method = sysclass.getDeclaredMethod("addURL", parameters);
    method.setAccessible(true);
    method.invoke(sysLoader, new Object[]{u});
  } catch (Throwable t) {
    t.printStackTrace();
    throw new IOException("Error, could not add URL to system classloader");
  }
}
 
Example 6
Source File: LeakTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static WeakReference<ClassLoader>
        testShadow(Class<?> originalTestClass) throws Exception {
    URLClassLoader originalLoader =
            (URLClassLoader) originalTestClass.getClassLoader();
    URL[] urls = originalLoader.getURLs();
    URLClassLoader shadowLoader =
            new ShadowClassLoader(urls, originalLoader.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 7
Source File: Test6800154.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
    Class cl = Class.forName("Test6800154");
    URLClassLoader apploader = (URLClassLoader) cl.getClassLoader();

    // Iterate over all divisors.
    for (int i = 0; i < DIVISORS.length; i++) {
        System.setProperty("divisor", "" + DIVISORS[i]);
        ClassLoader loader = new URLClassLoader(apploader.getURLs(), apploader.getParent());
        Class c = loader.loadClass("Test6800154");
        Runnable r = (Runnable) c.newInstance();
        r.run();
    }
}
 
Example 8
Source File: Test5057225.java    From jdk8u60 with GNU General Public License v2.0 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 9
Source File: Test5057225.java    From TencentKona-8 with GNU General Public License v2.0 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 10
Source File: Test6805724.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Class cl = Class.forName("Test6805724");
    URLClassLoader apploader = (URLClassLoader) cl.getClassLoader();

    // Iterate over all 2^k-1 divisors.
    for (int k = 1; k < Long.SIZE; k++) {
        long divisor = (1L << k) - 1;
        System.setProperty("divisor", "" + divisor);
        ClassLoader loader = new URLClassLoader(apploader.getURLs(), apploader.getParent());
        Class c = loader.loadClass("Test6805724");
        Runnable r = (Runnable) c.newInstance();
        r.run();
    }
}
 
Example 11
Source File: Test6805724.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Class cl = Class.forName("Test6805724");
    URLClassLoader apploader = (URLClassLoader) cl.getClassLoader();

    // Iterate over all 2^k-1 divisors.
    for (int k = 1; k < Long.SIZE; k++) {
        long divisor = (1L << k) - 1;
        System.setProperty("divisor", "" + divisor);
        ClassLoader loader = new URLClassLoader(apploader.getURLs(), apploader.getParent());
        Class c = loader.loadClass("Test6805724");
        Runnable r = (Runnable) c.newInstance();
        r.run();
    }
}
 
Example 12
Source File: ArchivePathHelper.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static URL archivePathToURLViaURLClassLoader(URLClassLoader urlClassLoader, String archivePath) {
    URL[] urls = urlClassLoader.getURLs();
    if (urls != null) {
        for (URL url: urls) {
            String fileName = url.getFile();
            String checkedArchivePath = (fileName.endsWith("/") && !archivePath.endsWith("/")) ? (archivePath + "/") : archivePath;
            if (fileName.endsWith(checkedArchivePath)) {
                return archiveFilePathToURL(fileName);
            }
        }
    }
    return null;
}
 
Example 13
Source File: Test6823354.java    From openjdk-jdk9 with GNU General Public License v2.0 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 14
Source File: FileUtils.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
public static URL getClassLoaderURL() throws URISyntaxException, IOException {
	URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
	for (URL url : classLoader.getURLs()) {
		File f = new File(url.toURI().getPath());
		ZipFile zipFile = new ZipFile(f);
		ZipEntry entry = zipFile.getEntry("eu/the5zig/util/io/FileUtils.class");
		zipFile.close();
		if (entry != null) {
			return url;
		}
	}
	throw new RuntimeException("Current Class Loader Context not found!");
}
 
Example 15
Source File: ResourceBundleWrapper.java    From ccu-historian with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Instantiate a {@link URLClassLoader} for resource lookups where the
 * codeBase URL is removed.  This method is typically called from an
 * applet's init() method.  If this method is never called, the
 * <code>getBundle()</code> methods map to the standard
 * {@link ResourceBundle} lookup methods.
 *
 * @param codeBase  the codeBase URL.
 * @param urlClassLoader  the class loader.
 */
public static void removeCodeBase(URL codeBase,
        URLClassLoader urlClassLoader) {
    List urlsNoBase = new ArrayList();

    URL[] urls = urlClassLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (! urls[i].sameFile(codeBase)) {
            urlsNoBase.add(urls[i]);
        }
    }
    // substitute the filtered URL list
    URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);
    noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}
 
Example 16
Source File: ResourceBundleWrapper.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Instantiate a {@link URLClassLoader} for resource lookups where the
 * codeBase URL is removed.  This method is typically called from an
 * applet's init() method.  If this method is never called, the
 * <code>getBundle()</code> methods map to the standard
 * {@link ResourceBundle} lookup methods.
 *
 * @param codeBase  the codeBase URL.
 * @param urlClassLoader  the class loader.
 */
public static void removeCodeBase(URL codeBase,
        URLClassLoader urlClassLoader) {
    List urlsNoBase = new ArrayList();

    URL[] urls = urlClassLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (!urls[i].sameFile(codeBase)) {
            urlsNoBase.add(urls[i]);
        }
    }
    // substitute the filtered URL list
    URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);
    noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}
 
Example 17
Source File: Test6805724.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Class cl = Class.forName("Test6805724");
    URLClassLoader apploader = (URLClassLoader) cl.getClassLoader();

    // Iterate over all 2^k-1 divisors.
    for (int k = 1; k < Long.SIZE; k++) {
        long divisor = (1L << k) - 1;
        System.setProperty("divisor", "" + divisor);
        ClassLoader loader = new URLClassLoader(apploader.getURLs(), apploader.getParent());
        Class c = loader.loadClass("Test6805724");
        Runnable r = (Runnable) c.newInstance();
        r.run();
    }
}
 
Example 18
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
   * The classpath used to compile is (in precedence order)
   *   - the classpath for this migration app  (first in order to pick up v3 support, overriding others)
   *   - any Pears, going up the parent chain, closest ones first
   *   - any Jars, going up the parent chain, closest ones last
   *   - passed in migrate classpath
   * @return the classpath to use in compiling the jcasgen'd sources
   */
  private String getCompileClassPath(Container container) {
 
    // start with this (the v3migration tool) app's classpath to a cp string
    URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = systemClassLoader.getURLs();
    StringBuilder cp = new StringBuilder();
    
    boolean firstTime = true;
    for (URL url : urls) {
      if (! firstTime) {
        cp.append(File.pathSeparatorChar);
      } else {
        firstTime = false;
      }
      cp.append(url.getPath());
    }
    
    // pears up the classpath, closest first
    Container c = container;
    while (c != null) {
      if (c.isPear) {
        cp.append(File.pathSeparator).append(c.pearClasspath);
      }
      c = c.parent;
    }
    
    // add the migrateClasspath, expanded
    
    if (null != migrateClasspath) {
      cp.append(File.pathSeparator).append(Misc.expandClasspath(migrateClasspath));
    }
 
    // add the Jars, closest last
    c = container;
    List<String> ss = new ArrayList<>();
    while (c != null) {
      if (c.isJar) {
        ss.add(c.root.toString());
      }
      c = c.parent;
    }
    Collections.reverse(ss);
    ss.forEach(s -> cp.append(File.pathSeparator).append(s));
        
//    System.out.println("debug: compile classpath = " + cp.toString());
    return cp.toString();
  }
 
Example 19
Source File: LibraryFingerprint.java    From java-specialagent with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new {@code LibraryFingerprint} with the specified {@code URL}
 * objects referencing JAR files.
 *
 * @param classLoader The {@code ClassLoader} to use for resolution of classes
 *          that should not be part of the fingerprint.
 * @param presents List of classes the fingerprint must assert are present.
 * @param absents List of classes the fingerprint must assert are absent.
 * @param logger The logger to be used during the fingerprinting execution.
 * @throws NullPointerException If {@code manifest} or {@code scanUrls} is
 *           null.
 * @throws IllegalArgumentException If the number of members in
 *           {@code scanUrls} is zero.
 * @throws IOException If an I/O error has occurred.
 */
LibraryFingerprint(final URLClassLoader classLoader, final List<String> presents, final List<String> absents, final Logger logger) throws IOException {
  if (classLoader.getURLs().length == 0)
    throw new IllegalArgumentException("Number of scan URLs must be greater than 0");

  this.classes = new FingerprintBuilder(logger).build(classLoader, Integer.MAX_VALUE).toArray(new ClassFingerprint[0]);
  this.presents = presents;
  this.absents = absents;
}
 
Example 20
Source File: ExtendedJettyClassLoader.java    From geomajas-project-server with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Constructs an extended class loader which delegates to the specified class loader and uses the specified parent
 * class loader.
 * 
 * @param delegate
 *            class loader to delegate to
 * @param parent
 *            the designated parent of this class loader
 * @param extend
 *            should be true if the scanning methods have to be delegated to the superclass
 */
public ExtendedJettyClassLoader(URLClassLoader delegate, ClassLoader parent, boolean extend) {
	super(delegate.getURLs(), parent);
	this.delegate = delegate;
	this.extend = extend;
}