Volume: 6 Issue: 3
Using The Java Platform Debugger Architecture
by Tony Loton


Listing 1
Connector connector=null;
List connectors=Bootstrap.virtualMachineManager().allConnectors();
Iterator iter=connectors.iterator();
while (iter.hasNext())
{
  Connector thisConnector=(Connector)iter.next();
  if (thisConnector.name().equals("com.sun.jdi.SocketAttach"))
   connector=thisConnector;
}



Listing 2
Map arguments=connector.defaultArguments();
for (Iterator itr=arguments.keySet().iterator(); itr.hasNext();)
{
  Connector.Argument argument=(Connector.Argument)
  arguments.get(itr.next());
}
Connector.Argument host=(Connector.Argument) arguments.get("hostname");
Connector.Argument port=(Connector.Argument) arguments.get("port");
host.setValue("targetMachine");
port.setValue("8000");


Listing 3
AttachingConnector attacher=(AttachingConnector) connector;
try { vm=attacher.attach(arguments); }
catch (Exception e) {//error}


Listing 4
EventRequestManager em=vm.eventRequestManager();
MethodEntryRequest meR=em.createMethodEntryRequest();
meR.addClassFilter("mypckg.*");
meR.enable();


Listing 5
EventQueue eventQ=vm.eventQueue();
while (running)
{
  EventSet eventSet=null;


  try { eventSet=eventQ.remove(); }
  catch (Exception e) { // handle the error }


  EventIterator eventIterator=eventSet.eventIterator();
  while (eventIterator.hasNext())
  {
   Event event=eventIterator.nextEvent();


   if (event instanceof MethodEntryEvent) { // process this event }
   vm.resume();
  }
}


Listing 6
String methodString=event.method().toString();
ThreadReference thread=event.thread();
List stackList=thread.frames();
int level=0;
for (Iterator it=stackList.iterator(); it.hasNext();)
{
  StackFrame stackFrame=(StackFrame) it.next();
  ObjectReference thisObject=stackFrame.thisObject();
  if (level==0)
   { calleeClass=thisObject.referenceType().toString(); }
  else if (level==1)
   { callerClass=thisObject.referenceType().toString(); }
}


Listing 7
Connector.Argument opts=(Connector.Argument) arguments.get("options");
Connector.Argument main=(Connector.Argument) arguments.get("main");
Connector.Argument susp=(Connector.Argument) arguments.get("suspend");


main.setValue("MyApplication arg1 arg2");
susp.setValue("false");


LaunchingConnector launcher=(LaunchingConnector) connector;


try
{
  vm=launcher.launch(arguments);
  process=vm.process();
  displayRemoteOutput(process.getErrorStream());
  displayRemoteOutput(process.getInputStream());
}
catch (Exception e) { // error }