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