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