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;
36 import org.slf4j.ext.XLogger;
37 import org.slf4j.ext.XLoggerFactory;
40 * This class is a utility class used to find Java classes on the class path, in directories, and in Jar files.
42 * @author Liam Fallon (liam.fallon@ericsson.com)
44 public abstract class ClassUtils {
45 // Get a reference to the logger
46 private static final XLogger LOGGER = XLoggerFactory.getXLogger(ClassUtils.class);
48 // Repeated string constants
49 private static final String CLASS_PATTERN = "\\.class$";
51 // The boot directory in Java for predefined JARs
52 private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
54 // Token for Classes directory in paths
55 private static final String CLASSES_TOKEN = "/classes/";
57 // Token for library fragment in path
58 private static final String LIBRARAY_PATH_TOKEN = "/lib";
61 * Private constructor used to prevent sub class instantiation.
63 private ClassUtils() {
64 // Private constructor to block subclassing
68 * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
70 * @return a set of class names for all classes in the class path
72 public static Set<String> getClassNames() {
73 // The return set of class names
74 final Set<String> classNameSet = new TreeSet<>();
77 // The library path for predefined classes in Java
78 String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
80 // Check it exists and has a "lib" in it
81 if (sunBootLibraryPathString != null && sunBootLibraryPathString.contains(LIBRARAY_PATH_TOKEN)) {
82 // Strip any superfluous trailer from path
83 sunBootLibraryPathString = sunBootLibraryPathString.substring(0,
84 sunBootLibraryPathString.lastIndexOf(LIBRARAY_PATH_TOKEN) + LIBRARAY_PATH_TOKEN.length());
86 final File bootLibraryFile = new File(sunBootLibraryPathString);
87 // The set used to hold class names is populated with predefined Java classes
88 classNameSet.addAll(processDir(bootLibraryFile, ""));
91 // Get the entries on the class path
92 URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
94 // Try get the classes in the bootstrap loader
96 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
97 if (nullclassloader != null) {
98 Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
99 if (mmethod != null) {
100 final Object cp = mmethod.invoke(null, (Object[]) null);
102 mmethod = cp.getClass().getMethod("getURLs");
103 if (mmethod != null) {
104 final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
105 if (moreurls != null && moreurls.length > 0) {
106 if (urls.length == 0) {
109 final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
110 System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
119 } catch (final ClassNotFoundException e) {
120 LOGGER.warn("Failed to find default path for JRE libraries", e);
123 // Iterate over the class path entries
124 for (final URL url : urls) {
125 if (url == null || url.getFile() == null) {
128 final File urlFile = new File(url.getFile());
129 // Directories may contain ".class" files
130 if (urlFile.isDirectory()) {
131 classNameSet.addAll(processDir(urlFile, url.getFile()));
133 // JARs are processed as well
134 else if (url.getFile().endsWith(".jar")) {
135 classNameSet.addAll(processJar(urlFile));
137 // It's a resource or some other non-executable thing
139 } catch (final Exception e) {
140 LOGGER.warn("could not get the names of Java classes", e);
147 * Find all classes in directories and JARs in those directories.
149 * @param classDirectory The directory to search for classes
150 * @param rootDir The root directory, to be removed from absolute paths
151 * @return a set of classes which may be empty
152 * @throws Exception on errors processing directories
154 public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
156 final TreeSet<String> classNameSet = new TreeSet<>();
158 // Iterate over the directory
159 if (classDirectory == null || !classDirectory.isDirectory()) {
162 for (final File child : classDirectory.listFiles()) {
163 if (child.isDirectory()) {
165 classNameSet.addAll(processDir(child, rootDir));
166 } else if (child.getName().endsWith(".jar")) {
168 classNameSet.addAll(processJar(child));
169 } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
170 // Process the ".class" file
172 child.getAbsolutePath().replace(rootDir, "").replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
179 * Condition the file name as a class name.
181 * @param fileNameIn The file name to convert to a class name
182 * @return the conditioned class name
184 public static String processFileName(final String fileNameIn) {
185 String fileName = fileNameIn;
187 if (fileName == null) {
190 final int classesPos = fileName.indexOf(CLASSES_TOKEN);
192 if (classesPos != -1) {
193 fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
196 return fileName.replaceFirst(CLASS_PATTERN, "").replace('/', '.');
200 * Read all the class names from a Jar.
202 * @param jarFile the JAR file
203 * @return a set of class names
204 * @throws IOException on errors processing JARs
206 public static Set<String> processJar(final File jarFile) throws IOException {
207 // Pass the file as an input stream
208 return processJar(new FileInputStream(jarFile.getAbsolutePath()));
212 * Read all the class names from a Jar.
214 * @param jarInputStream the JAR input stream
215 * @return a set of class names
216 * @throws IOException on errors processing JARs
218 public static Set<String> processJar(final InputStream jarInputStream) throws IOException {
220 final TreeSet<String> classPathSet = new TreeSet<>();
222 if (jarInputStream == null) {
225 // JARs are ZIP files
226 final ZipInputStream zip = new ZipInputStream(jarInputStream);
228 // Iterate over each entry in the JAR
229 for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
230 if (!entry.isDirectory() && entry.getName().endsWith(".class") && !entry.getName().contains("$")) {
231 classPathSet.add(entry.getName().replaceFirst(CLASS_PATTERN, "").replace('/', '.'));
239 * The main method exercises this class for test purposes.
241 * @param args the args
243 public static void main(final String[] args) {
244 for (final String clz : getClassNames()) {
245 LOGGER.info("Found class: {}", clz);