com.seeq.link.agent.ClassPathUtilities Maven / Gradle / Ivy
package com.seeq.link.agent;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import lombok.experimental.UtilityClass;
@UtilityClass
public class ClassPathUtilities {
/**
* Adds a URL to an existing classloader.
*
* Taken from http://stackoverflow.com/questions/7884393/can-a-directory-be-added-to-the-class-path-at-runtime
*
* @param urlClassLoader
* classloader to affect
* @param url
* url of classpath to be added
* @throws Exception
* various exceptions can occur
*/
public static void addToClassPath(URLClassLoader urlClassLoader, URL url) throws Exception {
Class urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(urlClassLoader, url);
}
public static List getJarsInFolder(File folder) throws Exception {
File[] jars = folder.listFiles((FilenameFilter) new SuffixFileFilter(".jar"));
List urls = new ArrayList<>();
for (File jar : jars) {
urls.add(jar.toURI().toURL());
}
return urls;
}
public static List getEntriesFromClasspathFile(File classPathFile,
BiFunction entryResolver)
throws Exception {
List urls = new ArrayList<>();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(classPathFile);
doc.getDocumentElement().normalize();
NodeList classpathNodes = doc.getElementsByTagName("classpathentry");
for (int i = 0; i < classpathNodes.getLength(); i++) {
Node classpathNode = classpathNodes.item(i);
NamedNodeMap classpathAttributes = classpathNode.getAttributes();
String kind = classpathAttributes.getNamedItem("kind").getNodeValue();
String path = classpathAttributes.getNamedItem("path").getNodeValue();
String classPathEntry = entryResolver.apply(kind, path);
if (classPathEntry != null) {
urls.add(new File(classPathEntry).toURI().toURL());
}
}
return urls;
}
}