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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.core.infrastructure.java.classes;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.lang.reflect.Method;
29 import java.net.URLClassLoader;
30 import java.util.Arrays;
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;
39 * This class is a utility class used to find Java classes on the class path, in directories, and in Jar files.
41 * @author Liam Fallon (liam.fallon@ericsson.com)
43 public abstract class ClassUtils {
44 // Get a reference to the logger
45 private static final XLogger LOGGER = XLoggerFactory.getXLogger(ClassUtils.class);
47 // Repeated string constants
48 private static final String CLASS_PATTERN = "\\.class$";
50 // The boot directory in Java for predefined JARs
51 private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
53 // Token for Classes directory in paths
54 private static final String CLASSES_TOKEN = "/classes/";
56 // Token for library fragment in path
57 private static final String LIBRARAY_PATH_TOKEN = "/lib";
60 * Private constructor used to prevent sub class instantiation.
62 private ClassUtils() {
63 // Private constructor to block subclassing
67 * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
69 * @return a set of class names for all classes in the class path
71 public static Set<String> getClassNames() {
72 // The return set of class names
73 final Set<String> classNameSet = new TreeSet<>();
76 // The library path for predefined classes in Java
77 String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
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());
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, ""));
90 // Get the entries on the class path
91 URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
93 // Try get the classes in the bootstrap loader
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);
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) {
108 final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
109 System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
118 } catch (final ClassNotFoundException e) {
119 LOGGER.warn("Failed to find default path for JRE libraries", e);
122 // Iterate over the class path entries
123 for (final URL url : urls) {
124 if (url == null || url.getFile() == null) {
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));
135 // It's a resource or some other non-executable thing
137 } catch (final Exception e) {
138 LOGGER.warn("could not get the names of Java classes", e);
145 * Find all classes in directories and JARs in those directories.
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
152 public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
154 final TreeSet<String> classNameSet = new TreeSet<>();
156 // Iterate over the directory
157 if (classDirectory == null || !classDirectory.isDirectory()) {
160 for (final File child : classDirectory.listFiles()) {
161 if (child.isDirectory()) {
163 classNameSet.addAll(processDir(child, rootDir));
164 } else if (child.getName().endsWith(".jar")) {
166 classNameSet.addAll(processJar(child));
167 } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
168 // Process the ".class" file
170 child.getAbsolutePath().replace(rootDir, "").replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
177 * Condition the file name as a class name.
179 * @param fileNameIn The file name to convert to a class name
180 * @return the conditioned class name
182 public static String processFileName(final String fileNameIn) {
183 String fileName = fileNameIn;
185 if (fileName == null) {
188 final int classesPos = fileName.indexOf(CLASSES_TOKEN);
190 if (classesPos != -1) {
191 fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
194 return fileName.replaceFirst(CLASS_PATTERN, "").replace('/', '.');
198 * Read all the class names from a Jar.
200 * @param jarFile the JAR file
201 * @return a set of class names
202 * @throws IOException on errors processing JARs
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()));
210 * Read all the class names from a Jar.
212 * @param jarInputStream the JAR input stream
213 * @return a set of class names
214 * @throws IOException on errors processing JARs
216 public static Set<String> processJar(final InputStream jarInputStream) throws IOException {
218 final TreeSet<String> classPathSet = new TreeSet<>();
220 if (jarInputStream == null) {
223 // JARs are ZIP files
224 final ZipInputStream zip = new ZipInputStream(jarInputStream);
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('/', '.'));
237 * The main method exercises this class for test purposes.
239 * @param args the args
241 public static void main(final String[] args) {
242 for (final String clz : getClassNames()) {
243 LOGGER.info("Found class: {}", clz);