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.InputStream;
26 import java.lang.reflect.Method;
28 import java.net.URLClassLoader;
29 import java.util.Arrays;
31 import java.util.TreeSet;
32 import java.util.zip.ZipEntry;
33 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 // The boot directory in Java for predefined JARs
48 private static final String SUN_BOOT_LIBRARY_PATH = "sun.boot.library.path";
50 // Token for Classes directory in paths
51 private static final String CLASSES_TOKEN = "/classes/";
53 // Token for library fragment in path
54 private static final String LIBRARAY_PATH_TOKEN = "/lib";
57 * Private constructor used to prevent sub class instantiation.
59 private ClassUtils() {}
62 * Get the class names of all classes on the class path. WARNING: This is a heavy call, use sparingly
64 * @return a set of class names for all classes in the class path
66 public static Set<String> getClassNames() {
67 // The return set of class names
68 final Set<String> classNameSet = new TreeSet<>();
71 // The library path for predefined classes in Java
72 String sunBootLibraryPathString = System.getProperty(SUN_BOOT_LIBRARY_PATH);
74 // Check it exists and has a "lib" in it
75 if (sunBootLibraryPathString != null && sunBootLibraryPathString.contains(LIBRARAY_PATH_TOKEN)) {
76 // Strip any superfluous trailer from path
77 sunBootLibraryPathString = sunBootLibraryPathString.substring(0,
78 sunBootLibraryPathString.lastIndexOf(LIBRARAY_PATH_TOKEN) + LIBRARAY_PATH_TOKEN.length());
80 final File bootLibraryFile = new File(sunBootLibraryPathString);
81 // The set used to hold class names is populated with predefined Java classes
82 classNameSet.addAll(processDir(bootLibraryFile, ""));
85 // Get the entries on the class path
86 URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
88 // Try get the classes in the bootstrap loader
90 final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
91 if (nullclassloader != null) {
92 // There a long way and a short way, Short way: causes a warning that cannot be suppressed
93 // URL[] moreurls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
95 Method m = nullclassloader.getMethod("getBootstrapClassPath");
97 final Object cp = m.invoke(null, (Object[]) null);
99 m = cp.getClass().getMethod("getURLs");
101 final URL[] moreurls = (URL[]) (m.invoke(cp, (Object[]) null));
102 if (moreurls != null && moreurls.length > 0) {
103 if (urls.length == 0) {
106 final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
107 System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
116 } catch (final ClassNotFoundException e) {
117 LOGGER.warn("Failed to find default path for JRE libraries", e);
120 // Iterate over the class path entries
121 for (final URL url : urls) {
122 if (url == null || url.getFile() == null) {
125 final File urlFile = new File(url.getFile());
126 // Directories may contain ".class" files
127 if (urlFile.isDirectory()) {
128 classNameSet.addAll(processDir(urlFile, url.getFile()));
130 // JARs are processed as well
131 else if (url.getFile().endsWith(".jar")) {
132 classNameSet.addAll(processJar(urlFile));
134 // It's a resource or some other non-executable thing
138 } catch (final Exception e) {
139 LOGGER.warn("could not get the names of Java classes", e);
146 * Find all classes in directories and JARs in those directories.
148 * @param classDirectory The directory to search for classes
149 * @param rootDir The root directory, to be removed from absolute paths
150 * @return a set of classes which may be empty
151 * @throws Exception on errors processing directories
153 public static Set<String> processDir(final File classDirectory, final String rootDir) throws Exception {
155 final TreeSet<String> classNameSet = new TreeSet<>();
157 // Iterate over the directory
158 if (classDirectory == null || !classDirectory.isDirectory()) {
161 for (final File child : classDirectory.listFiles()) {
162 if (child.isDirectory()) {
164 classNameSet.addAll(processDir(child, rootDir));
165 } else if (child.getName().endsWith(".jar")) {
167 classNameSet.addAll(processJar(child));
168 } else if (child.getName().endsWith(".class") && !child.getName().contains("$")) {
169 // Process the ".class" file
171 child.getAbsolutePath().replace(rootDir, "").replaceFirst("\\.class$", "").replace('/', '.'));
180 * Condition the file name as a class name.
182 * @param fileNameIn The file name to convert to a class name
183 * @return the conditioned class name
185 public static String processFileName(final String fileNameIn) {
186 String fileName = fileNameIn;
188 if (fileName == null) {
191 final int classesPos = fileName.indexOf(CLASSES_TOKEN);
193 if (classesPos != -1) {
194 fileName = fileName.substring(classesPos + CLASSES_TOKEN.length());
197 return fileName.replaceFirst("\\.class$", "").replace('/', '.');
201 * Read all the class names from a Jar.
203 * @param jarFile the JAR file
204 * @return a set of class names
205 * @throws Exception on errors processing JARs
207 public static Set<String> processJar(final File jarFile) throws Exception {
208 // Pass the file as an input stream
209 return processJar(new FileInputStream(jarFile.getAbsolutePath()));
213 * Read all the class names from a Jar.
215 * @param jarInputStream the JAR input stream
216 * @return a set of class names
217 * @throws Exception on errors processing JARs
219 public static Set<String> processJar(final InputStream jarInputStream) throws Exception {
221 final TreeSet<String> classPathSet = new TreeSet<>();
223 if (jarInputStream == null) {
226 // JARs are ZIP files
227 final ZipInputStream zip = new ZipInputStream(jarInputStream);
229 // Iterate over each entry in the JAR
230 for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
231 if (!entry.isDirectory() && entry.getName().endsWith(".class") && !entry.getName().contains("$")) {
232 classPathSet.add(entry.getName().replaceFirst("\\.class$", "").replace('/', '.'));
240 * The main method exercises this class for test purposes.
242 * @param args the args
244 public static void main(final String[] args) {
245 for (final String clz : getClassNames()) {
246 System.out.println("Found class: " + clz);