1 package eu.svjatoslav.inspector.java;
3 import eu.svjatoslav.inspector.java.structure.ClassGraph;
6 import java.io.FileInputStream;
7 import java.io.IOException;
8 import java.net.MalformedURLException;
10 import java.net.URLClassLoader;
11 import java.util.ArrayList;
12 import java.util.List;
13 import java.util.jar.JarEntry;
14 import java.util.jar.JarInputStream;
16 import static java.io.File.separator;
17 import static java.lang.System.getProperty;
20 * This class acts as a commandline interface for JavaInspect.
23 public static void main(String[] args) throws IOException, ClassNotFoundException {
24 CommandlineConfiguration configuration = new CommandlineConfiguration(args);
26 List<File> jarFiles = configuration.jarFiles.getValue();
28 URLClassLoader classLoader = new URLClassLoader(
29 getFileUrls(jarFiles),
30 configuration.getClass().getClassLoader());
32 ClassGraph classGraph = new ClassGraph();
33 classGraph.setTargetDirectoryPath(getProperty("user.dir") + separator);
34 classGraph.setKeepDotFile(true);
36 for (File jarFile : jarFiles)
37 addJarToGraph(jarFile, classLoader, classGraph, configuration);
39 classGraph.generateGraph(configuration.graphName.getValue());
41 if (configuration.isDebug())
42 System.out.println("Graph ready.");
45 private static URL[] getFileUrls(List<File> jarFiles) {
46 List<URL> urls = new ArrayList<>();
47 jarFiles.forEach((File file) -> {
49 urls.add(file.toURI().toURL());
50 } catch (MalformedURLException e) {
51 throw new RuntimeException(e);
55 return urls.toArray(new URL[urls.size()]);
58 private static void addJarToGraph(
59 File jarFile, URLClassLoader classLoader, ClassGraph classGraph, CommandlineConfiguration configuration)
60 throws IOException, ClassNotFoundException {
62 for (String className : getClassNamesFromJar(jarFile)) {
63 if (configuration.isDebug())
64 System.out.println("Adding class to graph: " + className);
66 classGraph.add(loadClassByName(classLoader, className));
70 private static Class loadClassByName(URLClassLoader classLoader, String className) throws ClassNotFoundException {
71 return Class.forName(className, true, classLoader);
74 public static List<String> getClassNamesFromJar(File jarFile) throws IOException {
75 List<String> result = new ArrayList<>();
77 JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile))
80 JarEntry jarEntry = jarInputStream.getNextJarEntry();
84 if (isClassFile(jarEntry))
85 result.add(getClassNameFromFileName(jarEntry));
92 private static boolean isClassFile(JarEntry jarEntry) {
93 return jarEntry.getName().endsWith(".class");
96 private static String getClassNameFromFileName(JarEntry jarEntry) {
97 String result = jarEntry.getName().replaceAll("/", "\\.");
98 return result.substring(0, result.lastIndexOf('.'));