private CtClass createControlClass(CtClass modifiedClass) throws Exception { CtClass patchClass = classPool.get(NameManger.getInstance().getPatchName(modifiedClass.getName())); patchClass.defrost(); CtClass controlClass = classPool.getAndRename(Constants.PATCH_TEMPLATE_FULL_NAME, NameManger.getInstance().getPatchControlName(modifiedClass.getSimpleName())); StringBuilder getRealParameterMethodBody = new StringBuilder(); getRealParameterMethodBody.append("public Object getRealParameter(Object parameter) {"); getRealParameterMethodBody.append("if(parameter instanceof " + modifiedClass.getName() + "){"); getRealParameterMethodBody. append("return new " + patchClass.getName() + "(parameter);"); getRealParameterMethodBody.append("}"); getRealParameterMethodBody.append("return parameter;}"); controlClass.addMethod(CtMethod.make(getRealParameterMethodBody.toString(), controlClass)); controlClass.getDeclaredMethod("accessDispatch").insertBefore(getAccessDispatchMethodBody(patchClass, modifiedClass.getName())); controlClass.getDeclaredMethod("isSupport").insertBefore(getIsSupportMethodBody(patchClass, modifiedClass.getName())); controlClass.defrost(); return controlClass; }
private void handleCompositeField(CtClass managedCtClass, CtField persistentField, CtMethod fieldWriter) throws NotFoundException, CannotCompileException { if ( !enhancementContext.isCompositeClass( persistentField.getType() ) || !PersistentAttributesHelper.hasAnnotation( persistentField, Embedded.class ) ) { return; } // make sure to add the CompositeOwner interface addCompositeOwnerInterface( managedCtClass ); // cleanup previous owner fieldWriter.insertBefore( String.format( "if (%1$s != null) { ((%2$s) %1$s).%3$s(\"%1$s\"); }%n", persistentField.getName(), CompositeTracker.class.getName(), EnhancerConstants.TRACKER_COMPOSITE_CLEAR_OWNER ) ); // trigger track changes fieldWriter.insertAfter( String.format( "if (%1$s != null) { ((%2$s) %1$s).%4$s(\"%1$s\", (%3$s) this); }%n" + "%5$s(\"%1$s\");", persistentField.getName(), CompositeTracker.class.getName(), CompositeOwner.class.getName(), EnhancerConstants.TRACKER_COMPOSITE_SET_OWNER, EnhancerConstants.TRACKER_CHANGER_NAME ) ); }
method.insertBefore(sb.toString());
fieldWriter.insertBefore( String.format( " if (this.%1$s != null && %2$s && $1 != null) { this.%1$s.%3$s(null); }%n", fieldWriter.insertBefore( String.format( " if (this.%3$s != null && %1$s) {%n" + fieldWriter.insertBefore( String.format( " if (this.%2$s != null && %1$s && this.%2$s.%3$s() != null) { this.%2$s.%3$s().remove(this); }%n", return; fieldWriter.insertBefore( String.format( " if (this.%2$s != null && %1$s) {%n" +
writer.insertBefore( String.format( " if (%1$s != null) { %1$s.callOwner(\"\"); }%n", writer.insertBefore( typeDescriptor.buildInLineDirtyCheckingBodyFragment( enhancementContext, persistentField ) );
public class FindUsageTransformer implements ClassFileTransformer{ Class clazz = null; public byte[] transform(ClassLoader loader,String className,Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if(className.equals("A")){ doClass(className, classBeingRedefined, classfileBuffer); } return classfileBuffer; } private byte[] doClass(String name, Class clazz, byte[] b) { ClassPool pool = ClassPool.getDefault(); CtClass cl = null; try { cl = pool.makeClass(new java.io.ByteArrayInputStream(b)); CtMethod method = cl.getDeclaredMethod("getA2"); // here you have lot of options to explore method.insertBefore("System.out.println(Thread.currentThread().getStackTrace()[0].getClassName()+ Thread.currentThread().getStackTrace()[0].getMethodName());"); b = cl.toBytecode(); } catch (Exception e) { System.err.println("Could not instrument " + name + ", exception : " + e.getMessage()); } finally { if (cl != null) { cl.detach(); } } return b; }
public static void addInstrumentation(CtClass ctClass, CtMethod ctMethod) throws NotFoundException, CannotCompileException { if (ctClass.getName().startsWith("com.application.bookstore.entities.test")) { String testName = ctClass.getName() + "." + ctMethod.getName(); String fileToWrite = "C:/profiler/root.txt"; ctMethod.insertBefore("{ com.application.bookstore.entities.test.ClassWithTheStaticField.lastTestMethod = " + testName + "; FileWriter fw = new FileWriter(\"" + fileToWrite + "\", true); BufferedWriter out = new BufferedWriter(fw); out.write(\"" + testName + "\"); out.newLine(); out.close(); }"); } else { String methodName = ctClass.getName() + "." + ctMethod.getName() + "()"; String fileToRead = "C:/profiler/root.txt"; ctMethod.insertBefore("{ FileWriter fw = new FileWriter(com.application.bookstore.entities.test.ClassWithTheStaticField.lastTestMethod, true); BufferedWriter out = new BufferedWriter(fw); out.write(\"" + methodName + "\"); out.newLine(); out.close(); }"); } }
@InitMethod static void initClass(CtClass c) throws CannotCompileException, NotFoundException { // add behavior to Widget.onAttach method CtMethod onAttach = c.getMethod("onAttach", "()V"); onAttach.insertBefore(GwtFinder.class.getName() + ".onAttach(this);"); // add behavior to RadioButton.setName method CtMethod onDetach = c.getMethod("onDetach", "()V"); onDetach.insertBefore(GwtFinder.class.getName() + ".onDetach(this);"); }
@InitMethod static void initClass(CtClass c) throws CannotCompileException, NotFoundException { // add behavior to Widget.onAttach method CtMethod onAttach = c.getMethod("onAttach", "()V"); onAttach.insertBefore(GwtFinder.class.getName() + ".onAttach(this);"); // add behavior to RadioButton.setName method CtMethod onDetach = c.getMethod("onDetach", "()V"); onDetach.insertBefore(GwtFinder.class.getName() + ".onDetach(this);"); }
ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("TestInstr"); CtMethod m = cc.getDeclaredMethod("sayHello"); m.insertBefore("{ System.out.println(\"method sayHello has been called\"); }"); cc.writeFile();
@InitMethod static void initClass(CtClass c) throws CannotCompileException, NotFoundException { CtMethod fireNativeEvent = c.getMethod( "fireNativeEvent", "(Lcom/google/gwt/dom/client/NativeEvent;Lcom/google/gwt/event/shared/HasHandlers;Lcom/google/gwt/dom/client/Element;)V"); // fire browser event loop first because some command or async callback may modify the DOM // structure + fire NativePreviewHandler fireNativeEvent.insertBefore(BrowserSimulatorImpl.class.getName() + ".get().fireLoopEnd(); " + DomEventPatcher.class.getName() + ".triggerNativeEvent($1, $3);"); // fire browser event loop at the end because some command may have been scheduled or RPC call // made when the event was dispatched. fireNativeEvent.insertAfter(BrowserSimulatorImpl.class.getName() + ".get().fireLoopEnd();"); }
private static void insertMetrics(CtClass fullDAOCtClass, CtMethod daoMethod, CtClass daoInterfaceCtClass) throws CannotCompileException, NotFoundException { final String timerField = createTimerField(fullDAOCtClass, daoMethod, daoInterfaceCtClass); logger.debug("Adding metrics to method " + daoMethod.getName() + "()"); daoMethod.addLocalVariable("__tc", ClassPool.getDefault().get(TimerContext.class.getName())); daoMethod.insertBefore("__tc = this." + timerField + ".time();"); daoMethod.insertAfter("__tc.stop();", false); }
private void modifyMethod(CtMethod method, CtClass returnTypeAsCtClass, String returnTypeAsString) throws CannotCompileException { final String returnValue = getCorrectReturnValueType(returnTypeAsCtClass); String classOrInstance = classOrInstance(method); String code = "Object value = " + mockGetawayClass.getName() + ".methodCall(" + classOrInstance + ", \"" + method.getName() + "\", $args, $sig, \"" + returnTypeAsString + "\");" + "if (value != " + MockGateway.class.getName() + ".PROCEED) " + "return " + returnValue + "; "; method.insertBefore("{ " + code + "}"); }
private void instrumentSetHTML(CtClass c) throws CannotCompileException { // add behavior to HasHTML.setHTML method try { CtMethod setHTML = c.getDeclaredMethod("setHTML", setArgs); addHTMLField(c); setHTML.insertBefore("this.instrument_oldHTML = this.getHTML();"); setHTML.insertAfter(GwtFinder.class.getName() + ".onSetHTML(this, $1, this.instrument_oldHTML);"); } catch (NotFoundException e) { // don't instrument method if not existing } }
private void instrumentSetText(CtClass c) throws CannotCompileException { // add behavior to HasHTML.setHTML method try { CtMethod setText = c.getDeclaredMethod("setText", setArgs); addTextField(c); setText.insertBefore("this.instrument_oldText = this.getText();"); setText.insertAfter(GwtFinder.class.getName() + ".onSetText(this, $1, this.instrument_oldText);"); } catch (NotFoundException e) { // don't instrument method if not existing } }
private void instrumentSetText(CtClass c) throws CannotCompileException { // add behavior to HasHTML.setHTML method try { CtMethod setText = c.getDeclaredMethod("setText", setArgs); addTextField(c); setText.insertBefore("this.instrument_oldText = this.getText();"); setText.insertAfter(GwtFinder.class.getName() + ".onSetText(this, $1, this.instrument_oldText);"); } catch (NotFoundException e) { // don't instrument method if not existing } }
private void instrumentSetHTML(CtClass c) throws CannotCompileException { // add behavior to HasHTML.setHTML method try { CtMethod setHTML = c.getDeclaredMethod("setHTML", setArgs); addHTMLField(c); setHTML.insertBefore("this.instrument_oldHTML = this.getHTML();"); setHTML.insertAfter(GwtFinder.class.getName() + ".onSetHTML(this, $1, this.instrument_oldHTML);"); } catch (NotFoundException e) { // don't instrument method if not existing } }
public static void main(String args[]){ ClassPool pool = ClassPool.getDefault(); pool.insertClassPath( "c:/Test.jar" ); CtClass cc = pool.get("com.test.TestFunction"); CtMethod m = CtNewMethod.make("public void test2() { System.out.println(\"test2\"); }", cc); cc.addMethod(m); CtMethod cm = cc.getDeclaredMethod("test1", new CtClass[0]); cm.insertBefore("{ test2();}"); byte[] b = cc.toBytecode(); // convert the new class to bytecode. pool.removeClassPath(cp); // need to remove the classpath to release connection to JAR file so we can update it. JarHandler jarHandler = new JarHandler(); jarHandler.replaceJarFile("C:/Test.jar", b, "com/test/TestFunction.class"); }
ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("testjavasisit.Hello"); cc.defrost(); CtMethod m = cc.getDeclaredMethod("say"); m.insertBefore("{ System.out.println(\"Hello11.say():\"); }"); cc.writeFile("build"); cc.toClass(); Hello h2 = new Hello(); h2.say();
@Override public void preInit() { ModActions.init(); try { ClassPool classPool = HookManager.getInstance().getClassPool(); CtClass ctAction = classPool.get("com.wurmonline.server.behaviours.Action"); HookManager.getInstance().addCallback(ctAction, "testModApi", this); CtMethod ctPoll = ctAction.getMethod("poll", Descriptor.ofMethod(CtClass.booleanType, new CtClass[0])); ctPoll.insertBefore("testModApi.pollAction(this);"); } catch (Exception e) { throw new HookException(e); } }