Changes for checkstyle 8.32
[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 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     // Repeated string constants
48     private static final String CLASS_PATTERN = "\\.class$";
49
50     // The boot directory in Java for predefined JARs
51     private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
52
53     // Token for Classes directory in paths
54     private static final String CLASSES_TOKEN = "/classes/";
55
56     // Token for library fragment in path
57     private static final String LIBRARAY_PATH_TOKEN = "/lib";
58
59     /**
60      * Private constructor used to prevent sub class instantiation.
61      */
62     private ClassUtils() {
63         // Private constructor to block subclassing
64     }
65
66     /**
67      * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
68      *
69      * @return a set of class names for all classes in the class path
70      */
71     public static Set<String> getClassNames() {
72         // The return set of class names
73         final Set<String> classNameSet = new TreeSet<>();
74
75         try {
76             // The library path for predefined classes in Java
77             String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
78
79             // Check it exists and has a "lib" in it
80             if (sunBootLibraryPathString != null && sunBootLibraryPathString.contains(LIBRARAY_PATH_TOKEN)) {
81                 // Strip any superfluous trailer from path
82                 sunBootLibraryPathString = sunBootLibraryPathString.substring(0,
83                         sunBootLibraryPathString.lastIndexOf(LIBRARAY_PATH_TOKEN) + LIBRARAY_PATH_TOKEN.length());
84
85                 final File bootLibraryFile = new File(sunBootLibraryPathString);
86                 // The set used to hold class names is populated with predefined Java classes
87                 classNameSet.addAll(processDir(bootLibraryFile, ""));
88             }
89
90             // Get the entries on the class path
91             URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
92
93             // Try get the classes in the bootstrap loader
94             try {
95                 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
96                 if (nullclassloader != null) {
97                     Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
98                     if (mmethod != null) {
99                         final Object cp = mmethod.invoke(null, (Object[]) null);
100                         if (cp != null) {
101                             mmethod = cp.getClass().getMethod("getURLs");
102                             if (mmethod != null) {
103                                 final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
104                                 if (moreurls != null && moreurls.length > 0) {
105                                     if (urls.length == 0) {
106                                         urls = moreurls;
107                                     } else {
108                                         final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
109                                         System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
110                                         urls = result;
111                                     }
112                                 }
113                             }
114                         }
115                     }
116                     // end long way!
117                 }
118             } catch (final ClassNotFoundException e) {
119                 LOGGER.warn("Failed to find default path for JRE libraries", e);
120             }
121
122             // Iterate over the class path entries
123             for (final URL url : urls) {
124                 if (url == null || url.getFile() == null) {
125                     continue;
126                 }
127                 final File urlFile = new File(url.getFile());
128                 // Directories may contain ".class" files
129                 if (urlFile.isDirectory()) {
130                     classNameSet.addAll(processDir(urlFile, url.getFile()));
131                 } else if (url.getFile().endsWith(".jar")) {
132                     // JARs are processed as well
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 }