org.arsenal.framework.core.loader.ShadowingClassLoader.java Source code

Java tutorial

Introduction

Here is the source code for org.arsenal.framework.core.loader.ShadowingClassLoader.java

Source

/*
 * Copyright 2002-2008 the original author or authors.
 *
 * 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 or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.arsenal.framework.core.loader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.arsenal.framework.util.Assert;
import org.arsenal.framework.util.StringUtils;
import org.arsenal.framework.util.XIOUtils;

public class ShadowingClassLoader extends ClassLoader {

    private final Set<String> excludedPackages = new HashSet<String>();

    private final Set<String> excludedClasses = new HashSet<String>();

    private final Object exclusionMonitor = new Object();

    /** Packages that are excluded by default */
    public static final String[] DEFAULT_EXCLUDED_PACKAGES = new String[] { "java.", "javax.", "sun.", "oracle.",
            "com.sun.", "com.ibm.", "COM.ibm.", "org.w3c.", "org.xml.", "org.dom4j.", "org.eclipse", "org.aspectj.",
            "net.sf.cglib.", "org.apache.xerces.", "org.apache.commons.logging." };

    private final ClassLoader parentClassLoader;

    private final List<ClassFileTransformer> classFileTransformers = new LinkedList<ClassFileTransformer>();

    private final Map<String, Class> classCache = new HashMap<String, Class>();

    /**
     * Create a new ShadowingClassLoader, decorating the given ClassLoader.
     * @param parentClassLoader the ClassLoader to decorate
     */
    public ShadowingClassLoader(ClassLoader parentClassLoader) {
        Assert.notNull(parentClassLoader, "Enclosing ClassLoader must not be null");
        this.parentClassLoader = parentClassLoader;
        for (String excludedPackage : DEFAULT_EXCLUDED_PACKAGES) {
            excludePackage(excludedPackage);
        }
    }

    /**
     * Add the given ClassFileTransformer to the list of transformers that this
     * ClassLoader will apply.
     * @param transformer the ClassFileTransformer
     */
    public void addTransformer(ClassFileTransformer transformer) {
        Assert.notNull(transformer, "Transformer must not be null");
        this.classFileTransformers.add(transformer);
    }

    /**
     * Copy all ClassFileTransformers from the given ClassLoader to the list of
     * transformers that this ClassLoader will apply.
     * @param other the ClassLoader to copy from
     */
    public void copyTransformers(ShadowingClassLoader other) {
        Assert.notNull(other, "Other ClassLoader must not be null");
        this.classFileTransformers.addAll(other.classFileTransformers);
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (shouldShadow(name)) {
            Class cls = this.classCache.get(name);
            if (cls != null) {
                return cls;
            }
            return doLoadClass(name);
        } else {
            return this.parentClassLoader.loadClass(name);
        }
    }

    /**
     * Determine whether the given class should be excluded from shadowing.
     * @param className the name of the class
     * @return whether the specified class should be shadowed
     */
    private boolean shouldShadow(String className) {
        return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader")
                && isEligibleForShadowing(className));
    }

    /**
     * Determine whether the specified class is eligible for shadowing
     * by this class loader.
     * @param className the class name to check
     * @return whether the specified class is eligible
     * @see #isExcluded
     */
    protected boolean isEligibleForShadowing(String className) {
        return !isExcluded(className);
    }

    private Class doLoadClass(String name) throws ClassNotFoundException {
        String internalName = StringUtils.replace(name, ".", "/") + ".class";
        InputStream is = this.parentClassLoader.getResourceAsStream(internalName);
        if (is == null) {
            throw new ClassNotFoundException(name);
        }
        try {

            byte[] bytes = XIOUtils.toByteArray(is);
            bytes = applyTransformers(name, bytes);
            Class cls = defineClass(name, bytes, 0, bytes.length);
            // Additional check for defining the package, if not defined yet.
            if (cls.getPackage() == null) {
                int packageSeparator = name.lastIndexOf('.');
                if (packageSeparator != -1) {
                    String packageName = name.substring(0, packageSeparator);
                    definePackage(packageName, null, null, null, null, null, null, null);
                }
            }
            this.classCache.put(name, cls);
            return cls;
        } catch (IOException ex) {
            throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
        }
    }

    private byte[] applyTransformers(String name, byte[] bytes) {
        String internalName = StringUtils.replace(name, ".", "/");
        try {
            for (ClassFileTransformer transformer : this.classFileTransformers) {
                byte[] transformed = transformer.transform(this, internalName, null, null, bytes);
                bytes = (transformed != null ? transformed : bytes);
            }
            return bytes;
        } catch (IllegalClassFormatException ex) {
            throw new IllegalStateException(ex);
        }
    }

    @Override
    public URL getResource(String name) {
        return this.parentClassLoader.getResource(name);
    }

    @Override
    public InputStream getResourceAsStream(String name) {
        return this.parentClassLoader.getResourceAsStream(name);
    }

    @Override
    public Enumeration<URL> getResources(String name) throws IOException {
        return this.parentClassLoader.getResources(name);
    }

    /**
     * Add a package name to exclude from decoration (e.g. overriding).
     * <p>Any class whose fully-qualified name starts with the name registered
     * here will be handled by the parent ClassLoader in the usual fashion.
     * @param packageName the package name to exclude
     */
    public void excludePackage(String packageName) {
        Assert.notNull(packageName, "Package name must not be null");
        synchronized (this.exclusionMonitor) {
            this.excludedPackages.add(packageName);
        }
    }

    /**
     * Add a class name to exclude from decoration (e.g. overriding).
     * <p>Any class name registered here will be handled by the parent
     * ClassLoader in the usual fashion.
     * @param className the class name to exclude
     */
    public void excludeClass(String className) {
        Assert.notNull(className, "Class name must not be null");
        synchronized (this.exclusionMonitor) {
            this.excludedClasses.add(className);
        }
    }

    /**
     * Determine whether the specified class is excluded from decoration
     * by this class loader.
     * <p>The default implementation checks against excluded packages and classes.
     * @param className the class name to check
     * @return whether the specified class is eligible
     * @see #excludePackage
     * @see #excludeClass
     */
    protected boolean isExcluded(String className) {
        synchronized (this.exclusionMonitor) {
            if (this.excludedClasses.contains(className)) {
                return true;
            }
            for (String packageName : this.excludedPackages) {
                if (className.startsWith(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        ShadowingClassLoader shadowLoader = new ShadowingClassLoader(loader);
        boolean shadow = shadowLoader.isEligibleForShadowing("SegSyncJobTaskMain");
        System.out.println(shadow);
        //shadowLoader.loadClass(name);
    }
}