Revisiting Guice and AOP with AspectJ
I decided to revisit my article on Guice and AOP with AspectJ instead of the AOP Alliance API that Guice comes with.
The full source code is available on GitHub.
To refresh your memory, we had implemented a declarative approach for controlling the access to a class methods through annotations:
@WithUserProfileVerification public class InMemoryContactManager implements ContactManager { private final Set<Person> contacts = new HashSet<Person>(); @RequiresProfile(ADMIN) public ContactManager add(Person person) { contacts.add(person); return this; } @RequiresProfile(ADMIN) public ContactManager remove(Person person) { contacts.remove(person); return this; } @RequiresProfile(USER) public Person lookup(String name) { for (Person person : contacts) { if (person.getName().equals(name)) { return person; } } return null; } }
First off AspectJ is way more expressive than the AOP Alliance API. Using Guice with AspectJ is not very different. If your aspects do not need injection then you fall back to plain AspectJ development, as Guice and AspectJ live apart from each other. Things are a little more subtile if you need to connect Guice with your aspects.
In our case we had one aspect that needed injection, hence the trick is to ask Guice to perform injection on the aspect instance. By default, an AspectJ aspect is a singleton, so all we need is to grab an access to the instance, which is as simple as calling the Aspects#aspectOf() static method.
Now let's see some code that differs from the Guice / AOP Alliance sample I showed you.
Here is how you can define a simple dirty console logger that hooks itself onto any implementation of the ContactManager interface:
package info.ponge.julien.hacks.guiceaspectj.aspects; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class ContactManagerLogger { @Before("call( * info.ponge.julien.hacks.guiceaspectj.contact.ContactManager.*(..) )") public void methodCalled(JoinPoint thisJoinPoint) { System.out.println("Calling: " + thisJoinPoint.getSignature().getName()); } }
The aspect that checks for the user permissions is implemented as follows:
package info.ponge.julien.hacks.guiceaspectj.aspects; import com.google.inject.Inject; import info.ponge.julien.hacks.guiceaspectj.auth.RequiresProfile; import info.ponge.julien.hacks.guiceaspectj.auth.UserProfile; import info.ponge.julien.hacks.guiceaspectj.auth.UserProfileChecker; import info.ponge.julien.hacks.guiceaspectj.auth.WithUserProfileVerification; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import static info.ponge.julien.hacks.guiceaspectj.auth.UserProfile.ADMIN; import static info.ponge.julien.hacks.guiceaspectj.auth.UserProfile.USER; @Aspect public class ProfileVerification { @Inject UserProfileChecker userProfileChecker; @Before("execution( * *(..) ) && @annotation( required ) && within( @WithUserProfileVerification * )") public void verify(RequiresProfile required) { UserProfile expected = required.value(); UserProfile current = userProfileChecker.getCurrentUserProfile(); if (insufficientProfile(expected, current)) { throw new RuntimeException("The current user profile (" + current + ") is not sufficient: " + required); } } private boolean insufficientProfile(UserProfile required, UserProfile current) { return (required == ADMIN && current != ADMIN) || (required == USER && (current != USER && current != ADMIN)); } }
Finally our Guice module is configured to perform the injection on the singleton that corresponds to the previous aspect:
package info.ponge.julien.hacks.guiceaspectj; import com.google.inject.*; import info.ponge.julien.hacks.guiceaspectj.aspects.ProfileVerification; import info.ponge.julien.hacks.guiceaspectj.auth.UserProfileChecker; import info.ponge.julien.hacks.guiceaspectj.auth.dumb.DumbUserProfileChecker; import info.ponge.julien.hacks.guiceaspectj.contact.ContactManager; import info.ponge.julien.hacks.guiceaspectj.contact.Person; import info.ponge.julien.hacks.guiceaspectj.contact.simple.InMemoryContactManager; import org.aspectj.lang.Aspects; import static org.aspectj.lang.Aspects.*; public class Main { public static void main(String[] args) { new Main().execute(); } private Module guiceModule = new AbstractModule() { @Override protected void configure() { bind(ContactManager.class) .to(InMemoryContactManager.class) .in(Singleton.class); bind(UserProfileChecker.class) .to(DumbUserProfileChecker.class) .in(Singleton.class); requestInjection(aspectOf(ProfileVerification.class)); } }; private Injector injector = Guice.createInjector(guiceModule); private void execute() { ContactManager contacts = injector.getInstance(ContactManager.class); UserProfileChecker profileChecker = injector.getInstance(UserProfileChecker.class); profileChecker.login("Julien", "secret"); contacts.add(new Person("Julien Ponge", "julien.ponge@gmail.com")); contacts.add(new Person("Jean-Jacques", "jean.jacques@gmail.com")); profileChecker.logout(); profileChecker.login("Jean-Jacques", "1234"); System.out.println(contacts.lookup("Julien Ponge")); profileChecker.logout(); contacts.add(new Person("Mr Bean", "mrbean@gmail.com")); } }
As one would expect, trying to add Mr Bean fails due to insufficient permissions:
Calling: add Calling: add Calling: lookup Julien PongeCalling: add Exception in thread "main" java.lang.RuntimeException: The current user profile (ANONYMOUS) is not sufficient: @info.ponge.julien.hacks.guiceaspectj.auth.RequiresProfile(value=ADMIN) at info.ponge.julien.hacks.guiceaspectj.aspects.ProfileVerification.verify(ProfileVerification.java:27) at info.ponge.julien.hacks.guiceaspectj.contact.simple.InMemoryContactManager.add(InMemoryContactManager.java:21) at info.ponge.julien.hacks.guiceaspectj.Main.execute(Main.java:54) at info.ponge.julien.hacks.guiceaspectj.Main.main(Main.java:17)
IzPack 4.3.3 released
On behalf of the IzPack project development team, I am pleased to announce the immediate availability of IzPack 4.3.3 which can be downloaded from our official website at http://izpack.org/.
This ia a stable, maintenance release that fixes some issues found in IzPack 4.3.1 and IzPack 4.3.2. As such, we highly recommend that our users promptly migrate to this version from production-quality installers.
7 issues were fixed in this release. See http://jira.codehaus.org/browse/IZPACK/fixforversion/15986 for a complete list and more details.
Should you encounter issues in IzPack 4.3.3, please go to http://jira.codehaus.org/browse/IZPACK to look for similar issues, and eventually report a new problem.
We would like to thank our developers, contributors, issue reporters and users for making this release possible!
Enjoy.
— Julien Ponge, IzPack project founder
JOnAS 5 and IzPack
I was giving JOnAS 5 a try today, and I could verify what I told in a conference last week: you are always the last person to know when people use your software
The installer launches from Java WebStart and guides you through all the steps to get a JOnAS application server ready. I took a few screenshots.
Well done guys, really!
Guice it up (or AOP can be made simple sometimes)
I have been knowing about the Google Guice dependency injection container features for quite some time. Guice is a really pleasant DI framework that does its job with brilliant simplicity from a developer point of view (oh yes, and you don't have to describe the classes wiring in a dumb XML file like Spring does).
Guice has more than DI capabilities though, as long as you spice it up with extensions libraries. Today I'll show you the AOP capabilities that Guice offers.
I must admit that I have always been puzzled by this thing called aspect-oriented programming. While the idea of separating actual code from cross-cutting concerns (e.g., security, transactions) makes a lot of sense, one may easily end-up writing spaghetti code.
If you don't believe me, have a look at Spring ROO, I am really curious to know if one can come up with serious arguments for not calling that mess of Java, AspectJ and Spring XML oddities "spaghetti code".
Anyway, AOP flourished rapidly a few years back, as advanced developers, methodologists and event academics all went crazy about it through books, frameworks and claims of the death of OOP. The good news is that for a change, the AOP hype faded away in a flashlight (I whish the same could have been true for those silly things called SOAP and BPEL). However, AOP is still very useful in non-dynamic languages like Java, and reasonable use can make code quite elegant.
Let's get back to Guice, as I will quickly go through some code snippets. I wanted to play with Guice through the trivial use-case of a declaratively access-restricted contacts manager. The code that you will see exhibits AOP and DI features in Guice. As far as the quality is concerned, it will show you the approach, but in an industrial case one would of course need something a bit more elaborated.
First of all, I created a wonderful Person model class:
package app; public class Person { private final String name; private final String email; public Person(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { return new StringBuffer(name) .append(" <") .append(email) .append(">") .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (!email.equals(person.email)) return false; if (!name.equals(person.name)) return false; return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + email.hashCode(); return result; } }
Disgression: it would have been much more concise in Scala or Groovy.
I then designed a ContactManager interface:
package app; public interface ContactManager { public ContactManager add(Person person); public ContactManager remove(Person person); public Person lookup(String name); }
Note that I made it minimalistically fluent so that add and remove calls could be chained.
I then wanted to design a basic access control mechanism, so that an implementation of ContactManager could declaratively restrict its access to a certain type of user profile, much like what we can do with EJB 3.x (incidentally, good implementations like Glassfish use AOP and bytecode engineering under the hood).
Hence, I designed annotations to let classes and methods specify access-control policies:
package app.auth; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface WithUserProfileVerification { }
and
package app.auth; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RequiresProfile { UserProfile value(); }
along with a user profile enumeration (anonymous user, regular user and administrator):
package app.auth; public enum UserProfile { ANONYMOUS, USER, ADMIN }
Now we are able to define a basic ContactManager implementation with declarative access-control policies:
package demo; import app.ContactManager; import app.Person; import app.auth.RequiresProfile; import static app.auth.UserProfile.ADMIN; import static app.auth.UserProfile.USER; import app.auth.WithUserProfileVerification; import java.util.HashSet; import java.util.Set; @WithUserProfileVerification public class ContactManagerImpl implements ContactManager { private final Set<Person> contacts = new HashSet<Person>(); @RequiresProfile(ADMIN) public ContactManager add(Person person) { contacts.add(person); return this; } @RequiresProfile(ADMIN) public ContactManager remove(Person person) { contacts.remove(person); return this; } @RequiresProfile(USER) public Person lookup(String name) { for (Person person : contacts) { if (person.getName().equals(name)) { return person; } } return null; } }
From this definition, anonymous users cannot do anything, regular users can perform lookups and administrators can add/remove contacts.
This can be summarized by this class diagram:

The next question is of course: how do you make that actually work?
First, let's design a profile checker interface along with a dumb implementation:
package app.auth; public interface UserProfileChecker { public UserProfile getCurrentUserProfile(); public UserProfile login(String login, String password); public UserProfile logout(); }
package demo; import app.auth.UserProfile; import static app.auth.UserProfile.*; import app.auth.UserProfileChecker; public class DumbUserProfileChecker implements UserProfileChecker { private UserProfile userProfile = ANONYMOUS; public UserProfile getCurrentUserProfile() { return userProfile; } public UserProfile login(String login, String password) { if (login.equals("Julien") && password.equals("secret")) { userProfile = ADMIN; } else if (login.equals("Jean-Jacques") && password.equals("1234")) { userProfile = USER; } else { userProfile = ANONYMOUS; } return getCurrentUserProfile(); } public UserProfile logout() { userProfile = ANONYMOUS; return userProfile; } }

Sounds great isn't it?
Still, the link is missing between our contact manager implementation, and this user profile checker.
The idea is to design an aspect for that: each class that uses our declarative access-control policies will have method calls beeing intercepted by the aspect. Here is the code:
package demo; import app.auth.RequiresProfile; import app.auth.UserProfile; import static app.auth.UserProfile.ADMIN; import static app.auth.UserProfile.USER; import app.auth.UserProfileChecker; import com.google.inject.Inject; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class UserProfileInterceptor implements MethodInterceptor { @Inject private UserProfileChecker profileChecker; public Object invoke(MethodInvocation methodInvocation) throws Throwable { UserProfile required = methodInvocation.getMethod().getAnnotation(RequiresProfile.class).value(); UserProfile current = profileChecker.getCurrentUserProfile(); if (insufficientProfile(required, current)) { throw new RuntimeException("The current user profile (" + current + ") is not sufficient: " + required); } else { return methodInvocation.proceed(); } } private boolean insufficientProfile(UserProfile required, UserProfile current) { return (required == ADMIN && current != ADMIN) || (required == USER && (current != USER && current != ADMIN)); } }
The user profile checker will be injected by Guice in the aspect (see the @Inject annotation). The interesting work is performed by the invoke method that looks at the required user profile (through the invoked method annotation) and checks it against the user profile checker. When the profile matches, the method actually gets invoked, otherwise a RuntimeException is raised.
From there what is missing is simply the Guice wiring definitions. Before we look at that, I also designed an aspect for logging method calls (hence, we will inject two aspects):
package demo; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import java.util.logging.Level; import java.util.logging.Logger; public class LoggingInterceptor implements MethodInterceptor { private Logger logger = Logger.getLogger(LoggingInterceptor.class.getName()); public Object invoke(MethodInvocation methodInvocation) throws Throwable { logger.logp( Level.INFO, methodInvocation.getClass().getName(), methodInvocation.getMethod().getName(), "invocation", methodInvocation.getArguments()); Object result = null; try { result = methodInvocation.proceed(); } finally { logger.logp( Level.INFO, methodInvocation.getClass().getName(), methodInvocation.getMethod().getName(), "return", result); return result; } } }

Finally, here is the Main class that has the Guice wiring configuration and a simple use-case:
package demo; import app.ContactManager; import app.Person; import app.auth.RequiresProfile; import app.auth.UserProfileChecker; import app.auth.WithUserProfileVerification; import com.google.inject.*; import static com.google.inject.matcher.Matchers.*; public class Main { public static void main(String[] args) { new Main().execute(); } private Module guiceModule = new AbstractModule() { @Override protected void configure() { bind(ContactManager.class) .to(ContactManagerImpl.class) .in(Singleton.class); bind(UserProfileChecker.class) .to(DumbUserProfileChecker.class) .in(Singleton.class); UserProfileInterceptor userProfileInterceptor = new UserProfileInterceptor(); requestInjection(userProfileInterceptor); bindInterceptor( annotatedWith(WithUserProfileVerification.class), annotatedWith(RequiresProfile.class), userProfileInterceptor); bindInterceptor( subclassesOf(ContactManager.class), any(), new LoggingInterceptor()); } }; private Injector injector = Guice.createInjector(guiceModule); private void execute() { ContactManager contacts = injector.getInstance(ContactManager.class); UserProfileChecker profileChecker = injector.getInstance(UserProfileChecker.class); profileChecker.login("Julien", "secret"); contacts.add(new Person("Julien Ponge", "julien.ponge@gmail.com")); contacts.add(new Person("Jean-Jacques", "jean.jacques@gmail.com")); profileChecker.logout(); profileChecker.login("Jean-Jacques", "1234"); System.out.println(contacts.lookup("Julien Ponge")); } }

You can easily modify the execute method call to check that access-control is enforced (e.g., have an anonymous user attempt to add an entry and see that an exception is raised).
The wiring defined in the module configuration is straightforward. One should only pay attention to the requestInjection(userProfileInterceptor) call. Indeed, aspects are not managed by the DI container. As we request an injection in the corresponding class, this call will make it on-demand.
As we saw in this small showcase, Google Guice is a very compelling DI framework with simple and efficient AOP capabilities.
Don't you think so?













