6da92d55ebfd19d7ca6b4d85109efe32f4dd21b0
[policy/apex-pdp.git] / core / core-infrastructure / src / main / java / org / onap / policy / apex / core / infrastructure / java / classes / ClassUtils.java
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         // Private constructor to block subclassing
65     }
66
67     /**
68      * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
69      *
70      * @return a set of class names for all classes in the class path
71      */
72     public static Set<String> getClassNames() {
73         // The return set of class names
74         final Set<String> classNameSet = new TreeSet<>();
75
76         try {
77             // The library path for predefined classes in Java
78             String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
79
80             // Check it exists and has a "lib" in it
81             if (sunBootLibraryPathString != null && sunBootLibraryPathString.contains(LIBRARAY_PATH_TOKEN)) {
82                 // Strip any superfluous trailer from path
83                 sunBootLibraryPathString = sunBootLibraryPathString.substring(0,
84                         sunBootLibraryPathString.lastIndexOf(LIBRARAY_PATH_TOKEN) + LIBRARAY_PATH_TOKEN.length());
85
86                 final File bootLibraryFile = new File(sunBootLibraryPathString);
87                 // The set used to hold class names is populated with predefined Java classes
88                 classNameSet.addAll(processDir(bootLibraryFile, ""));
89             }
90
91             // Get the entries on the class path
92             URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
93
94             // Try get the classes in the bootstrap loader
95             try {
96                 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
97                 if (nullclassloader != null) {
98                     Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
99                     if (mmethod != null) {
100                         final Object cp = mmethod.invoke(null, (Object[]) null);
101                         if (cp != null) {
102                             mmethod = cp.getClass().getMethod("getURLs");
103                             if (mmethod != null) {
104                                 final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
105                                 if (moreurls != null && moreurls.length > 0) {
106                                     if (urls.length == 0) {
107                                         urls = moreurls;
108                                     } else {
109                                         final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
110                                         System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
111                                         urls = result;
112                                     }
113                                 }
114                             }
115                         }
116                     }
117                     // end long way!
118                 }
119             } catch (final ClassNotFoundException e) {
120                 LOGGER.warn("Failed to find default path for JRE libraries", e);
121             }
122
123             // Iterate over the class path entries
124             for (final URL url : urls) {
125                 if (url == null || url.getFile() == null) {
126                     continue;
127                 }
128                 final File urlFile = new File(url.getFile());
129                 // Directories may contain ".class" files
130                 if (urlFile.isDirectory()) {
131                     classNameSet.addAll(processDir(urlFile, url.getFile()));
132                 }
133                 // JARs are processed as well
134                 else if (url.getFile().endsWith(".jar")) {
135                     classNameSet.addAll(processJar(urlFile));
136                 }
137                 // It's a resource or some other non-executable thing
138             }
139         } catch (final Exception e) {
140             LOGGER.warn("could not get the names of Java classes", e);
141         }
142
143         return classNameSet;
144     }
145
146     /**
147      * Find all classes in directories and JARs in those directories.
148      *
149      * @param classDirectory The directory to search for classes
150      * @param rootDir The root directory, to be removed from absolute paths
151      * @return a set of classes which may be empty
152      * @throws Exception on errors processing directories
153      */
154     public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
155         // The return set
156         final TreeSet<String> classNameSet = new TreeSet<>();
157
158         // Iterate over the directory
159         if (classDirectory == null || !classDirectory.isDirectory()) {
160             return classNameSet;
161         }
162         for (final File child : classDirectory.listFiles()) {
163             if (child.isDirectory()) {
164                 // Recurse down
165                 classNameSet.addAll(processDir(child, rootDir));
166             } else if (child.getName().endsWith(".jar")) {
167                 // Process the JAR
168                 classNameSet.addAll(processJar(child));
169             } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
170                 // Process the ".class" file
171                 classNameSet.add(
172                         child.getAbsolutePath().replace(rootDir, "").replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
173             }
174         }
175         return classNameSet;
176     }
177
178     /**
179      * Condition the file name as a class name.
180      *
181      * @param fileNameIn The file name to convert to a class name
182      * @return the conditioned class name
183      */
184     public static String processFileName(final String fileNameIn) {
185         String fileName = fileNameIn;
186
187         if (fileName == null) {
188             return null;
189         }
190         final int classesPos = fileName.indexOf(CLASSES_TOKEN);
191
192         if (classesPos != -1) {
193             fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
194         }
195
196         return fileName.replaceFirst(CLASS_PATTERN, "").replace('/', '.');
197     }
198
199     /**
200      * Read all the class names from a Jar.
201      *
202      * @param jarFile the JAR file
203      * @return a set of class names
204      * @throws IOException on errors processing JARs
205      */
206     public static Set<String> processJar(final File jarFile) throws IOException {
207         // Pass the file as an input stream
208         return processJar(new FileInputStream(jarFile.getAbsolutePath()));
209     }
210
211     /**
212      * Read all the class names from a Jar.
213      *
214      * @param jarInputStream the JAR input stream
215      * @return a set of class names
216      * @throws IOException on errors processing JARs
217      */
218     public static Set<String> processJar(final InputStream jarInputStream) throws IOException {
219         // The return set
220         final TreeSet<String> classPathSet = new TreeSet<>();
221
222         if (jarInputStream == null) {
223             return classPathSet;
224         }
225         // JARs are ZIP files
226         final ZipInputStream zip = new ZipInputStream(jarInputStream);
227
228         // Iterate over each entry in the JAR
229         for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
230             if (!entry.isDirectory() && entry.getName().endsWith(".class") && !entry.getName().contains("$")) {
231                 classPathSet.add(entry.getName().replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
232             }
233         }
234         zip.close();
235         return classPathSet;
236     }
237
238     /**
239      * The main method exercises this class for test purposes.
240      *
241      * @param args the args
242      */
243     public static void main(final String[] args) {
244         for (final String clz : getClassNames()) {
245             LOGGER.info("Found class: {}", clz);
246         }
247     }
248 }