ServletContextAdapter extends ClassVisitor { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if ((access & (ACC_STATIC | ACC_PUBLIC)) == ACC_PUBLIC && "addListener".equals(name) && ("(Ljava/lang/Object;)V".equals(desc) || "(Ljava/util/EventListener;)V".equals(desc))) { debug("modifying addListener(...) method for %s", className); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); return new EnahceAddListener(mv); } if ("<clinit>".equals(name) && !addedStaticInit) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); return new EnhanceStaticInit(mv); } return super.visitMethod(access, name, desc, signature, exceptions); } ServletContextAdapter(ClassVisitor cv); @Override void visit(int version, int access, String name, String signature, String superName, String[] interfaces); @Override MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions); @Override void visitEnd();  }
@Test public void testIgnoreNonPublicMethods() { ClassVisitor cv = mock(ClassVisitor.class); ServletContextAdapter sca = new ServletContextAdapter(cv); MethodVisitor result = sca.visitMethod(ACC_PROTECTED, "addListener", "(Ljava/lang/Object;)V", null, null); assertThat(result, not(instanceOf(EnahceAddListener.class))); result = sca.visitMethod(ACC_PRIVATE, "addListener", "(Ljava/util/EventListener;)V", null, null); assertThat(result, not(instanceOf(EnahceAddListener.class))); result = sca.visitMethod(ACC_STATIC | ACC_PUBLIC, "addListener", "(Ljava/util/EventListener;)V", null, null); assertThat(result, not(instanceOf(EnahceAddListener.class))); }
@Test public void testVisitMethodToIntercept() { ClassVisitor cv = mock(ClassVisitor.class); ServletContextAdapter sca = new ServletContextAdapter(cv); MethodVisitor result = sca.visitMethod(ACC_PUBLIC, "addListener", "(Ljava/lang/Object;)V", null, null); assertThat(result, instanceOf(EnahceAddListener.class)); result = sca.visitMethod(ACC_PUBLIC, "addListener", "(Ljava/util/EventListener;)V", null, null); assertThat(result, instanceOf(EnahceAddListener.class)); result = sca.visitMethod(ACC_PUBLIC, "addListener", "(Ljava/util/EventListener;)V", null, null); assertThat(result, instanceOf(EnahceAddListener.class)); }
@Test public void testVisitMethodNotToIntercept() { ClassVisitor cv = mock(ClassVisitor.class); ServletContextAdapter sca = new ServletContextAdapter(cv); MethodVisitor result = sca.visitMethod(ACC_PUBLIC, "addListeners", "(Ljava/lang/Object;)V", null, null); assertThat(result, not(instanceOf(EnahceAddListener.class))); result = sca.visitMethod(ACC_PUBLIC, "addListener", "(Ljava/util/List;)V", null, null); assertThat(result, not(instanceOf(EnahceAddListener.class))); result = sca.visitMethod(ACC_PUBLIC, "addListener", "(Ljava/lang/String;)V", null, null); assertThat(result, not(instanceOf(EnahceAddListener.class))); }