15 January 2014

More Btrace debugging

In the post http://blog.lesc.se/2009/06/btrace-debugging-tool-with-bugs.html I wrote about how it is possible to debug a running Java application. Here is some more magic.

Let say you have this simple program:

import javax.swing.JFrame;

public class SimpleApp {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Simple application");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 100);
    frame.setVisible(true);
  }
}


And this Btrace script:
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
import java.awt.EventQueue;
import java.awt.AWTEvent;
import java.awt.event.MouseEvent;
import java.lang.reflect.Field;

@BTrace
public class SimpleAppMouseTracer {
  @OnMethod(
     clazz="java.awt.EventQueue",
     method="dispatchEvent"
  )
  public static void onevent(@Self EventQueue queue, AWTEvent event) {
    if (event instanceof MouseEvent) {
      MouseEvent mouseEvent = (MouseEvent) event;
      Field idField = field("java.awt.AWTEvent", "id");
      Field xField = field("java.awt.event.MouseEvent", "x");
      Field yField = field("java.awt.event.MouseEvent", "y");
      if (getInt(idField, mouseEvent) == MouseEvent.MOUSE_CLICKED) {
        println(
          strcat("x = ", strcat(str(getInt(xField, mouseEvent)),
          strcat(", y = ", str(getInt(yField, mouseEvent))))));
      }
    }
  }
}


I have installed the Btrace into Java VisualVM (I downloaded and installed all the visualvm plugins from https://kenai.com/projects/btrace/downloads).

 


Each time I click with the mouse inside the Window I get a printout with the mouse coordinates.

The Btrace code is Java, but with many restrictions. That is why the String creation code gets a bit large; because build in Btrace functions must be used. The same goes for accessing variables inside the MouseEvent object.

No comments:

Post a Comment