Posts Tagged ‘guice’

Firbease Guice Support Patched

Wednesday, September 14th, 2011 by larsan

We’ve just patched the Firebase Guice Support to 1.1.1. This patch contains a single bug fix: If you configure your game to use a table listener, this listener needed also to be a tournament table listener previously. But no more!

The new version is available on the Firebase download page.

Unit Tests with Guice and Warp Persist

Sunday, April 25th, 2010 by larsan

Yesterday I needed to do some unit testing for a project using Guice and Warp Persist. And one thing that seems to be lacking, or wasn’t to be found be me yesterday, is the kind of unit testing you can do with Spring, where each method is wrapped by a transaction which is rolled back when the method ends.

To simplify, it enables you to do this:

@Test
public void createUser() {
    User u = userService.createUserWithId(1);
}

@Test
public void createUserWithSameId() {
    User u = userService.createUserWithId(1);
}

If you assume the “userService” is transactional, we’re on a database that spans multiple methods, and that the user ID must be unique, the above pseudo-code should fail as we’re trying to create two users with the same ID. If, however, there was a transaction wrapping both methods, and that transaction was rolled back, we’d be fine.

So, can you do it with Guice and Warp Persist? Sure you can!

(I’m using TestNG and JPA by the way, but you’ll get the point).

We’ll create a base class that sets up the Guice context as well as handles the transactions for us. Let’s start with creating the methods we need:

public abstract class JpaTestBase {

  @BeforeClass
  public void setUpJpa() throws Exception {
    // setup guice + jpa here here
  }

  @AfterClass
  public void tearDownJpa() throws Exception {
    // stop jpa here
  }

  /**
   * Return the module needed for the test.
   */
  protected abstract List<? extends Module> testModules();

  @BeforeMethod
  public void setupTransaction() throws Exception {
    // create "session in view"
  }

  @AfterMethod
  public void cleanTransaction() throws Exception {
    // rollback transaction and close session
  }
}

We’re using the TestNG “before” and “after” class to setup and tear down JPA. If the test was in a bigger suite you could probably do it around all test classes, but this will do for now. I’m also including a “testModules” method that subclasses should use to make sure their own test classes are setup correctly.

Before we go on, I’ll add some dependencies which will be explained later:

@Inject
protected PersistenceService service;

@Inject
protected WorkManager workManager;

@Inject
protected Provider<EntityManagerFactory> emfProvider;

We’ll setup the Guice context and the JPA persistence service in the “setUpJpa” method:

@BeforeClass
public void setUpJpa() throws Exception {
  // create list with subclass modules
  List<Module> list = new LinkedList<Module>(testModules());

  // add persistence module
  list.add(PersistenceService
            .usingJpa()
            .across(UnitOfWork.REQUEST)
            .forAll(Matchers.annotatedWith(Transactional.class), Matchers.any())
            .buildModule());

  // modules to array and create Guice
  Module[] arr = list.toArray(new Module[list.size()]);
  injector = Guice.createInjector(arr);

  // make sure we get our dependencies
  injector.injectMembers(this);

  // NB: we need to start the service (injected)
  service.start();
}

The persistence service will work across UnitOfWork.REQUEST as that’s what we’re emulating here. I’m also matching the transaction for any classes, this enables me to mark an entire class as transactional, as opposed to single methods, which I find handy.

All we need to do to shut down is to close the service, like so:

@AfterClass
public void tearDownJpa() throws Exception {
  service.shutdown();
}

Now, let’s wrap the methods. Remember our dependency injections earlier? Well, here’s where they come in handy. The WorkManager is used by Warp Persist to manage a session, we can tell it to start and end “work” and this will correspond to an EntityManager bound to the current thread. Let’s start with that:

@BeforeMethod
public void setupTransaction() throws Exception {
  workManager.beginWork();
}

@AfterMethod
public void cleanTransaction() throws Exception {
  workManager.endWork();
}

So before each method we’ll open a new EntityManager which will be closed when the method ends. So far so good. Now, in order to enable a rollback when the method ends we first need to wrap the entire execution in a transaction, which means we need to get hold of the EntityManager. Luckily, Warp Persist has a class called ManagedContext which holds currently bound objects (a bit like a custom scope), in which we’ll find our EntityManager keyed to it’s persistence context, ie. the EntityManagerFactory that created it. Take a look again at the injected dependencies we injected above: As the test only handles one persistence context we can safely let Guice inject a Provider for an EntityManagerFactory for us and assume it is going to be the right one.

Still with me? OK, let’s do it then:

@BeforeMethod
public void setupTransaction() throws Exception {
  // begin work
  workManager.beginWork();
  // get the entity manager, using it's factory
  EntityManagerFactory emf = emfProvider.get();
  EntityManager man = ManagedContext.getBind(EntityManager.class, emf);
  // begin transaction
  man.getTransaction().begin();
}

@AfterMethod
public void cleanTransaction() throws Exception {
  // get the entity manager, using its factory
  EntityManagerFactory emf = emfProvider.get();
  EntityManager man = ManagedContext.getBind(EntityManager.class, emf);
  // rollback transaction
  man.getTransaction().rollback();
  // end work
  workManager.endWork();
}

And that’s it! Each test method is now within a transaction that will be rolled back when the method ends. Now all you need to do is to write the actual tests…

Guice Support in Firebase

Thursday, March 4th, 2010 by larsan

I’ve always wanted to add dependency injection support to Firebase, and today we released a candidate for Guice! And if you ask me, it’s very cool indeed.

The documentation is a bit sparse at the moment, but can be found on our wiki. The rest of the post I’ll just show how a small fictional game would look using Guice.

To start with, the Guice support comes in a set of abstract base classes, one for each Firebase artefact. And to use those you’d have to add a dependency to you Maven build (I’ll assume Maven here, you can of course use whatever you’d like):

<dependency>
  <groupId>com.cubeia.firebase</groupId>
  <artifactId>guice-support</artifactId>
  <version>1.0-RC.1</version>
</dependency>

And if you haven’t already got it, you’d need our repository as well:

<repository>
  <id>cubeia-nexus</id>
  <url>http://m2.cubeia.com/nexus/content/groups/public/</url>
  <releases>
    <enabled>true</enabled>
  </releases>
  <snapshots>
    <enabled>true</enabled>
  </snapshots>
</repository>

Now your all set to go, just extend GuiceGame and return the class of you game processor within the configuration, like so:

public class MyGame extends GuiceGame {
    public Configuration getConfigurationHelp() {
        return new ConfigurationAdapter() {
            public Class getGameProcessorClass() {
                return MyProcessor.class;
            }
        };
    }
}

So what’s the magic then? It is this: The class MyProcessor will be instantiated by Guice and can therefore contain injections. And further, it will be done in a custom scope, per event, thus isolating instances nicely.

You can also add your own modules to the injection context, again by overriding a method in GuiceGame:

protected void preInjectorCreation(List list) {
    list.add(new MyGameModule());
}

Which means, you can inject not only stuff from the current table but also, your own classes. So if we continue:

public class MyProcessor implements MyProcessor {

    /*
     * This is probably configured in the "MyGameModule" configured
     * in the guice game extension.
     */
    @Inject
    private MyHandler handler;

    /*
     * This is a speciality, you can inject Firebase services
     * right into your classes.
     */
    @Service
    private ScriptSupport support;

    /*
     * And another shortcut, if you use Log4j, we have a
     * a helper annotation for you...
     */
    @Log4j
    private Logger log;

    public void handle(GameDataAction action, Table table) {
        // do something here eh?
    }

    [...]

}

That should give you the idea. You can inject Firebase services as well as a logger (and remember, if you don’t use Log4j, Guice support the Java utility logging package from scratch). There’s a couple of things not shown here, for example, you can inject table members directly into the classes and the state object, so you don’t have to pass those around.

Any catch? Well, when you create your own modules you’ll need to keep in mind that the processor will only work in a custom scope, called EventScope. So if you have something which needs to be bound not as a singleton or in the default scope, you’ll probably need to do something like this:

bind(MyHandler.class).to(MyHandlerImpl.class).in(EventScoped.class);

And that’s it! In a few days we’ll release our script support, which is as you might imagine built on top of the Guice support. And so far? I love it!

Firebase CE – What’s next?

Tuesday, January 26th, 2010 by larsan

So, we’ve released Firebase Community Edition. Now there’s a Java game server which is open source and available to be used. Now what?

Well, here’s what! There’s a couple of things we’d like to get out of the door immediately and some of them will start appearing soon indeed:

  • Script support: Java 6 has build in support for JavaScript and can be extended to support a rather large list of script engines. We’d like to add support for writing your game using any of these script languages. We’d love to see the first Ruby+Flash game out there!
  • IDE support: We already have proto code for some Eclipse plugins lying about, and these should be polished up and released. Of course, you can always use our Maven archetypes and plugins, and then import into Eclipse, but direct support would be nice too. Of course, if anyone want to use NetBeans weed have to figure out something for you to eh?
  • Documentation: It’s sparse at the moment and needs to be fleshed out. We hope you’d like to help us here by simply telling us what is missing and asking us about all those things weäve forgotten to write down. Or indeed wasn’t explained properly.
  • IoC support: This is a biggy. Again we have proto code for for Guice lying about which needs to be fixed and published, but obviously we need to add direct support for Spring as well. Actually, you can write your components in Guice now but you’d have to wire it together yourself. Spring needs to be tested, so let us get back to you on that, ok?

And that’s what we want to do the immediate future. Watch this space, this is going to be fun!