patterntesting.runtime.monitor.internal.ClasspathDigger Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of patterntesting-rt Show documentation
Show all versions of patterntesting-rt Show documentation
PatternTesting Runtime (patterntesting-rt) is the runtime component for
the PatternTesting framework. It provides the annotations and base classes
for the PatternTesting testing framework (e.g. patterntesting-check,
patterntesting-concurrent or patterntesting-exception) but can be also
used standalone for classpath monitoring or profiling.
It uses AOP and AspectJ to perform this feat.
/*
* $Id: ClasspathDigger.java,v 1.3 2016/03/13 14:42:09 oboehm Exp $
*
* Copyright (c) 2009 by Oliver Boehm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 15.05.2009 by oliver ([email protected])
*/
package patterntesting.runtime.monitor.internal;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.management.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.*;
import patterntesting.runtime.exception.*;
import patterntesting.runtime.io.*;
import patterntesting.runtime.monitor.ClassloaderType;
import patterntesting.runtime.util.*;
/**
* This helper class digs into found classloader for information like
* used classpath and other things. It was extracted from ClasspathMonitor
* to separate the classloader specific part of it into its own class.
*
* Since 1.6.1 this class was moved into the internal package. It is not
* intended for external use
*
*
* @author oliver
* @version $Revision: 1.3 $
* @since 15.05.2009
*/
public class ClasspathDigger {
/** The ClasspathAgent as MBean. */
protected static final ObjectName AGENT_MBEAN ;
private static final Logger LOG = LoggerFactory.getLogger(ClasspathDigger.class);
private final ClassLoader classLoader;
/** This will work of course only for the SunVM. */
private final String[] bootClassPath = ClasspathDigger.getClasspath("sun.boot.class.path");
private static final MBeanServer MBEAN_SERVER = ManagementFactory.getPlatformMBeanServer();
static {
try {
AGENT_MBEAN = new ObjectName("patterntesting.agent:type=ClasspathAgent");
} catch (MalformedObjectNameException e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* Instantiates a new classpath digger.
*/
public ClasspathDigger() {
this(Environment.getClassLoader());
}
/**
* Instantiates a new classpath digger.
*
* @param cloader the cloader
* @since 1.2
*/
public ClasspathDigger(final ClassLoader cloader) {
this.classLoader = cloader;
}
/**
* Gets the class loader.
*
* @return the classLoader
*/
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Checks if is classloader supported.
*
* @return true, if is classloader supported
*/
public boolean isClassloaderSupported() {
return ClassloaderType.isSupported(classLoader.getClass().getName());
}
/**
* Checks if the ClasspathAgent is available as MBean.
* The ClasspathAgent is needed for classloaders which are not
* directly supported (e.g. IBM's classloader of their JDK).
*
* @return true, if is agent available
*/
public static boolean isAgentAvailable() {
try {
return MBEAN_SERVER.getObjectInstance(AGENT_MBEAN) != null;
} catch (InstanceNotFoundException e) {
LOG.debug("MBean '{}' is not available.", AGENT_MBEAN);
LOG.trace("ClasspathAgent is not registered at {}:", MBEAN_SERVER, e);
return false;
}
}
/**
* To get the boot classpath the sytem property "sun.boot.class.path" is
* used to get them. This will work of course only for the SunVM.
*
* @return the boot classpath as String array
*/
public String[] getBootClasspath() {
return this.bootClassPath;
}
/**
* We can use the system property "java.class.path" to get the classpath.
* But this works not inside an application server or servlet enginle (e.g.
* inside Tomcat) because they have their own classloader to load the
* classes.
*
* In the past we tried to use the private (and undocoumented) attribute
* "domains" of the classloader. This works for a normal application but
* Tomcat's WebappClassLoader listed also classes in the "domains"-Set. Now
* we will try to detect the different classloader to access some private
* and secret attributes of this classloader.
*
* At the moment only org.apache.catalina.loader.WebappClassLoader is
* supported. For all other classloaders the standard approach using the
* system property "java.class.path" is used.
*
* @return the classpath as String array
*/
public String[] getClasspath() {
try {
switch (ClassloaderType.toClassloaderType(this.classLoader)) {
case NET:
return getNetClasspath();
case TOMCAT:
return getTomcatClasspath();
case WEBLOGIC:
return getWeblogicClasspath();
case WEBSPHERE:
return getWebsphereClasspath();
default:
LOG.trace("using 'java.class.path' to get classpath...");
}
} catch (IllegalArgumentException ex) {
LOG.warn("Will fallback to 'java.class.path' because cannot get classpath from {}:", classLoader, ex);
}
return getClasspath("java.class.path");
}
private String[] getNetClasspath() {
URLClassLoader netloader = (URLClassLoader) this.classLoader;
return getAsClasspath(netloader.getURLs());
}
private String[] getTomcatClasspath() {
URL[] repositoryURLs = (URL[]) ClassloaderType.TOMCAT.getClasspathFrom(this.classLoader);
return getAsClasspath(repositoryURLs);
}
private static String[] getAsClasspath(final URL[] repositoryURLs) {
String[] cp = new String[repositoryURLs.length];
for (int i = 0; i < cp.length; i++) {
cp[i] = Converter.toAbsolutePath(Converter.toURI(repositoryURLs[i]));
}
return cp;
}
private String[] getWeblogicClasspath() {
return getClasspathFromPackages();
}
/**
* The WebSphere classload has an attribute 'localClassPath' where the
* classpath is stored as String. Unfortunately the path of HTML and JSP
* pages is also part of this classpath, e.g. the classpath looks like
*
* "...:/tmp/web/WEB-INF/classes:/tmp/web/:...".
*
* So we must remove e.g. "/tmp/web" from the classpath to get the wanted
* Java classpath.
*
* @return the websphere classpath
*/
private String[] getWebsphereClasspath() {
String localClassPath = (String) ClassloaderType.WEBSPHERE
.getClasspathFrom(this.classLoader);
String[] classpath = splitClasspath(localClassPath);
List files = new ArrayList(classpath.length);
List toBeRemoved = new ArrayList(classpath.length);
File webinfClasses = new File("WEB-INF", "classes");
for (int i = 0; i < classpath.length; i++) {
ExtendedFile f = new ExtendedFile(classpath[i]);
files.add(f);
if (f.endsWith(webinfClasses)) {
toBeRemoved.add(f.getBaseDir(webinfClasses));
}
}
for (File file : toBeRemoved) {
files.remove(file);
}
return FileHelper.toStringArray(files);
}
/**
* Gets the classpath.
*
* @param key the key
* @return the classpath as String array
*/
protected static String[] getClasspath(final String key) {
String classpath = System.getProperty(key);
if (classpath == null) {
LOG.info(key + " is not set (not a SunVM?)");
return new String[0];
}
return splitClasspath(classpath);
}
private static String[] splitClasspath(final String classpath) {
String[] cp = StringUtils.split(classpath, File.pathSeparator);
for (int i = 0; i < cp.length; i++) {
if (cp[i].endsWith(File.separator)) {
cp[i] = cp[i].substring(0, (cp[i].length() - 1));
}
}
return cp;
}
/**
* Returns the packages which were loaded by the classloader.
*
* Unfortunately ClassLoader.getPackages() is protected - ok, let's do the
* hard way using reflexion.
*
* @return array with the loaded packages
*/
public Package[] getLoadedPackageArray() {
Method method;
Class> cloaderClass = classLoader.getClass();
try {
method = ReflectionHelper.getMethod(cloaderClass, "getPackages");
} catch (NoSuchMethodException nsme) {
LOG.warn(cloaderClass + "#getPackages() not found:", nsme);
return new Package[0];
} catch (SecurityException e) {
LOG.warn("Cannot get method " + cloaderClass + "#getPackages();", e);
return new Package[0];
}
try {
method.setAccessible(true);
return (Package[]) method.invoke(classLoader);
} catch (IllegalAccessException ex) {
LOG.warn("Cannot access " + method + " and will return empty array:", ex);
} catch (InvocationTargetException ex) {
LOG.warn("Cannot invoke " + method + " and will return empty array:", ex);
}
return new Package[0];
}
/**
* Here we use the loaded packages to calculate the classpath. For each
* loaded package we will look from which jar file or directory this
* package is loaded.
*
* @return the found classpath as string array
* @since 27-Jul-2009
*/
protected String[] getClasspathFromPackages() {
Set packageURIs = new LinkedHashSet();
Package[] packages = this.getLoadedPackageArray();
for (int i = 0; i < packages.length; i++) {
String resource = Converter.toResource(packages[i]);
URI uri = whichResource(resource, this.classLoader);
if (uri != null) {
URI path = ClasspathHelper.getParent(uri, resource);
packageURIs.add(path);
}
}
return getClasspathFromPackages(packageURIs);
}
private String[] getClasspathFromPackages(final Set packages) {
String[] classpath = new String[packages.size()];
Iterator iterator = packages.iterator();
for (int i = 0; i < classpath.length; i++) {
URI uri = iterator.next();
classpath[i] = Converter.toAbsolutePath(uri);
}
return classpath;
}
/**
* Gets the resources.
*
* @param name the name
* @return the resources
*/
public Enumeration getResources(final String name) {
try {
Enumeration resources = this.classLoader.getResources(name);
if (!resources.hasMoreElements()) {
LOG.debug("Resource '{}' not found in classpath", name);
if (name.startsWith("/")) {
return getResources(name.substring(1));
}
}
return resources;
} catch (IOException ioe) {
throw new NotFoundException("resource '" + name + "' not found in classpath", ioe);
}
}
/**
* Returns the URI of the given resource and the given classloader.
* If the resource is not found it will be tried again with/without
* a leading "/" and with the parent classloader.
*
* @param name resource name (e.g. "log4j.properties")
* @return URI of the given resource (or null if resource was not found)
*/
public URI whichResource(final String name) {
return whichResource(name, this.classLoader);
}
/**
* Returns the URI of the given resource and the given classloader.
* If the resource is not found it will be tried again with/without
* a leading "/" and with the parent classloader.
*
* @param name resource name (e.g. "log4j.properties")
* @param cloader class loader
* @return URI of the given resource (or null if resource was not found)
*/
//@ProfileMe
public static URI whichResource(final String name, final ClassLoader cloader) {
assert cloader != null : "no classloader given";
URL url = cloader.getResource(name);
if (url == null) {
String newName = name.startsWith("/") ? name.substring(1) : "/" + name;
try {
url = cloader.getResource(newName);
} catch (RuntimeException ex) {
throw new ClassloaderException(cloader, "cannot get resource \"" + name + "\"", ex);
}
}
if (url == null) {
ClassLoader parent = cloader.getParent();
if (parent == null) {
return null;
} else {
if (LOG.isTraceEnabled()) {
LOG.trace(name + " not found with " + cloader
+ ", will ask " + parent + "...");
}
return whichResource(name, parent);
}
}
return Converter.toURI(url);
}
/**
* Checks if the given classname is loaded.
* Why does we use not Class as parameter here? If you would allow a
* parameter of type "Class" this class will be problably loaded before
* and this method will return always true!
*
* @param classname name of the class
* @return true if class is loaded
*/
public boolean isLoaded(final String classname) {
for (Iterator> iterator = getLoadedClassList().iterator(); iterator.hasNext();) {
Class> loaded = iterator.next();
if (classname.equals(loaded.getName())) {
return true;
}
}
return false;
}
/**
* Puts also the classloader in the toString representation.
*
* @return string containing the class laoder
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ClasspathDigger for " + this.classLoader;
}
/**
* Returns a list of classes which were loaded by the given classloader.
*
* Ok, we must do some hacks here: there is an undocumented attribute
* "classes" which contains the loaded classes.
*
*
* HANDLE WITH CARE (it's a hack and it depends on the used classloader)
*
*
* @return list of classes
*/
@SuppressWarnings("unchecked")
public List> getLoadedClassList() {
try {
Field field = ReflectionHelper.getField(classLoader.getClass(),
"classes");
List> classList = (List>) field.get(classLoader);
return new ArrayList>(classList);
} catch (NoSuchFieldException ex) {
LOG.debug("Classloader {} has no field 'classes':", classLoader, ex);
} catch (IllegalAccessException ex) {
LOG.debug("Cannot access field 'classes' of {}:", classLoader, ex);
}
LOG.debug("Will use agent to get loaded classed because classloader {} is not supported.",
classLoader);
return getLoadedClassListFromAgent();
}
/**
* Gets the loaded class list from patterntesting-agent. For this method you
* must start the Java VM with PatternTesting Agent as Java agent
* (java -javaagent:patterntesting-agent-1.x.x.jar ...) because
* this MBean is needed for the loaded classes.
*
* This class is protected for test reason.
*
*
* @return the loaded class list from agent
*/
protected List> getLoadedClassListFromAgent() {
try {
LOG.trace("Using \"{}\" as fallback for unsupported classloader {}.", AGENT_MBEAN, this.classLoader);
Class>[] classes = (Class>[]) MBEAN_SERVER.invoke(AGENT_MBEAN, "getLoadedClasses", new Object[] { this
.getClass().getClassLoader() }, new String[] { ClassLoader.class.getName() });
return Arrays.asList(classes);
} catch (InstanceNotFoundException e) {
LOG.warn("MBean \"{}\" not found ({}) - be sure to call patterntesting as agent"
+ " ('java -javaagent:patterntesting-agent-1.x.x.jar...')", AGENT_MBEAN, e);
return new ArrayList>();
} catch (JMException e) {
LOG.warn("Cannot call 'getLoadedClasses(..)' from MBean \"{}\"", AGENT_MBEAN, e);
return new ArrayList>();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy