public void testNewArray() throws Exception { ExprEditor ed = new ExprEditor() { int dim[] = {1, 2, 2, 1, 2, 2, 3}; int cdim[] = {1, 1, 2, 1, 1, 2, 2}; int counter = 0; public void edit(NewArray expr) throws CannotCompileException { try { CtClass str = sloader.get("java.lang.String"); if (counter < 3) assertEquals(str, expr.getComponentType()); else assertEquals(CtClass.intType, expr.getComponentType()); assertEquals(dim[counter], expr.getDimension()); assertEquals(cdim[counter], expr.getCreatedDimensions()); expr.replace("{ i += $1; $_ = $proceed($$); }"); ++counter; } catch (NotFoundException e) { throw new CannotCompileException(e); } } }; CtClass cc = sloader.get("test2.NewArray"); CtMethod m1 = cc.getDeclaredMethod("foo"); m1.instrument(ed); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(48, invoke(obj, "run")); }
private static CtMethod delegator0(CtMethod delegate, CtClass declaring) throws CannotCompileException, NotFoundException { MethodInfo deleInfo = delegate.getMethodInfo2(); String methodName = deleInfo.getName(); String desc = deleInfo.getDescriptor(); ConstPool cp = declaring.getClassFile2().getConstPool(); MethodInfo minfo = new MethodInfo(cp, methodName, desc); minfo.setAccessFlags(deleInfo.getAccessFlags()); ExceptionsAttribute eattr = deleInfo.getExceptionsAttribute(); if (eattr != null) minfo.setExceptionsAttribute((ExceptionsAttribute) eattr.copy(cp, null)); Bytecode code = new Bytecode(cp, 0, 0); boolean isStatic = Modifier.isStatic(delegate.getModifiers()); CtClass deleClass = delegate.getDeclaringClass(); CtClass[] params = delegate.getParameterTypes(); int s; if (isStatic) { s = code.addLoadParameters(params, 0); code.addInvokestatic(deleClass, methodName, desc); } else { code.addLoad(0, deleClass); s = code.addLoadParameters(params, 1); code.addInvokespecial(deleClass, methodName, desc); } code.addReturn(delegate.getReturnType()); code.setMaxLocals(++s); code.setMaxStack(s < 2 ? 2 : s); // for a 2-word return value minfo.setCodeAttribute(code.toCodeAttribute()); return new CtMethod(minfo, declaring); }
public void testCodeGen() throws Exception { CtClass cc = sloader.get("test2.CodeGen"); CtMethod m1 = cc.getDeclaredMethod("run"); m1.insertBefore( "{ double d = true ? 1 : 0.1; " + " d = d > 0.5 ? 0.0 : - 1.0; " + " System.out.println(d); " + " String s = \"foo\"; " + " s = 1 + 2 + s + \"bar\"; " + " s += \"poi\" + 3 + seven() + seven(\":\" + ' '); " + " s += .14; " + " msg = s; " + " System.out.println(s); }"); // recursive type check is done if $proceed is used. CtMethod m2 = CtNewMethod.make( "public int test() {" + " String s = $proceed(\"int\" + (3 + 0.14)) + '.'; " + " System.out.println(s); return s.length(); }", cc, "this", "seven"); cc.addMethod(m2); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(19, invoke(obj, "run")); assertEquals(9, invoke(obj, "test")); }
private void findAndRemoveMethod(CtClass ctClass, String methodName) throws NotFoundException { try { CtMethod ctMethod = ctClass.getDeclaredMethod(methodName); ctClass.getClassFile().getMethods().remove(ctMethod.getMethodInfo()); } catch (Exception e) { } }
public T createJavassistProxy( LoadBalancer loadBalance, ConcurrentMap<String, T> map, Class ifaces) throws Exception { Class<?>[] interfaces = ifaces.getInterfaces(); if (interfaces.length == 1) { ClassPool mPool = new ClassPool(true); CtClass ctClass = mPool.get(interfaces[0].getName()); // 新建代理类 CtClass mCtc = mPool.makeClass(ifaces.getName() + "$JavassistProxy"); mCtc.setSuperclass(ctClass); for (CtMethod method : ctClass.getDeclaredMethods()) { System.out.println(method.getName()); // CtMethod m = new CtMethod(method.getReturnType(), // ,method.getParameterTypes(), mCtc); // cc.addMethod(m); // m.setBody("{ x += $1; }"); mCtc.addMethod(method); // method.setBody(""); } // mCtc.debugWriteFile("/home/liguojun"); return null; } else { return null; } }
private void enhanceJPACallback(CtClass ctClass, CtMethod method, Class anno) throws Exception { if (method.hasAnnotation(anno)) { CtMethod ctMethod = CtMethod.make( format( "public void {}() {\n" + " net.csdn.jpa.context.JPAContext jpaContext = getJPAConfig().reInitJPAContext();\n" + " try {\n" + " {}();\n" + " getJPAConfig().getJPAContext().closeTx(false);\n" + " } catch (Exception e) {\n" + " getJPAConfig().getJPAContext().closeTx(true);\n" + " } finally {\n" + " getJPAConfig().setJPAContext(jpaContext);\n" + " }\n" + " }", "$_" + method.getName(), method.getName()), ctClass); ctClass.addMethod(ctMethod); AnnotationsAttribute annotationsAttribute = EnhancerHelper.getAnnotations(ctMethod); EnhancerHelper.createAnnotation(annotationsAttribute, callback_classes.get(anno)); } }
private Object[] extractParams(Mapping mapping, HttpServletRequest request) { Object[] params; ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(mapping.clazz)); CtMethod cm = null; CtClass[] parameterTypes = new CtClass[0]; try { cm = pool.get(mapping.clazz.getName()).getDeclaredMethod(mapping.method.getName()); parameterTypes = cm.getParameterTypes(); } catch (NotFoundException e) { e.printStackTrace(); } if (0 == parameterTypes.length) return new Object[0]; params = new Object[parameterTypes.length]; LocalVariableAttribute attr = (LocalVariableAttribute) cm.getMethodInfo().getCodeAttribute().getAttribute(LocalVariableAttribute.tag); int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; for (int i = 0; i < params.length; i++) { String name = attr.variableName(i + pos); String typeName = parameterTypes[i].getName(); Binder binder = Binder.valueOf(typeName); Object param = binder.get(name, request, mapping); params[i] = param; } return params; }
public void testJIRA249() throws Exception { CtClass cc = sloader.get("test5.BoolTest"); CtMethod testMethod = cc.getDeclaredMethod("test"); testMethod.insertBefore("i = foo(true & true);"); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(1, invoke(obj, "run")); }
public void testJIRA241() throws Exception { CtClass cc = sloader.get("test5.JIRA241"); CtMethod testMethod = cc.getDeclaredMethod("test"); testMethod.insertAfter("System.out.println(\"inserted!\");"); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(10, invoke(obj, "run")); }
private void findAndRemoveMethod(CtClass ctClass, CtField ctField, String className) { try { CtMethod ctMethod = ctClass.getDeclaredMethod( ctField.getName(), new CtClass[] {ctClass.getClassPool().get(className)}); ctClass.getClassFile().getMethods().remove(ctMethod.getMethodInfo()); } catch (Exception e) { } }
public void testReplaceClassName() throws Exception { String oldName = "test2.ReplaceClassName2"; String newName = "test2.ReplaceClassName3"; CtClass cc = sloader.get("test2.ReplaceClassName"); cc.replaceClassName(oldName, newName); cc.writeFile(); CtClass cc2 = dloader.get(cc.getName()); CtMethod m = cc2.getDeclaredMethod("foo"); assertEquals(newName, m.getParameterTypes()[0].getName()); }
public void testLocalVar() throws Exception { CtClass cc = sloader.get("test2.LocalVar"); CtMethod m = cc.getDeclaredMethod("toString"); m.addLocalVariable("var", CtClass.booleanType); m.insertBefore("{var = true; }"); m.insertAfter("{if (var) hashCode(); }", false); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(3, invoke(obj, "foo")); }
static <A extends Annotation> void removeAnnotation(CtMethod<?> method, Class<A> annClass) { CtAnnotation<?> toRemove = null; for (CtAnnotation<? extends Annotation> ctAnnotation : method.getAnnotations()) { if (annClass.isAssignableFrom(ctAnnotation.getActualAnnotation().getClass())) { toRemove = ctAnnotation; break; } } if (toRemove != null) method.removeAnnotation(toRemove); }
public void testAddLocalVar() throws Exception { CtClass cc = sloader.get("test2.AddLocalVar"); CtMethod m1 = cc.getDeclaredMethod("foo"); m1.addLocalVariable("i", CtClass.intType); m1.insertBefore("i = 3;"); m1.insertAfter("$_ = i + 1;"); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(4, invoke(obj, "foo")); }
/** * Creates a public abstract method. * * @param returnType the type of the returned value * @param mname the method name * @param parameters a list of the parameter types * @param exceptions a list of the exception types * @param declaring the class to which the created method is added. * @see CtMethod#CtMethod(CtClass,String,CtClass[],CtClass) */ public static CtMethod abstractMethod( CtClass returnType, String mname, CtClass[] parameters, CtClass[] exceptions, CtClass declaring) throws NotFoundException { CtMethod cm = new CtMethod(returnType, mname, parameters, declaring); cm.setExceptionTypes(exceptions); return cm; }
public void testSuperCall() throws Exception { CtClass cc = sloader.get("test2.SuperCall"); CtMethod m1 = cc.getDeclaredMethod("foo"); m1.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { m.replace("{ $_ = $proceed($$); }"); } }); cc.writeFile(); Object obj = make(cc.getName()); invoke(obj, "bar"); }
public void testRemoveCall() throws Exception { CtClass cc = sloader.get("test2.RemoveCall"); CtMethod m1 = cc.getDeclaredMethod("bar"); m1.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { m.replace("{ $_ = ($r)null; }"); } }); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(0, invoke(obj, "bar")); }
public void testProceedToDefaultMethod() throws Exception { CtClass cc = ClassPool.getDefault().get("test5.ProceedDefault"); CtMethod mth = cc.getDeclaredMethod("bar"); mth.instrument( new ExprEditor() { public void edit(MethodCall c) throws CannotCompileException { c.replace("$_ = $proceed($$) + 10000;"); } }); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(21713, invoke(obj, "run")); }
public void testNewExprInTry() throws Exception { ExprEditor ed = new ExprEditor() { public void edit(NewExpr expr) throws CannotCompileException { expr.replace("$_ = new test2.HashMapWrapper($1, 1);"); } }; CtClass cc = sloader.get("test2.NewExprInTry"); CtMethod m1 = cc.getDeclaredMethod("foo"); m1.instrument(ed); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(1, invoke(obj, "run")); }
public void testJIRA246() throws Exception { CtClass ctClass = sloader.makeClass("test5.JIRA246Test"); ctClass.addInterface(sloader.get(test5.JIRA246.Test.class.getName())); String methodBody = "public void test() { defaultMethod(); }"; CtMethod ctMethod = CtMethod.make(methodBody, ctClass); ctClass.addMethod(ctMethod); }
public void testBadClass() throws Exception { CtClass badClass = ClassPool.getDefault().makeClass("badClass"); String src = String.join( System.getProperty("line.separator"), "public void eval () {", " if (true) {", " double t=0;", " } else {", " double t=0;", " }", " for (int i=0; i < 2; i++) {", " int a=0;", " int b=0;", " int c=0;", " int d=0;", " if (true) {", " int e = 0;", " }", " }", "}"); System.out.println(src); badClass.addMethod(CtMethod.make(src, badClass)); Class clazzz = badClass.toClass(); Object obj = clazzz.getConstructor().newInstance(); // <-- falls here }
public void testMethodCall() throws Exception { CtClass cc = sloader.get("test2.MethodCall"); CtMethod m1 = cc.getDeclaredMethod("bar"); m1.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { if ("clone".equals(m.getMethodName())) methodCallData = m.getClassName(); } }); cc.writeFile(); assertEquals("java.lang.String[]", methodCallData); assertEquals("java.lang.String[]", sloader.get("[Ljava/lang/String;").getName()); assertEquals("int[][]", sloader.get("[[I").getName()); }
/** Init the plugin from start method. */ @Transform(classNameRegexp = "org.apache.catalina.loader.WebappLoader") public static void patchWebappLoader(CtClass ctClass) throws NotFoundException, CannotCompileException, ClassNotFoundException { try { CtMethod startInternalMethod = ctClass.getDeclaredMethod("startInternal"); // init the plugin String src = PluginManagerInvoker.buildInitializePlugin(TomcatPlugin.class, "classLoader"); startInternalMethod.insertAfter(src); } catch (NotFoundException e) { LOGGER.warning( "org.apache.catalina.loader.WebappLoader does not contain startInternal method. Tomcat plugin will be disabled.\n" + "*** This is Ok, Tomcat plugin handles only special properties ***"); return; } }
public void onWrite(ClassPool pool, String className) throws NotFoundException, CannotCompileException { CtClass cc = pool.get(className); try { if (isPersistent(className)) { CtClass base = cc.getSuperclass(); CtConstructor cons = new CtConstructor(constructorParams, cc); if (base.subclassOf(persistent) || base == object) { cons.setBody(null); cc.addConstructor(cons); if (base == object) { cc.setSuperclass(persistent); } } else { if (!isPersistent(base.getName())) { throw new NotFoundException( "Base class " + base.getName() + " was not declared as persistent"); } cons.setBody("super($0);"); cc.addConstructor(cons); } preprocessMethods(cc, true, true); if (base == persistent || base == object) { CtMethod m = new CtMethod(isRecursive, cc, null); m.setBody("return false;"); cc.addMethod(m); addSerializeMethods(cc, false); } else if (base.subtypeOf(serializable)) { addSerializeMethods(cc, true); } if ((cc.getModifiers() & Modifier.PRIVATE) == 0) { CtClass f = pool.makeClass(className + "LoadFactory"); f.addInterface(factory); CtMethod c = new CtMethod(create, f, null); c.setBody("return new " + className + "($1);"); f.addMethod(c); CtNewConstructor.defaultConstructor(f); } } else { preprocessMethods( cc, cc.subtypeOf(persistent) && cc != persistent, !className.startsWith("org.nachodb")); } } catch (Exception x) { x.printStackTrace(); } }
public void testRemoveAnnotatino() throws Exception { CtClass cc = sloader.get("test5.RemoveAnnotation"); AnnotationsAttribute aa = (AnnotationsAttribute) cc.getClassFile().getAttribute(AnnotationsAttribute.invisibleTag); assertTrue(aa.removeAnnotation("test5.RemoveAnno1")); AttributeInfo ai = cc.getClassFile().removeAttribute(AnnotationsAttribute.invisibleTag); assertEquals(ai.getName(), AnnotationsAttribute.invisibleTag); CtMethod foo = cc.getDeclaredMethod("foo"); AnnotationsAttribute aa2 = (AnnotationsAttribute) foo.getMethodInfo().getAttribute(AnnotationsAttribute.invisibleTag); assertTrue(aa2.removeAnnotation("test5.RemoveAnno1")); CtMethod bar = cc.getDeclaredMethod("bar"); AnnotationsAttribute aa3 = (AnnotationsAttribute) bar.getMethodInfo().getAttribute(AnnotationsAttribute.invisibleTag); assertFalse(aa3.removeAnnotation("test5.RemoveAnno1")); assertTrue(aa3.removeAnnotation("test5.RemoveAnno2")); AttributeInfo ai2 = bar.getMethodInfo().removeAttribute(AnnotationsAttribute.invisibleTag); assertEquals(ai2.getName(), AnnotationsAttribute.invisibleTag); CtMethod run = cc.getDeclaredMethod("run"); AttributeInfo ai3 = run.getMethodInfo().removeAttribute(AnnotationsAttribute.invisibleTag); assertNull(ai3); CtField baz = cc.getDeclaredField("baz"); AttributeInfo ai4 = baz.getFieldInfo().removeAttribute(AnnotationsAttribute.invisibleTag); assertEquals(ai4.getName(), AnnotationsAttribute.invisibleTag); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(3, invoke(obj, "run")); }
public void testInsertLocal() throws Exception { CtClass cc = sloader.get("test2.InsertLocal"); CtMethod m1 = cc.getDeclaredMethod("foo"); m1.insertBefore("{ i = s.length(); d = 0.14; }"); m1.insertAfter("{ field = i; }"); CtMethod m2 = cc.getDeclaredMethod("run2"); m2.insertAt(22, "{ s = \"12\"; k = 5; }"); CtMethod m3 = cc.getDeclaredMethod("run3"); m3.instrument( new ExprEditor() { public void edit(NewExpr n) throws CannotCompileException { n.replace("{ i++; $_ = $proceed($$); }"); } public void edit(FieldAccess f) throws CannotCompileException { f.replace("{ i++; $_ = $proceed($$); }"); } public void edit(MethodCall m) throws CannotCompileException { m.replace("{ i++; $_ = $proceed($$); }"); } }); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(317, invoke(obj, "run")); assertEquals(7, invoke(obj, "run2")); assertEquals(3, invoke(obj, "run3")); }
public void testJIRA248() throws Exception { CtClass cc = sloader.get("test5.JIRA248"); String methodBody = "public int run() { return foo() + super.foo() + super.bar() + test5.JIRA248Intf2.super.baz(); }"; CtMethod ctMethod = CtMethod.make(methodBody, cc); cc.addMethod(ctMethod); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(40271, invoke(obj, "run")); }
/** * Creates a method. * * @param modifiers access modifiers. * @param returnType the type of the returned value. * @param mname the method name. * @param parameters a list of the parameter types. * @param exceptions a list of the exception types. * @param body the source text of the method body. It must be a block surrounded by <code>{} * </code>. If it is <code>null</code>, the created method does nothing except returning zero * or null. * @param declaring the class to which the created method is added. * @see Modifier */ public static CtMethod make( int modifiers, CtClass returnType, String mname, CtClass[] parameters, CtClass[] exceptions, String body, CtClass declaring) throws CannotCompileException { try { CtMethod cm = new CtMethod(returnType, mname, parameters, declaring); cm.setModifiers(modifiers); cm.setExceptionTypes(exceptions); cm.setBody(body); return cm; } catch (NotFoundException e) { throw new CannotCompileException(e); } }
public void testNewExprTry() throws Exception { ExprEditor ed = new ExprEditor() { public void edit(NewExpr expr) throws CannotCompileException { StringBuffer code = new StringBuffer(300); code.append("{ try "); code.append("{ $_ = $proceed($$); }"); code.append("catch (OutOfMemoryError e) {}}"); expr.replace(code.toString()); } }; CtClass cc = sloader.get("test2.NewExprTry"); CtMethod m1 = cc.getDeclaredMethod("foo"); m1.instrument(ed); cc.writeFile(); Object obj = make(cc.getName()); assertEquals(16, invoke(obj, "run")); }
public void testSetExceptions() throws Exception { CtClass cc = sloader.get("test2.SetExceptions"); CtMethod m = cc.getDeclaredMethod("f"); CtClass ex = m.getExceptionTypes()[0]; assertEquals("java.lang.Exception", ex.getName()); m.setExceptionTypes(null); assertEquals(0, m.getExceptionTypes().length); m.setExceptionTypes(new CtClass[0]); assertEquals(0, m.getExceptionTypes().length); m.setExceptionTypes(new CtClass[] {ex}); assertEquals(ex, m.getExceptionTypes()[0]); }