Contrôler l’ordre d’exécution des hooks dans Drupal

Contexte

Drupal et son mécanisme de hook permet de modifier le comportement par défaut du core ou d’autres modules depuis ses propres modules.

Pour chaque appel à une fonction hookable Drupal va rechercher dans tous les modules activés si ce module implémente ou non ce hook. Si un ou des modules implémentent le hook, Drupal va automatiquement les appeler.

Dans la majorité des cas, tout se passe bien, mais il arrive qu’on ait besoin de contrôler l’ordre d’exécution de ces hooks. Par exemple, lorsqu’un module A ajoute une fonctionnalité via un hook et qu’on souhaite modifier cet ajout dans un autre module B. Dans ce cas, il faut impérativement que le hook du module B soit appelé après celui du module A.

Continue reading

Développement web ,

Play Framework 2.0 – Premières impressions

Cet article à été publié sur le blog de Clever Age.

Vous pouvez le retrouver à cette adresse.

Développement web , , ,

Unit testing tricks for Play 2.0 and Ebean

Basic Ebean model testing

When you want to execute some tests that interact with your Models, you need to use a Play FakeApplication. This is described in the Java section of the Play 2.0 documentation.

Here is how the code looks like :

@Test
public void save() {
  running(fakeApplication(), new Runnable() {
    public void run() {
      // Here is your real test code
      Company company = new Company("My Company");
      company.save();
      assertThat(company.id).isNotNull();
    }
  });
}

As you can see, there is a lot of boilerplate code that we would like to avoid.

The easiest solution is to create a Test base class that will create de FakeApplication using a method annotated with @BeforeClass

Here is how the code could look like for the base class :

public class BaseModelTest {
  public static FakeApplication app;

  @BeforeClass
  public static void startApp() {
    app = Helpers.fakeApplication(Helpers.inMemoryDatabase());
    Helpers.start(app);
  }

  @AfterClass
  public static void stopApp() {
    Helpers.stop(app);
  }
}

You can then code your tests like this :

public class CompanyTest extends BaseModelTest {
  @Test
  public void save() {
    Company company = new Company("My Company");
    company.save();
    assertThat(company.id).isNotNull();
  }
}

Database cleaning

To keep my tests really independent of each other, I systematically clean the database before each test.

One solution to achieve that is to create a new FakeApplication before each test. This can be done by replacing the @BeforeClass / @AfterClass annotations with @Before / @After and removing the static keyword in the methods’ declarations.

It will work well but unfortunately, this will have a bad impact on the execution time. It can be ok if you only have a few tests, but when the number of tests will grow, it can become problematic. It would be nice to find a more efficient solution.

To avoid creating a FakeApplication for each test, we could just execute directely some drop table and create table SQL scripts. This should be faster.

I found an easy way to do that by reusing the evolution script generated by the EbeanPlugin class. Here is how we can do this :

public class BaseModelTest {
  public static FakeApplication app;
  public static String createDdl = "";
  public static String dropDdl = "";
  
  @BeforeClass
  public static void startApp() throws IOException {
    app = Helpers.fakeApplication(Helpers.inMemoryDatabase());
    Helpers.start(app);
    
    // Reading the evolution file
    String evolutionContent = FileUtils.readFileToString(
        app.getWrappedApplication().getFile("conf/evolutions/default/1.sql"));

    // Splitting the String to get Create & Drop DDL
    String[] splittedEvolutionContent = evolutionContent.split("# --- !Ups");
    String[] upsDowns = splittedEvolutionContent[1].split("# --- !Downs");
    createDdl = upsDowns[0];
    dropDdl = upsDowns[1];
    
  }

  @AfterClass
  public static void stopApp() {
    Helpers.stop(app);
  }
  
  @Before
  public void createCleanDb() {
    Ebean.execute(Ebean.createCallableSql(dropDdl));
    Ebean.execute(Ebean.createCallableSql(createDdl));
  }
}

Now before each test, you automatically have a database cleaned very quickly !

Here is a sample app illustrating this code : https://github.com/mguillermin/play2-ebean-testing

Note that if you have disabled evolutions, you will probably have to hack a little bit more to generate the create and drop scripts directly from Ebean. This is what is done in the EbeanPlugin.onStart() method.

IDE integration

Once you’ve correctly made your tests work with the FakeApplication, you might want to launch them directly from your IDE.

Why ?

Launching all your tests is easy with the command line. But when you want to launch a specific test class or method, it’s usually easier to use directly your IDE. You can then precisely select which tests to run, launch them in debug mode,…

The problem

If you try to do this on a test that use an Ebean entity, it will fail. Here is an example of what you will get :

java.lang.IllegalStateException: Class [class play.db.ebean.Model] is
enhanced and [class models.Company] is not - (you can not mix!!)

The problem is that your Model class is not enhanced by Ebean when you don’t launch your test from the Play console.

First solution : javaagent

Reading the Ebean reference guide , I found a way to automatically enhance your classes by using a specific javaagent.

All you have to do is to download Ebean, unzip it and then configure your IDE to add a JVM argument when launching the tests.

Here is how to do that with IntelliJ :

  • Go to the ‘Run’ / ‘Edit Configurations’ menu
  • Find the JUnit configuration under “Defaults”
  • Fill the ‘VM Options’ field with :
    -javaagent:/path/to/ebean/ebean-2.7.3-agent.jar
    

Play / Ebean / IntelliJ configuration

You can then enjoy running tests from your IDE.

Second solution : IDE plugin

If you use IntelliJ, there is an easier solution to enable enhancement automatically on your model classes. You will find in the plugin repository the Ebean weaver plugin that will do exactly what we want.

You just have to install it, restart, check the ‘Build’ / ‘Ebean weaving’ menu and that’s all.

Note that such a plugin exists also for Eclipse.

Conclusion

I hope that with these small tips and tricks, you will be able to enjoy even more discovering Play 2.0.

Développement web , , , ,

Appels asynchrones avec Play Framework

L’intégration de nouveaux composants permettant la gestion des appels asynchrones dans Play Framework a été récemment annoncé sur la mailing-list par Guillaume Bort. Ils ne sont pour l’instant pas disponible sur la version stable de Play, il faut donc récupérer la branche master pour les utiliser. En voici un rapide aperçu avec un exemple d’utilisation.

En résumé

Intégrés dans la librairie F ( play.libs.F ), ces nouveaux composants offrent, entre autre, la possibilité de mettre en pause une action jusqu’à ce qu’un événement se produise.

Lorsqu’on souhaite implémenter ce type de fonctionnalité, un problème se pose généralement : comme chaque requête est servie par un thread, si on suspend de manière simpliste les threads, on ne pourra pas avoir un nombre de clients supérieur au nombre de threads alloués au serveur. Même si il est possible d’augmenter le nombre de thread du serveur d’application, on ne peut pas le faire à l’infini et on ne peut que repousser le problème, pas l’éliminer.

L’implémentation réalisée dans Play permet de s’affranchir de cette barrière. Lors de la suspension de la requête, le thread est libéré automatiquement par le framework. Lorsque l’événement attendu survient, un thread est automatiquement réaffecté pour poursuivre la requête. Et c’est là que la magie opère : l’action reprend exactement à l’endroit où elle s’était arrêtée, de manière totalement transparente pour le développeur. Continue reading

Développement web , , ,

Utiliser Envers avec Play Framework

Ça fait un petit moment que je “joue” avec Play Framework (ok, elle était facile…) et ce que j’apprécie dans cet outil, c’est sa dualité.

Pour la majorité des besoins, on a tout ce qu’il faut sous la main et le framework est là pour nous faciliter la vie (pas besoin de définir les getters/setters, rechargement à chaud, serveur web intégré,…). On se retrouve alors très productif, à l’image de frameworks pur web comme symfony, RoR,…

Avec une telle productivité, ce qu’on oublierait presque, c’est qu’on est en train de faire du Java. Et si on fait du Java, ça veut dire qu’on a beaucoup beaucoup de librairies disponibles pour faire à peu près tout ce qu’on veut. C’est d’autant plus facile pour tout ce qui touche à l’accès aux données puisque Play repose sur JPA / Hibernate, La brique la plus utilisée dans ce domaine. Continue reading

Développement web , ,