All Downloads are FREE. Search and download functionalities are using the official Maven repository.

patterntesting.runtime.monitor.ClasspathDigger Maven / Gradle / Ivy

Go to download

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.

There is a newer version: 2.4.0
Show newest version
/**
 * $Id: ClasspathDigger.java,v 1.11 2012/03/20 18:46:23 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;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;

import javax.management.*;

import org.apache.commons.lang.StringUtils;
import org.slf4j.*;

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.
 * If you want to support an unknown classloader you can subclass this class
 * and together with ClasspathMonitor.
 *
 * @author oliver
 * @since 15.05.2009
 * @version $Revision: 1.11 $
 */
public final 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;
    private static Boolean classLoaderSupported = null;
    private static final String[] supportedClassLoaders = {
            "sun.misc.Launcher$AppClassLoader",
            "org.apache.catalina.loader.WebappClassLoader",
            "weblogic.utils.classloaders.ChangeAwareClassLoader"
    };
    /** This will work of course only for the SunVM. */
    private final String[] bootClassPath = ClasspathDigger.getClasspath("sun.boot.class.path");
    private static final MBeanServer mbeanServer = 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() {
        if (classLoaderSupported != null) {
            return classLoaderSupported;
        }
        String classloaderName = classLoader.getClass().getName();
        for (int i = 0; i < supportedClassLoaders.length; i++) {
            if(classloaderName.equals(supportedClassLoaders[i])) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 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 (mbeanServer.getObjectInstance(AGENT_MBEAN) != null);
        } catch (InstanceNotFoundException e) {
            log.debug("{} is not available.", AGENT_MBEAN, 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() { String classloaderName = classLoader.getClass().getName(); if (classloaderName .equals("org.apache.catalina.loader.WebappClassLoader")) { return getTomcatClasspath(); } else if (classloaderName.startsWith("weblogic")) { return getWeblogicClasspath(); } else { log.trace("using 'java.class.path' to get classpath..."); return ClasspathDigger.getClasspath("java.class.path"); } } private String[] getTomcatClasspath() { try { Field field = ReflectionHelper.getField(classLoader.getClass(), "repositoryURLs"); URL[] repositoryURLs = (URL[]) field.get(classLoader); String[] cp = new String[repositoryURLs.length]; for (int i = 0; i < cp.length; i++) { cp[i] = Converter.toAbsolutePath(Converter.toURI(repositoryURLs[i])); } return cp; } catch (Exception e) { log.warn("can't access field 'repositoryURLs'", e); return getClasspath("java.class.path"); } } private String[] getWeblogicClasspath() { return getClasspathFromPackages(); } /** * 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 separator = System.getProperty("path.separator", ":"); String[] cp = StringUtils.split(classpath, separator); 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("can't get method " + cloaderClass + "#getPackages()", e); return new Package[0]; } try { method.setAccessible(true); return (Package[]) method.invoke(classLoader); } catch (Exception e) { log.warn("can't access " + method, e); 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; } /** * 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) { if (name.startsWith("/")) { url = cloader.getResource(name.substring(1)); } else { url = cloader.getResource("/" + name); } } 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 */ //@ProfileMe @SuppressWarnings("unchecked") public List> getLoadedClassList() { try { Field field = ReflectionHelper.getField(classLoader.getClass(), "classes"); List> classList = (List>) field.get(classLoader); return new ArrayList>(classList); } catch (Exception e) { log.debug("Unsupported classloader {} / has no field \"classes\".", classLoader, e); 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[]) mbeanServer.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 - 2024 Weber Informatics LLC | Privacy Policy