Wednesday, December 14, 2011

Aspects and Maven

Many times you might want to implement restrictions on what developers are allowed to do. For instance, you might want to prohibit the usage of System.out in Java EE applications.

One way is to add triggers in your version control system. Another way is to add aspects. This short how to shows what you need to do the get aspects working.


Step 1

Create a new project, and add it to the super pom. Thus if you want to build a book application your super pom might look like this;

book-jar

book-war

Now add the new project which will contain your aspects, call it for instance aspect (or whatever).

your super pom shall look like this now;

book-jar

book-war

aspect


Create the aspect project with normal directory structure.

src/main/java/org/aja/aspect/

In the aspect directory we shall add our restriction;

Let's call it DoNotPrint.aj


File DoNotPrint.aj

public aspect DoNotPrint {

private pointcut withinBook() : within(org.aja..*);

declare error:
withinBook() &&
get(* System.out):
"Accessing System.out is not allowed.";

declare error:
withinBook() &&
get(* System.err):
"Accessing System.err is not allowed.";

declare error:
withinBook() &&
call(* java.lang.Throwable.printStackTrace()):
"Calling Throwable.printStackTrace() is not allowed.";
}

The file says that it shall weave all files in the package structur org.aja and send an error when it finds a System.out. Change decalre error to declare warning if you think that is sufficient.


Now manipulate the pom.xml in the aspect project. The super pom is finished.

Step 1, add a dependency to the proper aspect jar and all projects we shall weave


aspectj
aspectjrt
1.5.2a
provided


org.aja
book-jar
1.0.0
provided


org.aja
book-war
1.0.0
provided

So, we added both a dependency to the aspect jar which is needed for all operations and the two projects we want to verify, or weave.


Add this to the build tag.




org.codehaus.mojo
aspectj-maven-plugin



compile




1.5
1.5


org.aja
book-jar


org.aja
book-jar







That's it. Everytime you stand in the top of the project and build the book-jar, book-war and aspect it will browse through all your classes and the build will fail with an error message if it finds any instances of System.out in the code.

0 comments:

Post a Comment