JPz'log Coin Coin and Plop da Plop

4Nov/0912

Guice it up (or AOP can be made simple sometimes)

Juice

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:

guiceaop-1

Cables

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;
    }
 
}

guiceaop-2

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;
        }
    }
 
}

guiceaop-3

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"));
    }
 
}

guiceaop-4

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? :-)

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Live
  • Netvibes
  • StumbleUpon
  • Technorati
  • FriendFeed
  • Wikio
  • Twitter
  • Identi.ca
  • Reddit
  • RSS
  • Slashdot

Related posts:

  1. Revisiting Guice and AOP with AspectJ
  2. Playing with Berkeley DB Java Edition and Guice
  3. Groovy and EJBs
  4. I like Spring WS (or SOAP made right)
  5. Initialization blocks in Java

Comments (12) Trackbacks (0)
  1. This approach is incredibly slow relatively to the access costs but maybe that was not on you mind considering you even make logger calls which I fail to see the point for inclusion.

    AspectJ can do this much faster if none of the execution context associated with the join point needs to be accessed other than the static part. AOP alliance API was poorly designed in this regard but then again performance has never been a consideration for Spring religious leaders.

    • Hi William,

      The point is NOT to show a logger aop example. It shows how Guice does AOP on a simple access control scenario with declarative annotations.

      BTW Guice is fast compared to Spring and uses bytecode engineering.

      Cheers

      • Please think about this before making such “fast compared” to statements. I said AspectJ not Spring. God forbid I would say Spring is fast.

        MethodInvocation is flawed because it extends from the Invocation interface in the “alliance against efficiency” package which includes the arguments with the target object accessible with the JoinPoint super interface. The Interceptor is around based.

        @Around + @This @Arguments => Very, very slow relative to a @Before & @After with no context bindings. Not to mention we are also increasing the call stack depth which adds it own set of problems in diagnostics.

  2. In LoggingInterceptor, are you sure that methodInvocation.getClass().getName() is what you want to log ? If not, does methodInvocation.getMethod().getDeclaringClass().getName() works ?

  3. Not that bad… even very interesting example!

  4. Thanks guys for your useful comments!

    However please keep in mind that this is just a quick qnd dirty test of Guice AOP features.

  5. please do me a favour and try to implement the same with aspectj (preferably using its native syntax). others noted the performance issue with this solution but much more generally, I don’t think a DI framework was made for that (aspectj was). I bet you’ll find the code accomplishing the same much easier as well..

  6. Looks like your are swallowing possible exceptions in your log aspect. Your return statement should be inside the try block and there should be no return in the finally.
    But nice article anyway.


Leave a comment


No trackbacks yet.

JPz'log is Digg proof thanks to caching by WP Super Cache