Archive for the ‘code’ Category

JBoss 5 and AOP: how-to guide to add AOP aspects to your application


A quick example on how to add an interceptor to your application, for example to log or profile methods invocation:

  • Add “-javaagent:pluggable-instrumentor.jar” into JAVA_OPTS variable of file run.bat (or
  • Edit \conf\bootstrap\aop.xml and set the element enableLoadtimeWeaving to “true” and add to the element include the package you want to instrument
  • Create the jboss-aop.xml in the META-INF directory of your package like this:
<?xml version="1.0" encoding="UTF-8"?>
<aop xmlns="urn:jboss:aop-beans:1.0">
  <interceptor name="Int" class=""/>
  <bind pointcut="execution(* com.*->*(..))">
    <interceptor-ref name="Int"/>
  </bind >
  • Create the Interceptor class:
import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.MethodInvocation;
public class LogInterceptor implements Interceptor {
public String getName() {
  return "LogInterceptor";
public Object invoke(Invocation invocation) throws Throwable {
  long time=System.currentTimeMillis();
  try {
    return invocation.invokeNext();
  } finally {
    if (invocation instanceof MethodInvocation) {
      MethodInvocation mi = (MethodInvocation) invocation;
      String clazz="";
      try {
      } catch (Throwable e) {
        // TODO: handle exception
      //Here you can use a logger to log time and method name


Code snipplet


Some code snipplet useful everyday:

Read a file line by line:

InputStream in=this.getClass().getClassLoader().getResourceAsStream("aaa.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while(br.readLine()==null) { .... }

Integer to hexadecimal string:

String hex=Integer.toHexString(number);

Pretty Print XML Document:

org.w3c.dom.Document document=...;
try {
  javax.xml.transform.TransformerFactory tfactory = 
  javax.xml.transform.Transformer xform = tfactory.newTransformer();
  xform.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
  xform.setOutputProperty("{}indent-amount", "2"); writer = new;
  javax.xml.transform.Result result = 
  xform.transform(new javax.xml.transform.dom.DOMSource(document), result);
} catch (Exception e) {

Marshall JAXB to a file:

JAXBContext jaxbC;
try {
      jaxbC = JAXBContext.newInstance(jaxbClass.class);
      Marshaller marshaller = jaxbC.createMarshaller();
      marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
      marshaller.marshal(jaxbObject, new File("c:/aaa.txt"));
} catch (Exception e) {
      // TODO Auto-generated catch block

Print InputStream:

InputStream input=...;
byte[] buffer = new byte[1024];
int len =;
while (len != -1) {
    System.out.write(buffer, 0, len);
    len =;