Ido Kelson
Ido Kelson

Reputation: 23

Javassist - CannotCompileException cannot find some imported interface

I am using javassist with java agent to add code to java spring application. I am trying to add System.out code to DispatcherServlet doDispatch(). I am getting an exception: "javassist.CannotCompileException: cannot find javax.servlet.http.HttpServletRequest". javax.servlet.http.HttpServletRequest is an interface class imported by DispatcherServlet. It looks like some load order issue. How can I make it find or load the interface class? My transformer code look like:

public byte[] transform(ClassLoader loader, String className,
                            Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {
        boolean changed = false;
        if (className.equals("org/springframework/web/servlet/DispatcherServlet")) {
            try {
                String name = className.replaceAll("/", ".");
                pool.insertClassPath(new ByteArrayClassPath(name, classfileBuffer));
                CtClass cclass = pool.get(name);

                for (CtMethod currentMethod: cclass.getDeclaredMethods("doDispatch")) {
                    try {
                        currentMethod.insertBefore("System.out.println(\"before handler\");");
                        currentMethod.insertAfter("System.out.println(\"after handler\");");
                        changed = true;
                    } catch(javassist.CannotCompileException e) {
                        logger.error(e + ": " + currentMethod);
                    }
                }
                if (changed) {
                    classfileBuffer = cclass.toBytecode();
                    cclass.detach();
                    return classfileBuffer;
                }
                cclass.detach();
            } catch(NotFoundException e) {
                logger.error(e + ": " + className);
            } catch (Exception e) {
                logger.error(e + ": " + className);
            }
        }

        return null; // didn't change anything
    }

I tried to add the path to the class pool using: pool.appendClassPath("javax/servlet/http"); But it did not help

Upvotes: 0

Views: 126

Answers (1)

Ido Kelson
Ido Kelson

Reputation: 23

Found the problem: pool.appendSystemPath(); should be called on the ClassPool

Upvotes: 0

Related Questions