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