加载Jar文件到指定loader中

@param loader {@link URLClassLoader}
@param jarFile 被加载的jar
@throws UtilException IO异常包装和执行异常
355669
public static void loadJar(URLClassLoader loader, File jarFile) throws UtilException {
		try {
			final Method method = ClassUtil.getDeclaredMethod(URLClassLoader.class, "addURL", URL.class);
			if (null != method) {
				method.setAccessible(true);
				final List<File> jars = loopJar(jarFile);
				for (File jar : jars) {
					ReflectUtil.invoke(loader, method, new Object[] { jar.toURI().toURL() });
				}
			}
		} catch (IOException e) {
			throw new UtilException(e);
		}
	}
872074
public void loadClassifier(File file) {
    try {
      if (file != null) {
        classifier = CRFClassifier.getClassifier(file);
      } else {
        // default classifier in jar
        classifier = CRFClassifier.getDefaultClassifier();
      }
    } catch (Throwable e) {
      // we catch Throwable, since we'd also like to be able to get an
      // OutOfMemoryError
      String message;
      if (file != null) {
        message = "Error loading CRF: " + file.getAbsolutePath();
      } else {
        message = "Error loading default CRF";
      }
      System.err.println(message);
      String title = "CRF Load Error";
      String msg = e.toString();
      if (msg != null) {
        message += "\n" + msg;
      }
      displayError(title, message);
      return;
    }
    removeTags();
    buildTagPanel();
    // buildExtractButton();
    extractButton.setEnabled(true);
    extract.setEnabled(true);
  }
1001753
public void addFile(String sourceFolder, String name, ClassLoaderFile file) {
		Assert.notNull(sourceFolder, "SourceFolder must not be null");
		Assert.notNull(name, "Name must not be null");
		Assert.notNull(file, "File must not be null");
		removeAll(name);
		getOrCreateSourceFolder(sourceFolder).add(name, file);
	}
616643
@SuppressWarnings("unchecked")
	private void addURL(URL url) throws Exception {
		URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		Class clazz = URLClassLoader.class;
		Method method = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
		method.setAccessible(true);
		method.invoke(classLoader, new Object[] { url });
	}
1182273
protected void launch(String[] args) throws Exception {
		JarFile.registerUrlProtocolHandler();
		ClassLoader classLoader = createClassLoader(getClassPathArchives());
		launch(args, getMainClass(), classLoader);
	}
1340664
public void setClassLoader (ClassLoader loader)
    {
        _loader = loader;
        if (_comm != null) {
            _comm.setClassLoader(loader);
        }
    }
345496
protected boolean validateJarFile(File jarfile)
        throws IOException {

        if (triggers == null)
            return (true);
        JarFile jarFile = new JarFile(jarfile);
        for (int i = 0; i < triggers.length; i++) {
            Class clazz = null;
            try {
                if (parent != null) {
                    clazz = parent.loadClass(triggers[i]);
                } else {
                    clazz = Class.forName(triggers[i]);
                }
            } catch (Throwable t) {
                clazz = null;
            }
            if (clazz == null)
                continue;
            String name = triggers[i].replace('.', '/') + ".class";
            if (log.isDebugEnabled())
                log.debug(" Checking for " + name);
            JarEntry jarEntry = jarFile.getJarEntry(name);
            if (jarEntry != null) {
                log.info("validateJarFile(" + jarfile + 
                    ") - jar not loaded. See Servlet Spec 2.3, "
                    + "section 9.7.2. Offending class: " + name);
                jarFile.close();
                return (false);
            }
        }
        jarFile.close();
        return (true);

    }
24151
protected Set<Class<?>> loadAllClass(File jarFile, ScriptClassLoader loader) throws Exception {
		Set<Class<?>> clzzs = new HashSet<Class<?>>();
		JarFile jf = new JarFile(jarFile);
		try {
			loader.addURL(jarFile.toURI().toURL());// 添加文件到加载器
			Enumeration<JarEntry> it = jf.entries();
			while (it.hasMoreElements()) {
				JarEntry jarEntry = it.nextElement();
				if (jarEntry.getName().endsWith(".class")) {
					String className = jarEntry.getName().replace("/", ".").replaceAll(".class", "");
					clzzs.add(loader.findClass(className));
				}
			}
		} finally {
			jf.close();
		}
		return clzzs;
	}
1156594
private static void getClassPathesFromClassLoader(URLClassLoader ucl, ArrayList<Resource> 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));
	}

    }
627473
public static List<File> localFilesFromUrlClassLoader(final URLClassLoader urlClassLoader) {
        checkNotNull("urlClassLoader", urlClassLoader);

        final List<File> files = new ArrayList<>();

        final URL[] urls = urlClassLoader.getURLs();
        for (final URL url : urls) {
            if ("file".equals(url.getProtocol())) {
                files.add(asFile(url));
            }
        }

        return files;

    }
476986
public static List<URL> getClasspathURLs(ClassLoader loader) {
        List<URL> urls = Lists.newArrayList();
        if (loader != null) {
            final Enumeration<URL> resources;
            try {
                resources = loader.getResources("");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            while (resources.hasMoreElements()) {
                URL location = resources.nextElement();
                urls.add(location);
            }
        }
        return urls;
    }
1300389
public static void load(String originalName, ClassLoader loader) {
        // Adjust expected name to support shading of native libraries.
        String packagePrefix = calculatePackagePrefix().replace('.', '_');
        String name = packagePrefix + originalName;
        List<Throwable> suppressed = new ArrayList<Throwable>();
        try {
            // first try to load from java.library.path
            loadLibrary(loader, name, false);
            return;
        } catch (Throwable ex) {
            suppressed.add(ex);
            logger.debug(
                    "{} cannot be loaded from java.library.path, "
                    + "now trying export to -Dio.netty.native.workdir: {}", name, WORKDIR, ex);
        }

        String libname = System.mapLibraryName(name);
        String path = NATIVE_RESOURCE_HOME + libname;

        InputStream in = null;
        OutputStream out = null;
        File tmpFile = null;
        URL url;
        if (loader == null) {
            url = ClassLoader.getSystemResource(path);
        } else {
            url = loader.getResource(path);
        }
        try {
            if (url == null) {
                if (PlatformDependent.isOsx()) {
                    String fileName = path.endsWith(".jnilib") ? NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib" :
                            NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib";
                    if (loader == null) {
                        url = ClassLoader.getSystemResource(fileName);
                    } else {
                        url = loader.getResource(fileName);
                    }
                    if (url == null) {
                        FileNotFoundException fnf = new FileNotFoundException(fileName);
                        ThrowableUtil.addSuppressedAndClear(fnf, suppressed);
                        throw fnf;
                    }
                } else {
                    FileNotFoundException fnf = new FileNotFoundException(path);
                    ThrowableUtil.addSuppressedAndClear(fnf, suppressed);
                    throw fnf;
                }
            }

            int index = libname.lastIndexOf('.');
            String prefix = libname.substring(0, index);
            String suffix = libname.substring(index, libname.length());

            tmpFile = File.createTempFile(prefix, suffix, WORKDIR);
            in = url.openStream();
            out = new FileOutputStream(tmpFile);

            if (shouldShadedLibraryIdBePatched(packagePrefix)) {
                patchShadedLibraryId(in, out, originalName, name);
            } else {
                byte[] buffer = new byte[8192];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
            }

            out.flush();

            // Close the output stream before loading the unpacked library,
            // because otherwise Windows will refuse to load it when it's in use by other process.
            closeQuietly(out);
            out = null;
            loadLibrary(loader, tmpFile.getPath(), true);
        } catch (UnsatisfiedLinkError e) {
            try {
                if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() &&
                    !NoexecVolumeDetector.canExecuteExecutable(tmpFile)) {
                    // Pass "io.netty.native.workdir" as an argument to allow shading tools to see
                    // the string. Since this is printed out to users to tell them what to do next,
                    // we want the value to be correct even when shading.
                    logger.info("{} exists but cannot be executed even when execute permissions set; " +
                                "check volume for \"noexec\" flag; use -D{}=[path] " +
                                "to set native working directory separately.",
                                tmpFile.getPath(), "io.netty.native.workdir");
                }
            } catch (Throwable t) {
                suppressed.add(t);
                logger.debug("Error checking if {} is on a file store mounted with noexec", tmpFile, t);
            }
            // Re-throw to fail the load
            ThrowableUtil.addSuppressedAndClear(e, suppressed);
            throw e;
        } catch (Exception e) {
            UnsatisfiedLinkError ule = new UnsatisfiedLinkError("could not load a native library: " + name);
            ule.initCause(e);
            ThrowableUtil.addSuppressedAndClear(ule, suppressed);
            throw ule;
        } finally {
            closeQuietly(in);
            closeQuietly(out);
            // After we load the library it is safe to delete the file.
            // We delete the file immediately to free up resources as soon as possible,
            // and if this fails fallback to deleting on JVM exit.
            if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) {
                tmpFile.deleteOnExit();
            }
        }
    }
904885
private void addJobJarToClassPath(String localJarFile, StringBuffer classPath) {
    File jobCacheDir = new File
      (new Path(localJarFile).getParent().toString());
    File[] libs = new File(jobCacheDir, "lib").listFiles();
    String sep = System.getProperty("path.separator");

    if (libs != null) {
      for (int i = 0; i < libs.length; i++) {
        classPath.append(sep); // add libs from jar to classpath
        classPath.append(libs[i]);
      }
    }
    classPath.append(sep);
    classPath.append(new File(jobCacheDir, "classes"));
    classPath.append(sep);
    classPath.append(jobCacheDir);
  }
1107007
protected void addClassPathes(final GroovyClassLoader classLoader) {
        if (classpath != null) {
            for (int i = 0; i < classpath.list().length; i++) {
                classLoader.addClasspath(classpath.list()[i]);
            }
        }
    }
1318945
public void addFile(File file) {
        if (file != null && file.exists()) {
            try {
                classPath.add(file.toURI().toURL());
            } catch (MalformedURLException e) {
                throw new AssertionError("converting an existing file to an url should have never thrown an exception!");
            }
        }
    }
308826
URLClassLoader createUrlClassLoader(
            final List<String> classpathElements,
            final ClassLoader contextClassLoader)
            throws MojoExecutionException {
        try {
            final URL[] urls = new URL[classpathElements.size()];
            int i = 0;
            for (final String classpathElement : classpathElements) {
                urls[i++] = new File(classpathElement).toURI().toURL();
            }
            return URLClassLoader.newInstance(urls, contextClassLoader);
        } catch (final MalformedURLException e) {
            throw new MojoExecutionException("Unable to instantiate class loader", e);
        }
    }
868295
public void setClassLoader(GroovyClassLoader loader) {
        ClassLoader parent = Thread.currentThread().getContextClassLoader();
        if (parent == null) parent = ProcessingUnit.class.getClassLoader();
        this.classLoader = (loader == null ? new GroovyClassLoader(parent, configuration) : loader);
    }