Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Byteman - Carving up your Java code

Byteman - Carving up your Java code

Brown Bag talk I gave on first steps with Byteman.

Chris Sinjakli

March 01, 2012

More Decks by Chris Sinjakli

Other Decks in Programming


  1. Java Agent API package java.lang.instrument; interface ClassFileTransformer { byte[] transform(ClassLoader

    loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer); }
  2. Who does this? • About a million tutorials – Usually

    print the class name – At best adding simple trace code to methods • Newer, cooler mocking frameworks – Powermock, Mockito, JMockit – Better approach then JMock & friends (which use Proxy + CGLIB) – Mock final classes/methods, plus other stuff • Pure Java profilers?
  3. How? • Specify byteman.jar as a Java Agent when you

    start your app • Provide a Byteman rule script • Can provide these scripts later (to a running app) – app must be started with Byteman listener
  4. Simple program package org.my class AppMain { public static void

    main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } } }
  5. Byteman rule script RULE trace main entry CLASS AppMain METHOD

    main AT ENTRY IF true DO traceln("entering main") ENDRULE
  6. Byteman rule script RULE trace main exit CLASS AppMain METHOD

    main AT EXIT IF true DO traceln("exiting main") ENDRULE
  7. Worth mentioning • You can use it on classes you

    don’t have the source for • You can even use this on core Java classes (java.lang) – Byteman makes you confirm • Works on interfaces too (all implementing classes get your injected code) • Much more sophisticated rule scripts – Different “AT” points in method – “IF” statements that do something – Access to local variables (eg “AFTER WRITE $foo”)
  8. Testing support • Comes with a JUnit Runner • Define

    the rules (from earlier scripts) as test annotations • Useful for fault injection (integration tests where you’re not mocking everything out?)
  9. Testing support @Test @BMRule(name=“foo”, targetClass = “FileInputStream”, targetMethod=“<init>(File)”, condition=“$1.getName().equals(\“doesnt_exist.txt\”)”, action=“throw

    new FileNotFoundException(\“It’s not there!\”)”) public void testReadFile() { ... myClass.processFile(“doesnt_exist.txt”); // Throws an exception ... }
  10. Testing support • Rule in previous example will only be

    in place for that test – Can annotate class instead to apply to all tests • There’s also @BMScript to import external rule scripts • Relatively simple to run with maven (config samples on website)
  11. Summary • Seems cool • Not sure what I’d actually

    use it for • Integration tests most likely candidate