Wednesday, January 18, 2012

Arquillian with NetBeans, GlassFish embedded, JPA and a MySQL Datasource - Part II

This is a followup post to the one I did yesterday. Even if it was intended to be a more complex demo it turns out, that I missed a big issue with the setup. Everything works fine up to the point when you start introducing enhanced features to your entities. To name but a few: lazy loading, change tracking, fetch groups and so on. JPA providers like to call this "enhancing" and it is most often referred to as "weaving". Weaving is a technique of manipulating the byte-code of compiled Java classes. The EclipseLink JPA persistence provider uses weaving to enhance JPA entities for the mentioned things and to do internal optimizations. Weaving can be performed either dynamically at runtime, when Entities are loaded, or statically at compile time by post-processing the Entity .class files. Dynamic weaving is mostly recommended as it is easy to configure and does not require any changes to a project's build process. You may have seen some finer log output from EclipseLink like the following:
[...]--Begin weaver class transformer processing class [com/mycompany/simpleweb/entities/AuditLog].
[...]--Weaved persistence (PersistenceEntity) [com/mycompany/simpleweb/entities/AuditLog].
[...]--Weaved change tracking (ChangeTracker) [com/mycompany/simpleweb/entities/AuditLog].
[...]--Weaved lazy (ValueHolder indirection) [com/mycompany/simpleweb/entities/AuditLog].
[...]--Weaved fetch groups (FetchGroupTracker) [com/mycompany/simpleweb/entities/AuditLog].
[...]--End weaver class transformer processing class [com/mycompany/simpleweb/entities/AuditLog].

The problem with Arquillian and Embedded GlassFish
Imagine you take the example from yesterday's blog post and change the simple String account property to something like this:
 @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    private Person person;
That's exactly one of the mentioned cases where your JPA provider would need to do some enhancements to your class files before executing. Without modifying the project it would lead to some very nasty exceptions:
Exception Description: A NullPointerException would have occurred accessing a non-existent weaved _vh_ method [_persistence_get_person_vh].  The class was not weaved properly - for EE deployments, check the module order in the application.xml deployment descriptor and verify that the module containing the persistence unit is ahead of any other module that uses it.
[...]
Internal Exception: java.lang.NoSuchMethodException: com.mycompany.simpleweb.entities.AuditLog._persistence_get_person_vh()
Mapping: org.eclipse.persistence.mappings.ManyToOneMapping[person]
Descriptor: RelationalDescriptor(com.mycompany.simpleweb.entities.AuditLog --> [DatabaseTable(AUDITLOG)])
 at org.eclipse.persistence.exceptions.DescriptorException.noSuchMethodWhileInitializingAttributesInMethodAccessor(DescriptorException.java:1170)
 at org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor.initializeAttributes(MethodAttributeAccessor.java:200)
[...]
indicating that something is missing. And that missing method is introduced by the weaving process. If you decompile a weaved entity you can see what the JPA provider is complaining about. This is how your enhanced entity class should look like. And this is only one of the enhanced methods a weaving process is introducing into your code.

  public WeavedAttributeValueHolderInterface _persistence_get_person_vh()
    {
        _persistence_initialize_person_vh();
        if(_persistence_person_vh.isCoordinatedWithProperty() || _persistence_person_vh.isNewlyWeavedValueHolder())
        {
            Person person1 = _persistence_get_person();
            if(person1 != _persistence_person_vh.getValue())
                _persistence_set_person(person1);
        }
        return _persistence_person_vh;
    }

Dynamic vs. Static Weaving
Obviously the default dynamic weaving doesn't work with the described setup. Why? Weaving is a spoiled child. It only works when the entity classes to be weaved do exist only in the application classloader. The combination of embedded GlassFish, Arquillian and the maven sure-fire-plugin mix this up a bit and the end of the story is, that exactly none of your entities are enhanced at all. Compare this nice discussion for a more detailed explanation. If dynamic waving doesn't work, we have to use the fallback called static weaving. Static means: post processing the entities during the build. Having the maven project at hand, this sounds like a fairly easy job. Let's look for something like this. The first thing you probably find is the StaticWeaveAntTask. The second thing may be Craig's eclipselink-staticweave-maven-plugin. Let's start with the StaticWeaveAntTask. You would have to use maven-antrunner-plugin to get this introduced. Copy classes from left to right and do an amazing lot of wrangling to get your classpath rigth. Laird Nelson did a great job to archetype-ize an example configuration for all 3 big JPA providers (EclipseLink, OpenJPA, Hibernate) and your could give this a try. A detailed explanation about what is happening can be found on his blog. Thanks Laird for the pointers! Don't get me wrong: This is a valid approach, but I simply don't like it. Mainly because it introduces a massive complexity to the build and having seen far too many projects without the right skills for managing even normal maven projects, this simply isn't a solution for me. I tried the static weaving plugin done by Craig Day.

Adding static weaving to simpleweb
So, let's open the pom.xml from yesterdays project and introduce the new plugin:
 <plugin>
     <artifactId>eclipselink-staticweave-maven-plugin</artifactId>
     <groupId>au.com.alderaan</groupId>
     <version>1.0.1</version>
          <executions>
             <execution>
                  <goals>
                    <goal>weave</goal>
                  </goals>
                  <phase>process-classes</phase>
             </execution>
           </executions>
      </plugin>
Done. Now your classes are weaved and if you introduce some logging via the plugin configuration you can actually see, what happens to your entity classes. The plugin is available via repo1.maven.org. The only issue I came across is, that the introduced dependency towards EclipseLink 2.2.0 isn't (or course) not available via the same repo, so you probably would need to build it for yourself with the right repositories and dependencies. You can get the source code via the plugin's google code page.
Don't forget to add the weaving property to your test-persistance.xml:

  <property name="eclipselink.weaving" value="static" />

[UPDATE: 19.01.2012]
Craig released a new 1.0.2 version of the plugin which solves the issues with the EclipseLink dependency. You now can simply include the needed EclipseLink version as a dependency to the plugin. Also needed is the correct EclipseLink maven repository. A complete example with a configured log level looks like this:
  <repository>
            <id>eclipselink</id>
            <name>Repository hosting the eclipselink artifacts</name>
            <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo/</url>
        </repository>

[...]
  <plugin>
                <artifactId>eclipselink-staticweave-maven-plugin</artifactId>
                <groupId>au.com.alderaan</groupId>
                <version>1.0.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>weave</goal>
                        </goals>
                        <phase>process-classes</phase>
                        <configuration>
                            <logLevel>ALL</logLevel>
                        </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.eclipse.persistence</groupId>
                        <artifactId>eclipselink</artifactId>
                        <version>2.3.1</version>
                    </dependency>
                </dependencies>
            </plugin>