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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.core.infrastructure.java.classes;
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;
31 import java.net.URLClassLoader;
32 import java.util.Arrays;
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;
41 * This class is a utility class used to find Java classes on the class path, in directories, and in Jar files.
43 * @author Liam Fallon (liam.fallon@ericsson.com)
45 public abstract class ClassUtils {
46 // Get a reference to the logger
47 private static final XLogger LOGGER = XLoggerFactory.getXLogger(ClassUtils.class);
49 // Repeated string constants
50 private static final String CLASS_PATTERN = "\\.class$";
52 // The boot directory in Java for predefined JARs
53 private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
55 // Token for Classes directory in paths
56 private static final String CLASSES_TOKEN = "/classes/";
58 // Token for library fragment in path
59 private static final String LIBRARAY_PATH_TOKEN = "/lib";
62 * Private constructor used to prevent sub class instantiation.
64 private ClassUtils() {
65 // Private constructor to block subclassing
69 * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
71 * @return a set of class names for all classes in the class path
73 public static Set<String> getClassNames() {
74 // The return set of class names
75 final Set<String> classNameSet = new TreeSet<>();
78 // The library path for predefined classes in Java
79 String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
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());
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, ""));
92 // Get the entries on the class path
93 URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
95 // Try get the classes in the bootstrap loader
96 urls = getClassesFromBootstrapLoader(urls);
98 // Iterate over the class path entries
99 for (final URL url : urls) {
100 if (url == null || url.getFile() == null) {
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));
111 // It's a resource or some other non-executable thing
113 } catch (final Exception e) {
114 LOGGER.warn("could not get the names of Java classes", e);
120 private static URL[] getClassesFromBootstrapLoader(URL[] urls)
121 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
123 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
124 if (nullclassloader == null) {
128 Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
129 if (mmethod == null) {
133 final Object cp = mmethod.invoke(null, (Object[]) null);
138 mmethod = cp.getClass().getMethod("getURLs");
139 if (mmethod == null) {
143 final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
144 if (moreurls == null || moreurls.length == 0) {
148 if (urls.length == 0) {
151 final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
152 System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
155 } catch (final ClassNotFoundException e) {
156 LOGGER.warn("Failed to find default path for JRE libraries", e);
162 * Find all classes in directories and JARs in those directories.
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
169 public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
171 final TreeSet<String> classNameSet = new TreeSet<>();
173 // Iterate over the directory
174 if (classDirectory == null || !classDirectory.isDirectory()) {
177 for (final File child : classDirectory.listFiles()) {
178 if (child.isDirectory()) {
180 classNameSet.addAll(processDir(child, rootDir));
181 } else if (child.getName().endsWith(".jar")) {
183 classNameSet.addAll(processJar(child));
184 } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
185 // Process the ".class" file
187 child.getAbsolutePath().replace(rootDir, "").replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
194 * Condition the file name as a class name.
196 * @param fileNameIn The file name to convert to a class name
197 * @return the conditioned class name
199 public static String processFileName(final String fileNameIn) {
200 String fileName = fileNameIn;
202 if (fileName == null) {
205 final int classesPos = fileName.indexOf(CLASSES_TOKEN);
207 if (classesPos != -1) {
208 fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
211 return fileName.replaceFirst(CLASS_PATTERN, "").replace('/', '.');
215 * Read all the class names from a Jar.
217 * @param jarFile the JAR file
218 * @return a set of class names
219 * @throws IOException on errors processing JARs
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()));
227 * Read all the class names from a Jar.
229 * @param jarInputStream the JAR input stream
230 * @return a set of class names
231 * @throws IOException on errors processing JARs
233 public static Set<String> processJar(final InputStream jarInputStream) throws IOException {
235 final TreeSet<String> classPathSet = new TreeSet<>();
237 if (jarInputStream == null) {
240 // JARs are ZIP files
241 final ZipInputStream zip = new ZipInputStream(jarInputStream);
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('/', '.'));
254 * The main method exercises this class for test purposes.
256 * @param args the args
258 public static void main(final String[] args) {
259 for (final String clz : getClassNames()) {
260 LOGGER.info("Found class: {}", clz);