16a3369fbd1900e999d724ed4bde99b54d927233
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.core.infrastructure.java.classes;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.lang.reflect.Method;
28 import java.net.URL;
29 import java.net.URLClassLoader;
30 import java.util.Arrays;
31 import java.util.Set;
32 import java.util.TreeSet;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipInputStream;
35
36 import org.slf4j.ext.XLogger;
37 import org.slf4j.ext.XLoggerFactory;
38
39 /**
40  * This class is a utility class used to find Java classes on the class path, in directories, and in Jar files.
41  *
42  * @author Liam Fallon (liam.fallon@ericsson.com)
43  */
44 public abstract class ClassUtils {
45     // Get a reference to the logger
46     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ClassUtils.class);
47
48     // Repeated string constants
49     private static final String CLASS_PATTERN = "\\.class$";
50
51     // The boot directory in Java for predefined JARs
52     private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
53
54     // Token for Classes directory in paths
55     private static final String CLASSES_TOKEN = "/classes/";
56
57     // Token for library fragment in path
58     private static final String LIBRARAY_PATH_TOKEN = "/lib";
59
60     /**
61      * Private constructor used to prevent sub class instantiation.
62      */
63     private ClassUtils() {}
64
65     /**
66      * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
67      *
68      * @return a set of class names for all classes in the class path
69      */
70     public static Set<String> getClassNames() {
71         // The return set of class names
72         final Set<String> classNameSet = new TreeSet<>();
73
74         try {
75             // The library path for predefined classes in Java
76             String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
77
78             // Check it exists and has a "lib" in it
79             if (sunBootLibraryPathString != null && sunBootLibraryPathString.contains(LIBRARAY_PATH_TOKEN)) {
80                 // Strip any superfluous trailer from path
81                 sunBootLibraryPathString = sunBootLibraryPathString.substring(0,
82                         sunBootLibraryPathString.lastIndexOf(LIBRARAY_PATH_TOKEN) + LIBRARAY_PATH_TOKEN.length());
83
84                 final File bootLibraryFile = new File(sunBootLibraryPathString);
85                 // The set used to hold class names is populated with predefined Java classes
86                 classNameSet.addAll(processDir(bootLibraryFile, ""));
87             }
88
89             // Get the entries on the class path
90             URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
91
92             // Try get the classes in the bootstrap loader
93             try {
94                 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
95                 if (nullclassloader != null) {
96                     Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
97                     if (mmethod != null) {
98                         final Object cp = mmethod.invoke(null, (Object[]) null);
99                         if (cp != null) {
100                             mmethod = cp.getClass().getMethod("getURLs");
101                             if (mmethod != null) {
102                                 final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
103                                 if (moreurls != null && moreurls.length > 0) {
104                                     if (urls.length == 0) {
105                                         urls = moreurls;
106                                     } else {
107                                         final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
108                                         System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
109                                         urls = result;
110                                     }
111                                 }
112                             }
113                         }
114                     }
115                     // end long way!
116                 }
117             } catch (final ClassNotFoundException e) {
118                 LOGGER.warn("Failed to find default path for JRE libraries", e);
119             }
120
121             // Iterate over the class path entries
122             for (final URL url : urls) {
123                 if (url == null || url.getFile() == null) {
124                     continue;
125                 }
126                 final File urlFile = new File(url.getFile());
127                 // Directories may contain ".class" files
128                 if (urlFile.isDirectory()) {
129                     classNameSet.addAll(processDir(urlFile, url.getFile()));
130                 }
131                 // JARs are processed as well
132                 else if (url.getFile().endsWith(".jar")) {
133                     classNameSet.addAll(processJar(urlFile));
134                 }
135                 // It's a resource or some other non-executable thing
136             }
137         } catch (final Exception e) {
138             LOGGER.warn("could not get the names of Java classes", e);
139         }
140
141         return classNameSet;
142     }
143
144     /**
145      * Find all classes in directories and JARs in those directories.
146      *
147      * @param classDirectory The directory to search for classes
148      * @param rootDir The root directory, to be removed from absolute paths
149      * @return a set of classes which may be empty
150      * @throws Exception on errors processing directories
151      */
152     public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
153         // The return set
154         final TreeSet<String> classNameSet = new TreeSet<>();
155
156         // Iterate over the directory
157         if (classDirectory == null || !classDirectory.isDirectory()) {
158             return classNameSet;
159         }
160         for (final File child : classDirectory.listFiles()) {
161             if (child.isDirectory()) {
162                 // Recurse down
163                 classNameSet.addAll(processDir(child, rootDir));
164             } else if (child.getName().endsWith(".jar")) {
165                 // Process the JAR
166                 classNameSet.addAll(processJar(child));
167             } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
168                 // Process the ".class" file
169                 classNameSet.add(
170                         child.getAbsolutePath().replace(rootDir, "").replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
171             }
172         }
173         return classNameSet;
174     }
175
176     /**
177      * Condition the file name as a class name.
178      *
179      * @param fileNameIn The file name to convert to a class name
180      * @return the conditioned class name
181      */
182     public static String processFileName(final String fileNameIn) {
183         String fileName = fileNameIn;
184
185         if (fileName == null) {
186             return null;
187         }
188         final int classesPos = fileName.indexOf(CLASSES_TOKEN);
189
190         if (classesPos != -1) {
191             fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
192         }
193
194         return fileName.replaceFirst(CLASS_PATTERN, "").replace('/', '.');
195     }
196
197     /**
198      * Read all the class names from a Jar.
199      *
200      * @param jarFile the JAR file
201      * @return a set of class names
202      * @throws IOException on errors processing JARs
203      */
204     public static Set<String> processJar(final File jarFile) throws IOException {
205         // Pass the file as an input stream
206         return processJar(new FileInputStream(jarFile.getAbsolutePath()));
207     }
208
209     /**
210      * Read all the class names from a Jar.
211      *
212      * @param jarInputStream the JAR input stream
213      * @return a set of class names
214      * @throws IOException on errors processing JARs
215      */
216     public static Set<String> processJar(final InputStream jarInputStream) throws IOException {
217         // The return set
218         final TreeSet<String> classPathSet = new TreeSet<>();
219
220         if (jarInputStream == null) {
221             return classPathSet;
222         }
223         // JARs are ZIP files
224         final ZipInputStream zip = new ZipInputStream(jarInputStream);
225
226         // Iterate over each entry in the JAR
227         for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
228             if (!entry.isDirectory() && entry.getName().endsWith(".class") && !entry.getName().contains("$")) {
229                 classPathSet.add(entry.getName().replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
230             }
231         }
232         zip.close();
233         return classPathSet;
234     }
235
236     /**
237      * The main method exercises this class for test purposes.
238      *
239      * @param args the args
240      */
241     public static void main(final String[] args) {
242         for (final String clz : getClassNames()) {
243             LOGGER.info("Found class: {}", clz);
244         }
245     }
246 }