Kontakt

Last year JetBrains announced Kotlin – a statically-typed JVM-targeted programming language. The web-based Kotlin preview has been launched recently. Check out this demo to get the first impression.

I got curious about the Kotlin programming language and attended a talk by Andrey Breslav at Devoxx 2011. Today I’m one of the lucky guys who got the access to the private EAP. After experimenting with Kotlin I decided to write a series of articles about this language in order to share with you my experience. This article is the first one and covers a basic “Hello, world” example. Let’s dive in.

Initial Java program

First we will create a Java program that we later convert into Kotlin. Here is our “Hello, world!” example in Java.

package hello;

public class HelloWorld {
    private String name;

    public HelloWorld(String name) {
        this.name = name;
    }

    public String greet() {
        return "Hello, " + name;
    }

    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorld("Kotlin");

        System.out.println(helloWorld.greet());
    }
}

An equivalent Kotlin program

Now let’s convert this example into a Kotlin program.

package hello

class HelloWorld(var name: String){

    fun greet(): String {
        return "Hello, $name"
    }
}

fun main(args: Array<String>) {
    var helloWorld = HelloWorld("Kotlin")

    System.out?.println(helloWorld.greet())
}

This tiny Kotlin program demonstrates a couple of Kotlin features. Let’s start with the constructor.

Primary constructors

In Kotlin you may declare constructors immediately in the class declaration. Note that the constructor in the example above initializes class properties without having a body. Such constructors are called primary constructors.

Properties

Do properties in Kotlin have the same meaning as in Java? In contrast to Java, Kotlin classes don’t have fields that are read/written using getters and setters. Instead Kotlin classes have properties: mutable properties are declared with the var (for variable) keyword and read-only properties are declared with the val (for value) keyword. In the example above the HelloWorld class has a mutable property named name. Note that the property is declared directly in the constructor. Because the property has been declared with var keyword, we can alter its value, as shown in the following example.

var helloWorld = HelloWorld("Kotlin")
helloWorld.name = "Kotlin again"

The value of the property may be changed by assigning it directly to the property. If we would have declared the property using then val keyword, assigning a new value would result in a compiler error. Also please note that there’s no new keyword in Kotlin.

Functions

Kotlin classes have functions that are declared with the fun keyword. A function may have parameters and may have a return type. The return type Unit is what void is in Java. If a function is not a “Single-expression functions” (to be covered in a later article) and returns Unit, then the return type may be omitted.

The greet() function in the example above returns a String value. Note that the returned String contains a template expression that allows you to avoid ugly String concatenation using + operator. A template expression starts with a dollar sign ($). The value after $ represents a named placeholder that is evaluated at runtime. In this example the expression refers to the name property.

Null-Safety

Did you notice the question mark (?) in the System.out?.println statement? Kotlin distinguishes between nullable and non-nullable references. The ?. operator is called a safe call. It’s Kotlin’s way to avoid NullPointerException. If the expression on the left hand side refers to null, the expression on the right hand side is not executed. More on Null-Safety in some of the next articles about Kotlin.

And last but not least, did you notice that we didn’t use any semicolons?

IDE support

Does Kotlin have IDE support? Well, JetBrains is the company behind IDEA which is the best IDE for Java. But also Groovy and Scala support in IDEA is excellent. It’s natural that JetBrains provides IDE support for its own language. I played around with the Kotlin plugin for IDEA. It needs some final polishing but it is already quite usable. Here is a screenshot.

That’s it for now. In this article we cover a few basic Kotlin features. I hope you enjoyed it. Stay tuned.

Tapestry 5.3 release candidate is out and the final release is approaching. That’s why I want to share with you a new cool feature which will make your life easier.

As a Tapestry user you surely know Tapestry’s component reference documentation. This documentation is generated using Tapestry’s Maven plugin. Many of Tapestry users, who are also Maven users, are using this plugin for their custom components. Unfortunately there was no solution for non-Maven users before Tapestry 5.3.

Starting with version 5.3 Tapestry provides a JavaDoc plugin which can be used to generate a component reference documentation as part of JavaDoc. An example is demonstrated in the following screenshot.

 

Check out this JavaDoc to see what is possible with the new JavaDoc plugin.

What is needed to integrate a component reference into the JavaDoc? You just need to place @tapestrydoc on the component’s classes, as shown in the following example.

/**
 *  Here comes your JavaDoc...
 *
 * @tapestrydoc
 */
public class MyComponent {
   ...
}

Additionally you need to use Tapestry’s taglet when generating the JavaDoc. For more details on JavaDoc Taglets see here.

Integration with Maven

Now let’s see how to tell Maven’s JavaDoc plugin to use Tapestry’s taglet.

<project>
  ...
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.8</version>
        <configuration>
          ...
          <taglet>org.apache.tapestry5.javadoc.TapestryDocTaglet</taglet>
          <tagletArtifact>
             <groupId>org.apache.tapestry</groupId>                       
             <artifactId>tapestry-javadoc</artifactId>                       
             <version>5.3-rc-3</version>                   
          </tagletArtifact>
          ...
        </configuration>
      </plugin>
    </plugins>
    ...
  </reporting>
  ...
</project>

That’s all. Tapestry’s JavaDoc plugin will do the rest and generate kickass JavaDocs.

Integration with Gradle

If you are interested how to generate the component reference with Gradle, please check out Tapestry’s build script.

Integration with Ant

Honestly I have no idea how to do that as I didn’t use Ant for years. I’m pretty sure it is possible. Please read the documentation for Ant’s JavaDoc plugin for more details.

Stay tuned!

As already announced here, I’ll be publishing my Tapestry 5 book on my own. Because “Tapestry 5 in Action” sounds like a book published by Manning, I decided to choose another title.

Coming up with a cool title is a challenge. That’s why I decided to ask the community for a new title for the book. If you have a proposal, please drop me a line or comment on this post. Please post any idea you have (with or without subtitle), no matter how crazy it is. The author of the chosen title will be rewarded by a free PDF copy when the book is published.

Looking forward to see your ideas.

Some weeks ago I have been informed by Manning Publications that the Tapestry 5 in Action book is canceled. Based on MEAP sales Manning did a sales forecast. It looks like the book is financially not attractive enough.

As you can imagine, this news made me upset. I was working on the book for about 8 month now. The half of the book (almost 250 pages) is already finished and I was looking forward to see the book in a final shape. After the MEAP has been started, I’ve got a lot of positive feedback regarding the book. It looks like the readers like the book’s content very much.

Manning’s decision was more than a surprise for me. After being upset for a couple of days I changed my opinion about Manning’s decision. Now I believe that this cancelation is the best thing that could happen to the book. I decided to publish the book on my own (probably on lulu.com). First of all, it is much more financially attractive for me. Secondly, I’ll be able to publish as many editions as I wish. I can update the book’s content every time a new Tapestry version is released. The only disadvantage is that lulu.com doesn’t provide something like an “early access program” so that the readers will need to wait until the book is finished.

If you was one of the MEAP customers who bought the Tapestry 5 in Action book, there is no reason to be sad. The book is going to be published. I promise you.

Stay tuned!

Frequently web applications have a requirement to execute some business logic which is not bound to any HTTP request. For example, you might want to execute some periodic maintenance job to cleanup the database or a job sending messages to your users. In this article I’ll show you how to register jobs to be executed by Tapestry without blocking any incoming HTTP request.

Interval Jobs

Imagine you have a CleanupService service to be executed for database cleanup. The service’s interface is shown in the following example. The service implementation details are not interesting for this article as they are very specific to your application.

public interface CleanupService {
    void clean();
}

Now let’s schedule a periodic execution of the cleanup at application’s startup. This is accomplished by contributing to the RegistryStartup service’s configuration, as shown in the following example.

public class AppModule {

    @Startup
    public static void scheduleJobs(
                   PeriodicExecutor executor,
                   final CleanupService cleanupService) {

        executor.addJob(
            new IntervalSchedule(300000L),
            "Cleanup Job",
            new Runnable() {
                public void run() {
                    cleanupService.clean();
                }
            });
    }
}

As of Tapestry 5.3 the PeriodicExecutor service can be used to schedule jobs. In the example above, this service is injected into a startup method. The service’s addJob method is used to register jobs to be executed.This method takes three parameters:

  1. Instance of Schedule: defines when to execute the next job
  2. Name used in debugging output related to the job
  3. Instance of Runnable that represents the work to be done

In the example above, a IntervalSchedule instance is used to schedule a job to be executed every 300000 milliseconds (5 minutes). Note that the Runnable is just a wrapper around the CleanupService.

Using CRON expressions

Instead of defining intervals for job executions, Tapestry also allows you to use CRON expressions, such as described here. Note that Tapestry uses the CRON parser from the Quartz Scheduler without depending on it.

The following example demonstrates how to use CRON expressions.

public class AppModule {

    @Startup
    public static void scheduleJobs(
                   PeriodicExecutor executor,
                   final CleanupService cleanupService) {

        executor.addJob(
            new CronSchedule("0 0/5 14 * * ?"),
            "Cleanup Job",
            new Runnable() {
                public void run() {
                    cleanupService.clean();
                }
            });
    }
}

In the example above, a job is registered to be executed every 5 minutes starting at 2pm and ending at 2:55pm, every day.

Happy scheduling.

The Tapestry team has been very busy in the last months and it looks like Tapestry 5.3 goes Beta. While we are working on fixing last minor issues before version 5.3 becomes generally available, I want to share with you some of the new upcoming features.

From the user perspective Tapestry 5.3 will be the most attractive release since 5.0. This article gives you a short overview.

New Components

Several components has been added to the core library:

  • Kaptcha / KaptchaField: Allow you to protect your forms from spam.
  • Tree: Used to render a recursive tree structure, with expandable/collapsable/selectable nodes.
  • Dynamic: An awesome component allowing a component to render itself differently at different times, by making use of an external template file. More details on this component follow in the next post
  • Checklist: Multiple selection component. Generates a UI consisting of a list of check boxes. This component is used as alternative to the Palette component.
  • Alerts: Used to display alerts.

Alerts

In the past the only way to present some messages to the user was to persist some page properties using the flash strategy. Now Tapestry provides a central mechanism for handling user alerts: the AlertManager service and the Alerts component. Using AlertManager service you can add alerts which are presented to the user using the Alerts component. Alerts can be added during both traditional and Ajax requests, and may be transient (displayed for a few seconds), normal, or sticky (persist until the user expressly dismisses them). Alerts support three severities: info, warn(ing) and error; the look and feel can be customized by overriding Tapestry’s default CSS rules.

Template Skinning

I discussed template skinning feature in this article.

Improved Exception Reporting

Tapestry is known to provide excellent messages when something goes wrong. In version 5.3, the exception reporting has been improved for Ajax requests. Please watch this screencast for more details.

New JavaScript Abstraction Layer

As you probably know, Tapestry is stuck with using Prototype and Scriptaculous for backward compatibility reasons. A lot of Tapestry users has been complaining about missing support of jQuery. Those of you, how can’t live without jQuery are probably using this Tapestry/jQuery library which allows you to get rid of Prototype and Scriptaculous.

Breaking backward compatibility with existing apps just by rewriting the client-side code to jQuery is not an option. Also tying Tapestry to jQuery wouldn’t be a good decision. If yet another JavaScript library will become successful next year and everybody starts to migrate, you are stuck again. A much better solution is to provide an abstraction layer which allows you to use any JavaScript library you like just by replacing a couple of files. Some work has already been done in Tapestry 5.3. The transition is done gradually and will be finalized in version 5.4.

Improved Ajax

The MultiZoneUpdate class has been deprecated in favor of AjaxResponseRenderer service. This service manages the rendering of a partial page render as part of an Ajax response. Let’s see a simple example.

public class AjaxDemo {
    @Inject
    private Block block;

    @Inject
    private AjaxResponseRenderer ajaxResponseRenderer;

    @Inject
    @Path("MultiZoneUpdateDemo.js")
    private Asset library;

    Object onActionFromUpdate() {
        ajaxResponseRenderer.addRender("zone", block);

        ajaxResponseRenderer.addCallback(
                    new JavaScriptCallback() {
            public void run(JavaScriptSupport support) {

                support.importJavaScriptLibrary(library);
                support.addInitializerCall(
                     "writeMessageTo",
                     new JSONObject("id", "message",
                                    "message", "Updated"));
         }
        });
    }
}

As you can see, the new API allows us to update a zone with the content from a renderer (such as a Block, Component or other object that can be coerced to RenderCommand). It is also possible to queue a JavaScriptCallback to be executed during the partial markup render. In this example the callback is used to import a JavaScript library as part of the rendered page and to add a call to a client-side function inside the Tapestry.Initializer namespace.

JSR 330 Integration

Starting from Tapestry 5.3, it’s possible to use JSR-330 annotations for injection. Using the standard annotations, your code in the service layer doesn’t need to depend on Tapestry. Please read this article for more details.

JPA 2 Integration

Finally, Tapestry provides a native JPA 2 integration. How does it differ from Tynamo’s JPA integration? First of all, it is maintained by the Tapestry team, that will ensure the backward compatibility with future releases. Secondly, it provides some features that were not available in Tynamo. For example, you can have multiple persistence units in the same application. Furthermore, Tapestry allows you to configure JPA without XML. Read this article for more details.

JavaScript and CSS Compression

A module integrating Yahoo’s YUI Compressor has been added. This library allows you to compress your JavaScript and CSS.

Component Reference

Great news for component developers. Starting with Tapestry 5.3 generating a component reference will be as easy as writing JavaDoc. You no longer need to use Maven. Instead you just need to place @tapestrydoc in the component’s class JavaDoc. That’s all. The following screenshot demonstrates the result.

Scheduling Jobs

The PeriodicExecutor service has been introduced to allow execution of scheduled jobs. The following example demonstrates how to schedule a job to be executed every 5 minutes.

public class PeriodicExecutorDemo {

    public PeriodicExecutorDemo(PeriodicExecutor executor) {

       executor.addJob(
          new IntervalSchedule(300000L),
          "MyJob",
           new Runnable () { void run() { ... }; } );
    }
}

 

Plastic

Plastic is a bytecode transformation library based on ASM. Plastic is designed to simplify the run-time transformation of Java classes. The most parts of the internal API using Javassist has been rewritten to use Plastic. The Javassist-based API has been deprecated and will be removed in Tapestry 5.4. Starting from version 5.4 Tapestry will not longer depend on Javassist. Yay!

 

Have fun with Tapestry and stay tuned!

In this article I want to share with you a new awesome Tapestry feature introduced in 5.3. This feature allows you to provide different skins for a single page by creating several templates. These different templates are used by Tapestry to render the same page in a special way for different clients. For example, when developing a web application for both standard and mobile clients you might need to render the same page different depending on the current client. So, you need to create two different templates for each page and choose one of them depending on the user agent sent by the client.

In the Extending Template Lookup Mechanism article I described how to accomplish that in Tapestry 5.2. The described approach was not ideal because of the issue with Tapestry’s template cache.  Anyway, the new API in Tapestry 5.3 is cool. Let’s see it in action. First, let me show you how the template cache works.

Template cache

As you probably know the structure of Tapestry’s pages is static. I don’t want to cover the reasons for the static structure in this article; please read Tapestry’s documentation for more details. Because of the static structure the instances of Tapestry pages can be cached. You can imagine the page cache as a multidimensional coordinate system. By default the cache is two-dimensional; one of the axes is for page classes, the other for locales. If you have n pages in your application and you configured Tapestry to support m locales, then there might be maximal n * m page instances in the cache, as illustrated in the following figure.

The new API in Tapestry 5.3 allows you to add additional dimensions to the cache matrix. For example, a new dimension might be the client. Let’s say we have two different clients: standard and mobile. In this case the maximal number of page instances is n * m * 2, as shown in the following example.

Now let’s explore how to provide client-specific templates for pages and how to add additional dimensions to the page cache.

Locating component resources

The ComponentResourceLocator interface is the central service for locating resources for components. The interface defines two methods:

  • locateTemplate: Locates the template for a component (including pages and base classes).
  • locateMessageCatalog: Locates the message catalog for a component.

Both methods take a ComponentResourceSelector parameter. Briefly speaking, ComponentResourceSelector defines the axes to be used by the page cache.

The default implementation of the ComponentResourceLocator interface reads only the Locale from the passed  ComponentResourceSelector instance, so that the cache is 2-dimensional. Let’s create our own implementation of ComponentResourceSelector interface which will make use of a third dimension. The following example demonstrates how to accomplish that.

public class CustomComponentResourceLocator
              implements ComponentResourceLocator {

    private final ComponentResourceLocator delegate;

    private final Resource contextRoot;

    private final ComponentClassResolver resolver;

    public CustomComponentResourceLocator(
          ComponentResourceLocator delegate,
          Resource contextRoot,
          ComponentClassResolver resolver) {

        this.delegate = delegate;
        this.contextRoot = contextRoot;
        this.resolver = resolver;
    }

    @Override
    public Resource locateTemplate(
              ComponentModel model,
              ComponentResourceSelector selector) {

        if(!model.isPage()) {
            return null;
        }

        String className = model.getComponentClassName();

        String logicalName =
              resolver.resolvePageClassNameToPageName(className);

        Client client = selector.getAxis(Client.class);

        if (client == Client.MOBILE) {
            String path = String.format("mobile/%s.%s",
                     logicalName,
                     TapestryConstants.TEMPLATE_EXTENSION);

            Resource resource = contextRoot.forFile(path);

            if (resource.exists()) {
                return resource.forLocale(selector.locale);
            }
        }

        return delegate.locateTemplate(model, selector);
    }

    @Override
    public List<Resource> locateMessageCatalog(
              Resource baseResource,
              ComponentResourceSelector selector) {

        return delegate.locateMessageCatalog(
                               baseResource, selector);
    }
}

As you can see, our implementation is a decorator for the original ComponentResourceLocator implementation. Inside the locateTemplate() method the passed ComponentResourceSelector instance is used to retrieve the third axis which is of type Client. If the current client is Client.MOBILE, we try to locate a special template from the mobile sub-folder. If a page template exists in this sub-folder, it is returned. Otherwise we delegate to the original ComponentResourceLocator implementation in order to return the default template.

Next, we need to decorate the built-in ComponentResourceLocator by providing a decorate method in the AppModule class.

public class AppModule {

   @Decorate(serviceInterface = ComponentResourceLocator.class)
   public static Object customComponentResourceLocator(
           ComponentResourceLocator delegate,
           @ContextProvider AssetFactory assetFactory,
           ComponentClassResolver componentClassResolver) {

        return new CustomComponentResourceLocator(
                      delegate,
                      assetFactory.getRootResource(),
                      componentClassResolver);
    }
}

Where does the Client axes come from? This is where the ComponentRequestSelectorAnalyzer service comes into play. This service has been introduced in Tapestry 5.3 and is responsible for determining the ComponentResourceSelector for the current request. The default implementation of the interface creates a 2-dimensional ComponentResourceSelector instance; the axes are page class and Locale for the current request. Let’s implement our own ComponentRequestSelectorAnalyzer implementation which will return a 3-dimensional ComponentResourceSelector. The following example demonstrates how to accomplish that.

public class CustomComponentRequestSelectorAnalyzer
                implements ComponentRequestSelectorAnalyzer {

    private final ThreadLocale threadLocale;

    private ClientService clientService;

    public CustomComponentRequestSelectorAnalyzer(
          ThreadLocale threadLocale,
          ClientService clientService) {

        this.threadLocale = threadLocale;
        this.clientService = clientService;
    }

    @Override
    public ComponentResourceSelector buildSelectorForRequest() {

       Locale locale = threadLocale.getLocale();
       Client client = clientService.getCurrentClient();

        return new ComponentResourceSelector(locale)
                      .withAxis(Client.class, client);
    }
}

As you can see, we create a ComponentResourceSelector by passing the current Locale to the constructor. Then we add an additional axis of type Client. The current Client is retrieved from ClientService which is your custom service. Probably you would implement such a service by examining the User-Agent HTTP header. Anyway, the implementation details of ClientService are not interesting for this article.

Finally, we need to override the original implementation of ComponentRequestSelectorAnalyzer service by contributing to the ServiceOverride service’s configuration, as shown in the following example.

public class AppModule {

    public static void bind(ServiceBinder binder) {
        binder.bind(ClientService.class,
                    ClientServiceImpl.class);

        binder.bind(ComponentRequestSelectorAnalyzer.class,
                    CustomComponentRequestSelectorAnalyzer.class)
             .withId("CustomComponentRequestSelectorAnalyzer");
    }

     @Contribute(ServiceOverride.class)
    public static void overrideSelectorAnalyzer(
           MappedConfiguration<Class, Object> cfg,

          @InjectService("CustomComponentRequestSelectorAnalyzer")
          ComponentRequestSelectorAnalyzer analyzer){

           cfg.add(ComponentRequestSelectorAnalyzer.class, analyzer);
    }
}

That’s all. Whenever you ClientService determines that the current client is a mobile devices and returns Client.MOBILE, Tapestry will look for a template in the mobile sub-folder in the context root. If found it is used to render the response for the mobile device. If not found, the default template is used.

Have fun with Tapestry and stay tuned.

Tapestry claims to be performant and scalable. You want a proof? Than read this great post. The author compares the performance of Rails, Wicket, Grails, Play, Tapestry, Lift, JSP, Context. It is not a surprise that Tapestry outperformed the most of the competitors. Here are the results:

For more details on the benchmark please read the original article.

Two years ago Peter Thomas made a similar comparison and the result was not that good for Tapestry. It seems like two year ago Wicket was ahead of  Tapestry and Grails. But the recent comparison shows that Wicket’s performance is the worst. What could be the reason for such different results? First of all, I believe that Peter Thomas’ comparison was not accurate. Peter is known to be a Wicket lover. When the comparison is made by an unbiased person, then the results look completely different. Another possible reason could be that Tapestry improved in the last two years a lot. Removal of page pooling and other important changes might be the reason for that. However, seeing that Tapestry’s performance just rocks is a satisfaction.

In the last post I gave you a short preview of the Tapestry/JPA integration library in the upcoming 5.3 release. In this post I’m going to show a new feature that I added yesterday. You will see that configuring JPA with Tapestry is much more simple than defined in the JPA specification.

The persistence.xml file is the standard configuration file in JPA used to define the persistence units. Let’s explore the following persistence descriptor using a non-JTA data source.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             version="2.0">
   <persistence-unit name="Blue"
                     transaction-type="RESOURCE_LOCAL">

      <non-jta-data-source>
         jdbc/JPATest
      </non-jta-data-source>

      <properties>
         <property name="eclipselink.ddl-generation"
                   value="create-tables"/>
         <property name="eclipselink.logging.level"
                   value="fine"/>
      </properties>
   </persistence-unit>

</persistence>

Now let’s see how to provide an equivalent JPA configuration without using any XML descriptors. This can be accomplished by making a contribution to the EntityManagerSource service.

public class AppModule {

   @Contribute(EntityManagerSource.class)
   public static void configurePersistenceUnitInfos(
      MappedConfiguration<String,PersistenceUnitConfigurer>
      cfg) {

      PersistenceUnitConfigurer configurer
                 = new PersistenceUnitConfigurer() {

         public void configure(
                  TapestryPersistenceUnitInfo unitInfo) {

            unitInfo.nonJtaDataSource("jdbc/JPATest")
               .addProperty("eclipselink.ddl-generation",
                            "create-tables")
               .addProperty("eclipselink.logging.level",
                            "fine");
         }
     };

     cfg.add("Blue", configurer);
   }
}

The EntityManagerSource service’s configuration is a map in which the keys are persistence unit names and the values are PersistenceUnitConfigurer instances. In other words, a PersistenceUnitConfigurer instance is associated with a persistence unit to be configured. The TapestryPersistenceUnitInfo instance passed to the PersistenceUnitConfigurer holds the persistence unit metadata for use by the persistence provider. It may represent a persistence unit defined in the persistence.xml file or an empty persistence unit. Confused? Let me clarify it.

If the contribution key matches a persistence unit defined in the persistence.xml file, then the passed TapestryPersistenceUnitInfo instance is pre-filled with the metadata from persistence.xml. This metadata can be modified programmatically inside a PersistenceUnitConfigurer. If persistence.xml file is not present or the contribution key doesn’t match any persistence unit, the passed TapestryPersistenceUnitInfo instance is empty. This way Tapestry allows you to configure JPA without writing XML descriptor files.

Enjoy!

In this article I’m going to describe the Tapestry/JPA 2 Integration library that provides out-of-the-box support for using JPA 2 as the back end for normal CRUD style Tapestry applications. I added this library to Tapestry’s trunk some weeks ago but didn’t have any time to write an article about it. Now that we are close to a first 5.3 release, I would like to give you a preview of this library.

Configuring JPA

The persistence.xml file is the standard configuration file in JPA used to define the persistence units. By default, this file is expected to be located on the classpath in the META-INF directory. Tapestry reads this file to create the EntityManagerFactory. The following example demonstrates a persistence.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             version="2.0">
   <persistence-unit name="Red"
                     transaction-type="RESOURCE_LOCAL">
       <properties>
          <property name="javax.persistence.jdbc.driver"
                    value="org.h2.Driver" />
          <property name="javax.persistence.jdbc.url"
                    value="jdbc:h2:mem:test" />
          <property name="javax.persistence.jdbc.username"
                    value="sa" />
          <property name="eclipselink.ddl-generation"
                    value="create-tables"/>
          <property name="eclipselink.logging.level"
                    value="fine"/>
      </properties>
   </persistence-unit>

   <persistence-unit name="Blue"
                     transaction-type="RESOURCE_LOCAL">
      <non-jta-data-source>
         jdbc/JPATest
      </non-jta-data-source>
   </persistence-unit>

</persistence>

Note that you need to provide unique names for persistence units. In the example above we defined two persistence units named Red and Blue.

If you want to place the persistence.xml file in an other directory or name it arbitrarily, you can make a contribution to the SymbolProvider service, as shown in the following example. This is a quite useful feature if you want to use a different persistence descriptor for tests.

public class AppModule {

   @Contribute(SymbolProvider.class)
   @ApplicationDefaults
   public static void provideFactoryDefaults(
       MappedConfiguration<String, String> configuration) {

      configuration.add(
            JpaSymbols.PERSISTENCE_DESCRIPTOR,
            "/jndi-datasource-persistence-unit.xml");
   }
}

For each of the persistence units defined in the persistence.xml file Tapestry creates a TapestryPersistenceUnitInfo. The interface TapestryPersistenceUnitInfo is mutable extension of the PersistenceUnitInfo interface which allows you to configure a persistence unit programmatically. This can be accomplished by making a contribution to the EntityManagerSource service, as shown in the following example.

public class AppModule {

   @Contribute(EntityManagerSource.class)
   public static void configurePersistenceUnitInfos(
            MappedConfiguration<String,PersistenceUnitConfigurer>
            cfg) {

      PersistenceUnitConfigurer configurer
                 = new PersistenceUnitConfigurer() {

         public void configure(
                  TapestryPersistenceUnitInfo unitInfo) {
            unitInfo.addManagedClass(User.class);
         }
      };

      cfg.add("Blue", configurer);
   }
}

The EntityManagerSource service’s configuration is a map in which a persistence unit name is associated with a PersistenceUnitConfigurer instance. A PersistenceUnitConfigurer is used to configure a TapestryPersistenceUnitInfo that has been read from the persistence.xml file.

Automatically adding managed classes

If only a single persistence unit is defined, Tapestry scans the  application-root-package.entities package. The classes in that package are automatically added as managed classes to the defined persistence unit.

If you have additional packages containing entities, you may contribute them to the JpaEntityPackageManager service configuration.

public class AppModule {

   @Contribute(JpaEntityPackageManager.class)
   public static void providePackages(
            Configuration<String> configuration) {
      configuration.add("org.example.myapp.domain");
   }
}

You may add as many packages as you wish.

Injecting the EntityManager into page and component classes

The created entity managers can be injected into page and component classes.  Depending on whether more than one persistence unit has been defined, the way to inject EntityManager varies slightly.

Let’s start with a simple scenario, where only a single persistence unit is defined. In this case, an EntityManager can be injected using the @Inject annotation.

public class CreateAddress {

   @Inject
   private EntityManager entityManager;

   @Property
   private Address address;

   @CommitAfter
   void onSuccess() {
      entityManager.persist(address);
   }
}

Alternatively, you can use the @PersistenceContext annotation to get the EntityManager injected into a page or component.

public class CreateAddress {

   @PersistenceContext
   private EntityManager entityManager;

   @Property
   private Address address;

   @CommitAfter
   void onSuccess() {
      entityManager.persist(address);
   }
}

If you have multiple instances of persistence-unit defined in the same application, you need to explicitly tell Tapestry which persistence unit you want to get injected. So,  just placing @Inject annotation on the injection place is not sufficient.

public class CreateAddress {

   @PersistenceContext(unitName = "Blue")
   private EntityManager entityManager;

   @Property
   private Address address;

   @CommitAfter
   @PersistenceContext(unitName = "Blue")
   void onSuccess() {
      entityManager.persist(address);
   }
}

In the example above, the @PersistenceContext annotation’ s name attribute is used to explicitly define the name of the unit to inject.

Injecting EntityManager into services

While component injection occurs only on fields, the injection in the IoC layer may be triggered by a  field or a constructor. The following example demonstrates field injection, when a single persistence unit is defined in the persistence descriptor.

public class UserDAOImpl implements UserDAO {
   @Inject
   private EntityManager entityManager;

   ...
}

The constructor injection is demonstrated in the following example.

public class UserDAOImpl implements UserDAO {

   private EntityManager entityManager;

   public UserDAOImpl(EntityManager entityManager) {
      this.entityManager = entityManager;
   }

   ...
}

Because @PersistenceContext annotation must not be placed on constructor parameters, you can’t use constructor injection if multiple persistence units are defined in the same application. In such a case, only field injection is supported, as shown in the following example.

public class UserDAOImpl implements UserDAO {
   @Inject
   @PersistenceContext(unitName = "Blue")
   private EntityManager entityManager;

   ...
}

Transaction management

As you already know from the Hibernate integration library, Tapestry automatically manages transactions for you. The JPA integration library defines the @CommitAfter annotation, which acts as the correspondent annotation from the Hibernate integration library. Let’s explore the UserDAO interface to see the annotation in action.

public interface UserDAO {

   @CommitAfter
   @PersistenceContext(unitName = "Blue")
   void add(User user);

   List<User> findAll();

   @CommitAfter
   @PersistenceContext(unitName = "Blue")
   void delete(User... users);
}

As you can see, the annotation may be placed on service method in order to mark that method as transactional. Any method marked with @CommitAfter annotation will have a transaction started before, and committed after it is called. Runtime exceptions thrown by by a transactional method will abort the transaction. Checked exceptions are ignored and the transaction will be committed anyway.

Note that EntityTransaction interface does not support two phase commit. Committing transactions of multiple EntityManagers in the same request might result in data consistency issues. That’s why @CommitAfter annotation must be accompanied by the @PersistenceContext annotation if multiple persistence unit are defined in an application. This way you can only commit the transaction of a single persistence unit. You should be very carefully, if you are committing multiple transactions manually in the same request.

After placing the @CommitAfter annotation on methods, you need to tell Tapestry to advise those methods. This is accomplished by adding the transaction advice, as shown in the following example.

public class AppModule {

   @Match("*DAO")
   public static void adviseTransactionally(
         JpaTransactionAdvisor advisor,
         MethodAdviceReceiver receiver) {

      advisor.addTransactionCommitAdvice(receiver);
   }
}

That’s it for the first part of the article on JPA 2 support in Tapestry. In the next article I’ll cover some further interesting features of the JPA integration library like providing ValueEncoder for managed classes, using @Persist and @SessionState annotations with entities and JPA-enabled Grid component.

Tapestry 5 Blog - Copyright © 2009 - Eclectic Theme by Your Inspiration Web - Powered by WordPress