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.

The newest version!
/**
 * $Id: ClasspathDigger.java,v 1.8 2009/12/29 21:33:29 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.reflect.*;
import java.net.*;
import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import patterntesting.runtime.annotation.ProfileMe;
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.8 $
 */
public class ClasspathDigger {

    private static final Log log = LogFactoryImpl.getLog(ClasspathDigger.class);
    private final ClassLoader classLoader = initClassloader();
    private 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");

    /**
     * @{link "http://www.odi.ch/prog/design/newbies.php#23"}
     * @return a valid classloader
     */
    protected ClassLoader initClassloader() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = ClasspathDigger.class.getClassLoader();
            log.warn("no ContextClassLoader found - using " + classLoader);
        }
        return classLoader;
    }

    /**
     * @return the classLoader
     */
    public ClassLoader getClassLoader() {
        return classLoader;
    }

    /**
     * Checks if is classloader supported.
     *
     * @return true, if is classloader supported
     */
    public boolean isClassloaderSupported() {
        String classloaderName = classLoader.getClass().getName();
        for (int i = 0; i < supportedClassLoaders.length; i++) {
            if(classloaderName.equals(supportedClassLoaders[i])) {
                return true;
            }
        }
        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 serlet 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(); } /** * @return the classpath as String array */ protected static String[] getClasspath(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(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(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") * @param cloader * @return URI of the given resource (or null if resource was not found) */ @ProfileMe public static URI whichResource(String name, 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); } /** * Puts also the classloader in the toString representation. * @see java.lang.Object#toString() */ @Override public String toString() { return "ClasspathDigger for " + this.classLoader; } } /** * $Log: ClasspathDigger.java,v $ * Revision 1.8 2009/12/29 21:33:29 oboehm * tested with Windows and WLS * * Revision 1.7 2009/12/19 22:34:09 oboehm * trailing spaces removed * * Revision 1.6 2009/09/25 14:49:43 oboehm * javadocs completed with the help of JAutodoc * * Revision 1.5 2009/09/18 13:54:52 oboehm * javadoc warnings fixed * * Revision 1.4 2009/08/11 20:20:23 oboehm * 1st try of tuning up ClasspathMonitor by using multiple threads * * Revision 1.3 2009/08/03 06:12:37 oboehm * partially support of WLS classload (via getClasspathFromPackages) * * $Source: /cvsroot/patterntesting/PatternTesting08/patterntesting-rt/src/main/java/patterntesting/runtime/monitor/ClasspathDigger.java,v $ */




© 2015 - 2025 Weber Informatics LLC | Privacy Policy