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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.apex.core.infrastructure.java.classes;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.lang.reflect.InvocationTargetException;
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 lombok.AccessLevel;
38 import lombok.NoArgsConstructor;
39 import org.slf4j.ext.XLogger;
40 import org.slf4j.ext.XLoggerFactory;
43 * This class is a utility class used to find Java classes on the class path, in directories, and in Jar files.
45 * @author Liam Fallon (liam.fallon@ericsson.com)
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);
52 // Repeated string constants
53 private static final String CLASS_PATTERN = "\\.class$";
55 // The boot directory in Java for predefined JARs
56 private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
58 // Token for Classes directory in paths
59 private static final String CLASSES_TOKEN = "/classes/";
61 // Token for library fragment in path
62 private static final String LIBRARAY_PATH_TOKEN = "/lib";
65 * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
67 * @return a set of class names for all classes in the class path
69 public static Set<String> getClassNames() {
70 // The return set of class names
71 final Set<String> classNameSet = new TreeSet<>();
74 // The library path for predefined classes in Java
75 var sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
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());
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, ""));
88 // Get the entries on the class path
89 URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
91 // Try get the classes in the bootstrap loader
92 urls = getClassesFromBootstrapLoader(urls);
94 // Iterate over the class path entries
95 for (final URL url : urls) {
96 if (url == null || url.getFile() == null) {
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));
107 // It's a resource or some other non-executable thing
109 } catch (final Exception e) {
110 LOGGER.warn("could not get the names of Java classes", e);
116 private static URL[] getClassesFromBootstrapLoader(URL[] urls)
117 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
119 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
120 if (nullclassloader == null) {
124 var mmethod = nullclassloader.getMethod("getBootstrapClassPath");
125 if (mmethod == null) {
129 final Object cp = mmethod.invoke(null, (Object[]) null);
134 mmethod = cp.getClass().getMethod("getURLs");
135 if (mmethod == null) {
139 final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
140 if (moreurls == null || moreurls.length == 0) {
144 if (urls.length == 0) {
147 final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
148 System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
151 } catch (final ClassNotFoundException e) {
152 LOGGER.warn("Failed to find default path for JRE libraries", e);
158 * Find all classes in directories and JARs in those directories.
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
165 public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
167 final TreeSet<String> classNameSet = new TreeSet<>();
169 // Iterate over the directory
170 if (classDirectory == null || !classDirectory.isDirectory()) {
173 for (final File child : classDirectory.listFiles()) {
174 if (child.isDirectory()) {
176 classNameSet.addAll(processDir(child, rootDir));
177 } else if (child.getName().endsWith(".jar")) {
179 classNameSet.addAll(processJar(child));
180 } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
181 // Process the ".class" file
183 child.getAbsolutePath().replace(rootDir, "").replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
190 * Condition the file name as a class name.
192 * @param fileNameIn The file name to convert to a class name
193 * @return the conditioned class name
195 public static String processFileName(final String fileNameIn) {
196 String fileName = fileNameIn;
198 if (fileName == null) {
201 final int classesPos = fileName.indexOf(CLASSES_TOKEN);
203 if (classesPos != -1) {
204 fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
207 return fileName.replaceFirst(CLASS_PATTERN, "").replace('/', '.');
211 * Read all the class names from a Jar.
213 * @param jarFile the JAR file
214 * @return a set of class names
215 * @throws IOException on errors processing JARs
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()));
223 * Read all the class names from a Jar.
225 * @param jarInputStream the JAR input stream
226 * @return a set of class names
227 * @throws IOException on errors processing JARs
229 public static Set<String> processJar(final InputStream jarInputStream) throws IOException {
231 final TreeSet<String> classPathSet = new TreeSet<>();
233 if (jarInputStream == null) {
236 // JARs are ZIP files
237 final var zip = new ZipInputStream(jarInputStream);
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('/', '.'));
250 * The main method exercises this class for test purposes.
252 * @param args the args
254 public static void main(final String[] args) {
255 for (final String clz : getClassNames()) {
256 LOGGER.info("Found class: {}", clz);