Search in sources :

Example 6 with CtClass

use of org.hotswap.agent.javassist.CtClass in project HotswapAgent by HotswapProjects.

the class CtClassJavaProxyGenerator method getFriendlyMethodSignature.

/**
 * Returns a human-readable string representing the signature of a method with the given name and parameter types.
 */
private static String getFriendlyMethodSignature(String name, CtClass[] parameterTypes) {
    StringBuilder sig = new StringBuilder(name);
    sig.append('(');
    for (int i = 0; i < parameterTypes.length; i++) {
        if (i > 0) {
            sig.append(',');
        }
        CtClass parameterType = parameterTypes[i];
        int dimensions = 0;
        while (parameterType.isArray()) {
            try {
                parameterType = parameterType.getComponentType();
            } catch (NotFoundException e) {
                throw new RuntimeException(e);
            }
            dimensions++;
        }
        sig.append(parameterType.getName());
        while (dimensions-- > 0) {
            sig.append("[]");
        }
    }
    sig.append(')');
    return sig.toString();
}
Also used : CtClass(org.hotswap.agent.javassist.CtClass) NotFoundException(org.hotswap.agent.javassist.NotFoundException)

Example 7 with CtClass

use of org.hotswap.agent.javassist.CtClass in project HotswapAgent by HotswapProjects.

the class WeldPlugin method getArchivePath.

private String getArchivePath(ClassLoader classLoader, CtClass ctClass, String knownClassName) throws NotFoundException {
    try {
        return (String) ReflectionHelper.invoke(null, Class.forName(BdaAgentRegistry.class.getName(), true, classLoader), "getArchiveByClassName", new Class[] { String.class }, knownClassName);
    } catch (ClassNotFoundException e) {
        LOGGER.error("getArchivePath() exception {}.", e.getMessage());
    }
    String classFilePath = ctClass.getURL().getPath();
    String className = ctClass.getName().replace(".", "/");
    // archive path ends with '/', therefore we set end position before the '/' (-1)
    String archivePath = classFilePath.substring(0, classFilePath.indexOf(className) - 1);
    return (new File(archivePath)).toPath().toString();
}
Also used : BdaAgentRegistry(org.hotswap.agent.plugin.weld.command.BdaAgentRegistry) CtClass(org.hotswap.agent.javassist.CtClass) File(java.io.File)

Example 8 with CtClass

use of org.hotswap.agent.javassist.CtClass in project HotswapAgent by HotswapProjects.

the class ProxyFactoryTransformer method patchProxyFactory.

/**
 * Patch ProxyFactory class.
 *   - add factory registration into constructor
 *   - changes call classLoader.loadClass(...) in getProxyClass() to ProxyClassLoadingDelegate.loadClass(classLoader, ...)
 *   - changes call ClassFileUtils.toClass() in createProxyClass() to ProxyClassLoadingDelegate.loadClass(...)
 *
 * @param ctClass the ProxyFactory class
 * @param classPool the class pool
 * @throws NotFoundException the not found exception
 * @throws CannotCompileException the cannot compile exception
 */
@OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.proxy.ProxyFactory")
public static void patchProxyFactory(CtClass ctClass, ClassPool classPool) throws NotFoundException, CannotCompileException {
    CtClass[] constructorParams = new CtClass[] { classPool.get("java.lang.String"), classPool.get("java.lang.Class"), classPool.get("java.util.Set"), // classPool.get("java.lang.String"),
    classPool.get("javax.enterprise.inject.spi.Bean"), classPool.get("boolean") };
    CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(constructorParams);
    // TODO : we should find constructor without this() call and put registration only into this one
    declaredConstructor.insertAfter("if (" + PluginManager.class.getName() + ".getInstance().isPluginInitialized(\"" + WeldPlugin.class.getName() + "\", this.classLoader)) {" + PluginManagerInvoker.buildCallPluginMethod("this.classLoader", WeldPlugin.class, "registerProxyFactory", "this", "java.lang.Object", "bean", "java.lang.Object", "this.classLoader", "java.lang.ClassLoader", "proxiedBeanType", "java.lang.Class") + "}");
    CtMethod getProxyClassMethod = ctClass.getDeclaredMethod("getProxyClass");
    getProxyClassMethod.instrument(new ExprEditor() {

        public void edit(MethodCall m) throws CannotCompileException {
            if (m.getClassName().equals(ClassLoader.class.getName()) && m.getMethodName().equals("loadClass"))
                m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.loadClass(this.classLoader,$1); }");
        }
    });
    CtMethod createProxyClassMethod = ctClass.getDeclaredMethod("createProxyClass");
    createProxyClassMethod.instrument(new ExprEditor() {

        public void edit(MethodCall m) throws CannotCompileException {
            if (m.getClassName().equals("org.jboss.weld.util.bytecode.ClassFileUtils") && m.getMethodName().equals("toClass"))
                m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClass($$); }");
        }
    });
}
Also used : PluginManager(org.hotswap.agent.config.PluginManager) CtClass(org.hotswap.agent.javassist.CtClass) WeldPlugin(org.hotswap.agent.plugin.weld.WeldPlugin) ExprEditor(org.hotswap.agent.javassist.expr.ExprEditor) CannotCompileException(org.hotswap.agent.javassist.CannotCompileException) MethodCall(org.hotswap.agent.javassist.expr.MethodCall) CtMethod(org.hotswap.agent.javassist.CtMethod) CtConstructor(org.hotswap.agent.javassist.CtConstructor) OnClassLoadEvent(org.hotswap.agent.annotation.OnClassLoadEvent)

Example 9 with CtClass

use of org.hotswap.agent.javassist.CtClass in project HotswapAgent by HotswapProjects.

the class ViewConfigTransformer method patchViewConfigExtension.

/**
 * Register DeltaspikePlugin and add reinitialization method to RepositoryComponent
 *
 * @param ctClass
 * @param classPool the class pool
 * @throws CannotCompileException the cannot compile exception
 * @throws NotFoundException the not found exception
 */
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.jsf.impl.config.view.ViewConfigExtension")
public static void patchViewConfigExtension(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {
    CtMethod init = ctClass.getDeclaredMethod("init");
    init.insertAfter("{" + "if (this.isActivated) {" + PluginManagerInvoker.buildInitializePlugin(DeltaSpikePlugin.class) + "}" + "}");
    LOGGER.debug("org.apache.deltaspike.jsf.impl.config.view.ViewConfigExtension enhanced with plugin initialization.");
    CtClass viewConfigResProxyClass = classPool.get("org.hotswap.agent.plugin.deltaspike.jsf.ViewConfigResolverProxy");
    CtField viewConfigResProxyField = new CtField(viewConfigResProxyClass, VIEW_CONFIG_RESOLVER_PROXY_FIELD, ctClass);
    ctClass.addField(viewConfigResProxyField);
    CtMethod generateProxyClassMethod = ctClass.getDeclaredMethod("transformMetaDataTree");
    generateProxyClassMethod.instrument(new ExprEditor() {

        public void edit(NewExpr e) throws CannotCompileException {
            if (e.getClassName().equals("org.apache.deltaspike.jsf.impl.config.view.DefaultViewConfigResolver"))
                e.replace("{ " + "java.lang.Object _resolver = new org.apache.deltaspike.jsf.impl.config.view.DefaultViewConfigResolver($$); " + "if (this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + "==null) {" + "this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + "=new org.hotswap.agent.plugin.deltaspike.jsf.ViewConfigResolverProxy();" + "}" + "this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + ".setViewConfigResolver(_resolver);" + "java.util.List _list = org.hotswap.agent.plugin.deltaspike.jsf.ViewConfigResolverUtils.findViewConfigRootClasses(this.rootViewConfigNode);" + PluginManagerInvoker.buildCallPluginMethod(DeltaSpikePlugin.class, "registerViewConfigRootClasses", "this", "java.lang.Object", "_list", "java.util.List") + "   $_ = this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + ";" + "}");
        }
    });
}
Also used : CtClass(org.hotswap.agent.javassist.CtClass) CtField(org.hotswap.agent.javassist.CtField) ExprEditor(org.hotswap.agent.javassist.expr.ExprEditor) NewExpr(org.hotswap.agent.javassist.expr.NewExpr) CannotCompileException(org.hotswap.agent.javassist.CannotCompileException) CtMethod(org.hotswap.agent.javassist.CtMethod) OnClassLoadEvent(org.hotswap.agent.annotation.OnClassLoadEvent)

Example 10 with CtClass

use of org.hotswap.agent.javassist.CtClass in project HotswapAgent by HotswapProjects.

the class ModuleClassLoaderTransformer method patchModuleClassLoader.

/**
 * @param ctClass the ct class
 * @throws NotFoundException the not found exception
 * @throws CannotCompileException the cannot compile exception
 */
@OnClassLoadEvent(classNameRegexp = "org.jboss.modules.ModuleClassLoader")
public static void patchModuleClassLoader(ClassPool classPool, CtClass ctClass) throws CannotCompileException {
    try {
        CtField pathField = ctClass.getDeclaredField("paths");
        CtClass pathsType = pathField.getType();
        String pathsGetter = "";
        CtClass ctHaClassLoader = classPool.get(HotswapAgentClassLoaderExt.class.getName());
        ctClass.addInterface(ctHaClassLoader);
        if ("java.util.concurrent.atomic.AtomicReference".equals(pathsType.getName())) {
            // version>=1.5
            pathsGetter = ".get()";
        }
        CtClass objectClass = classPool.get(Object.class.getName());
        CtField ctField = new CtField(objectClass, "$$ha$prepend", ctClass);
        ctClass.addField(ctField);
        ctClass.addMethod(CtNewMethod.make("private void $$ha$setupPrepend() {" + "       Class clPaths = Class.forName(\"org.jboss.modules.Paths\", true, this.getClass().getClassLoader());" + "       java.lang.reflect.Method spM  = clPaths.getDeclaredMethod(\"$$ha$setPrepend\", new Class[] {java.lang.Object.class});" + "       spM.invoke(this.paths" + pathsGetter + ", new java.lang.Object[] { $$ha$prepend });" + "}", ctClass));
        // Implementation of HotswapAgentClassLoaderExt.setExtraClassPath(...)
        ctClass.addMethod(CtNewMethod.make("public void setExtraClassPath(java.net.URL[] extraClassPath) {" + "   try {" + "       java.util.List resLoaderList = new java.util.ArrayList();" + "       for (int i=0; i<extraClassPath.length; i++) {" + "           try {" + "               java.net.URL url = extraClassPath[i];" + "               java.io.File root = new java.io.File(url.getPath());" + "               org.jboss.modules.ResourceLoader resourceLoader = org.jboss.modules.ResourceLoaders.createFileResourceLoader(url.getPath(), root);" + "               resLoaderList.add(resourceLoader);" + "           } catch (java.lang.Exception e) {" + "           " + ModuleClassLoaderTransformer.class.getName() + ".logSetExtraClassPathException(e);" + "           }" + "       }" + "       this.$$ha$prepend = resLoaderList;" + "       $$ha$setupPrepend();" + "   } catch (java.lang.Exception e) {" + "       " + ModuleClassLoaderTransformer.class.getName() + ".logSetExtraClassPathException(e);" + "   }" + "}", ctClass));
        CtMethod methRecalculate = ctClass.getDeclaredMethod("recalculate");
        methRecalculate.setName("_recalculate");
        ctClass.addMethod(CtNewMethod.make("boolean recalculate() {" + "   boolean ret = _recalculate();" + "   $$ha$setupPrepend();" + "   return ret;" + "}", ctClass));
        CtClass ctResLoadClass = classPool.get("org.jboss.modules.ResourceLoaderSpec[]");
        CtMethod methResourceLoaders = ctClass.getDeclaredMethod("setResourceLoaders", new CtClass[] { ctResLoadClass });
        methResourceLoaders.setBody("{" + "   boolean ret = setResourceLoaders((org.jboss.modules.Paths)this.paths" + pathsGetter + ", $1);" + "   $$ha$setupPrepend();" + "   return ret;" + "}");
    } catch (NotFoundException e) {
        LOGGER.warning("Unable to find field \"paths\" in org.jboss.modules.ModuleClassLoader.", e);
    }
}
Also used : CtClass(org.hotswap.agent.javassist.CtClass) CtField(org.hotswap.agent.javassist.CtField) NotFoundException(org.hotswap.agent.javassist.NotFoundException) HotswapAgentClassLoaderExt(org.hotswap.agent.util.classloader.HotswapAgentClassLoaderExt) CtMethod(org.hotswap.agent.javassist.CtMethod) OnClassLoadEvent(org.hotswap.agent.annotation.OnClassLoadEvent)

Aggregations

CtClass (org.hotswap.agent.javassist.CtClass)69 NotFoundException (org.hotswap.agent.javassist.NotFoundException)20 CtMethod (org.hotswap.agent.javassist.CtMethod)18 ClassPool (org.hotswap.agent.javassist.ClassPool)14 OnClassLoadEvent (org.hotswap.agent.annotation.OnClassLoadEvent)13 CannotCompileException (org.hotswap.agent.javassist.CannotCompileException)8 CtConstructor (org.hotswap.agent.javassist.CtConstructor)8 CtField (org.hotswap.agent.javassist.CtField)8 HashMap (java.util.HashMap)6 LoaderClassPath (org.hotswap.agent.javassist.LoaderClassPath)6 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 Test (org.junit.Test)5 Iterator (java.util.Iterator)4 ExprEditor (org.hotswap.agent.javassist.expr.ExprEditor)4 Method (java.lang.reflect.Method)3 IdentityHashMap (java.util.IdentityHashMap)3 BadBytecode (org.hotswap.agent.javassist.bytecode.BadBytecode)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2