0

I am writing a -javaagent to capture the HTTP request and response using Java's Instrumentation API such as javassist/ asm. I could insert the code around the method but how can I capture if the method is about to make a HTTP call and capture the HTTP request details, response code?

public static void premain(
    String agentArgs,
    Instrumentation inst
) throws IOException {

    inst.addTransformer((classLoader, className, classBeingRedefined, protectionDomain, classfileBuffer) -> {

        try {
            ClassPool cp = ClassPool.getDefault();

            CtClass cc = cp.get("other.Stuff");
            CtMethod m = cc.getDeclaredMethod("run");
            m.addLocalVariable("elapsedTime", CtClass.longType);
            m.insertBefore("elapsedTime = System.currentTimeMillis();");
            m.insertAfter(
            "{elapsedTime = System.currentTimeMillis() - elapsedTime;"
                        + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
            byte[] byteCode = cc.toBytecode();
            cc.detach();
            return byteCode;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    });
}
Vishrant
  • 15,456
  • 11
  • 71
  • 120
  • You'd need to read it from the method arguments as you would if you rewrote the method for your own purposes. – Rafael Winterhalter Oct 24 '20 at 21:27
  • While this is perfectly possible with ASM, ByteBuddy or Javassist, it looks like the perfect AspectJ use case. Did you look into that? It also features an optional Java agent and instruments your code on the fly, just in a less cryptic way IMO. P.S., it would be better to also include the target class into your question in order to enable everyone here to reproduce your situation. It is kind of difficult to reason about your `run` method without even having information about its signature and/or its content. – kriegaex Oct 25 '20 at 01:17
  • @RafaelWinterhalter @kriegaex, thanks for the input. I was able to write a javaagent to capture the parameters using `byte-buddy`, but having another weird issue that I have described in this question https://stackoverflow.com/questions/64530922/byte-buddy-transform-running-multiple-times-for-a-single-execution – Vishrant Oct 26 '20 at 02:50

0 Answers0