KStructs: direct access to C-like memory structs with Kotlin for the JVM

While KPointers is a library that provides for very low level access to memory in Kotlin for the JVM, a higher level of abstraction is required to access structured data, so that we do not need to remember offsets and field sizes every time we need to read/write to them.

KStructs is a Kotlin library whose intent is to solve this issue, so that access to off-heap C-struct-like memory is much simpler. KStructs is built on top KPointers.

Go to the KStructs site for a very simple introduction to KStructs, and download it from there.

KPointers: pointers in Kotlin

As of lately, I’ve been having fun with low-level programming, and have had to perform tasks like

  • Implement high performance unbuffered disk access from Java/Kotlin (access to raw memory buffers required, but speed went from 2GB/s to 3.1GB/s in the fastest NVME SSDs)
  • Calls to external OS DLLs with access to external memory buffers to work with Large Pages.
  • Shared memory usage

I have needed to access  memory directly from Java and Kotlin, and have had to wrap such access in the JVM side, and that has meant having to deal with pointers pointing to all kinds of data.

Unfortunately (or maybe fortunately, as it avoid lots of very troublesome problems) the JVM does not provide a way to manipulate pointers…except by using the Unsafe class. That is not portable, but in reality there are so many projects using it to attain high performance, that it is present in all JVM I have ever used for production code.

So, we have Unsafe, but…it sees pointers as longs, and that is really bad when what you have are pointers to all kinds of data, need to perform pointer arithmetic, etc. So, to point to the to next byte, increase the long/pointer by 1, but increase it by 4 if it is a float, by 2 if it is a char etc, etc. And don’t mix it, or you’ll get in deep trouble, as Unsafe is much more dangerous for working with pointers than the way we work with pointers in C or C+++.

Now, the inherent risk of working with pointers that is one of the reason Java doesn’t support pointers, and we are all happy about it -most of the time.

But, if you need pointers, you need the safest possible pointers there are, not plain longs. So, if you are working with Kotlin, use KPointers: it provides high performance pointer types for all primitive types, and support all standard pointer operations, from pointer arithmetic to indexed access, increment, decrement, etc.

If you want to see code for that, go to the README page of KPointers: it is short and goes straight to the point

Arquillian y GlassFish: portar ‘Hola Mundo’ desde TomEE

Por ahora hemos visto cómo efectuar un test Hola Mundo con Arquillian y WildFly, y cómo portar dicho test a Arquillian + TomEE.

Hoy veremos cómo ejecutar ese test contra GlassFish, usando su adaptador managed.

1.Configuración de dependencias

En teoría, lo único que debería cambiar a nivel de dependencias son las librerías de arquillian para GlassFish (cambio #1).

Modificaremos build.gradle para utilizar org.jboss.arquillian.container:arquillian-glassfish-managed-3.1:1.0.0.Final-SNAPSHOT, como sigue:

   // *****************************************************************************
   // GlassFish managed
   testRuntime 'org.jboss.arquillian.container:arquillian-glassfish-managed-3.1:1.0.0.Final-SNAPSHOT'

2. Código

El mismo que para WildFly y para TomEE.

3. Configuración de Runtime

Aunque tocaría ahora, ya hemos cambiado las dependencias de tiempo de ejecución para tests más arriba.

Debemos cambiar el archivo arquillian.xml para configurar el servidor managed de GlassFish (cambio #2), que quedará como sigue:

<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
   <container qualifier="glassfish-managed" default="true">
      <configuration>
         <property name="glassFishHome">/home/pagdev/pagde/tool/glassfish-4.1/</property>
      </configuration>
   </container>
</arquillian>

La única propiedad obligatoria de esta configuración es glassFishHome, que debe apuntar al directorio de instalación de GlassFish.

4. Ejecutar tests

Se ejecutan exactamente igual:

gradle test --tests *Test

Notas

Tan solo hemos tenido que hacer dos cambios para poder lanzar el test más simple posible usando un bean EJB.

Gradle tardó en ejecutar el test contra GlassFish managed alrededor de 18 segundos, y contra WildFly managed sobre los 11 segundos, y a lo largo de numerosas ejecuciones los tiempor variaron no más de 2 segundos. Contra Tomcat embedded, los tests se ejecutaron en torno a 6 o 7 segundos.

Software utilizado

Esto ha sido probado con GlassFish 4.1 y Arquillian 1.1.8, usando Gradle 2.3.

Arquillian y TomEE: portar ‘Hola Mundo’ de WildFly a TomEE

En teoría, Arquillian permite escribir tests de integración para varios servidores utilizando el mismo código y con unos cambios mínimos de configuración.

En este blog mi objetivo es usar Arquillian con TomEE en lugar de WildFly, y ver qué cambios debemos realizar para ejecutar el mismo test Hola Mundo que ya vimos en WildFly.

El objetivo es detallar todos y cada uno los cambios de configuración entre TomEE embedded y WildFly embedded.

1.Configuración de dependencias

Dado que no usamos ninguna funcionalidad específica de ningún servidor de aplicaciones, las dependencias de compilación y de test son las mismas que en el proyecto para WildFly.

En teoría, lo único que debería cambiar a nivel de dependencias son las librerías del runtime de Tomee (cambio #1), necesarias para arrancar y ejecutar TomEE en lugar de WildFly.

Modificaremos build.gradle para utilizar org.apache.openejb:arquillian-tomee-embedded:1.7.1, como sigue:

   // *****************************************************************************
   // TomeePlume: embedded
   testRuntime 'org.apache.openejb:arquillian-tomee-embedded:1.7.1'

Sin embargo, en la práctica, al ejecutar los test, nos encontramos con un error, java.lang.ClassFormatError, que se soluciona cambiando la dependencia de la API de JEE6 a javax:javaee-api:6.0 (cambio #2) para TomEE.

Como WildFly funciona perfectamente contra esta dependencia, este es más bien un cambio a hacer a la configuración de WildFly que a la de TomEE.

2. Código

El mismo que para WildFly.

3. Configuración de Runtime

Aunque tocaría ahora, ya hemos cambiado las dependencias para ejecutar TomEE en lugar de WildFly más arriba.

Por supuesto, debemos cambiar el archivo arquillian.xml para configurar el servidor embedded de Tomee (cambio #3), que quedará como sigue:

<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
   <container qualifier="tomee" default="true">
      <configuration>
      </configuration>
   </container>
</arquillian>

Y, sí, no hace falta configurar ningún parámetro para usar el TomEE embedded.

Otra cosa a tener en cuenta es que en la versión de WildFly con el adaptador embedded era obligatorio pasar a la máquina virtual del servidor el parámetro java.util.logging.manager, seleccionando el log manager de WildFly. Pero dicho gestor no está disponible en TomEE, por lo que no arrancará.

Solución: no pasar el parámetro java.util.logging.manager al runtime de TomEE (cambio #4).

4. Ejecutar tests

Se ejecutan exactamente igual.

En resumen

Hemos tenido que hacer cuatro cambios para poder lanzar el test más simple posible usando un bean EJB.

En realidad, si actualizamos la versión de WildFly para que use la dependencia org.apache.openejb:javaee-api:6.0-4 como API de JEE 6, con la que funciona perfectamente, el número de cambios es de 3, todos ellos triviales.

No está nada mal, ¿no?

Notas

Como nota aparte, comentar que Gradle tardó en ejecutar el test contra TomEE 5.856 segundos. El mismo test, lanzado contra WildFly con la configuración standalone.xml tardó 9.443 segundos.

Los tiempos en numerosas ejecuciones se mantuvieron siempre en torno a estos valores, con variaciones de no más de 1 segundo. Es una diferencia notable y que vale la pena mencionar, pero tampoco le daría mucha importancia, ya que el nuestro no es un escenario realista.

Software utilizado

Esto ha sido probado con TomeePlume 1.7.1 y Arquillian 1.1.8, usando Gradle 2.3.

Arquillian y WildFly: test ‘Hola Mundo’

Arquillian permite crear tests de integración con servidores/contenedores web y JEE como WildFly (o Tomcat), de forma bastante sencilla.

Para trabajar con un servidor, Arquillian usa adaptadores de contenedor, que permiten arrancar y parar los contenedores. Estos pueden ser de tres tipos: embebidos, gestionados, y remotos (embedded, managed y remote, a partir de ahora).

Para este Hola mundo usaremos el adaptador embedded, y dejaremos para otro artículo la discusión de qué ventajas e inconvenientes tiene cada tipo de adaptador y cuándo usar cada uno.

1. Configuración de dependencias

Para compilar los tests necesitaremos JUnit y Arquillian: con tan solo incluir junit:junit:4.11 y org.jboss.arquillian.junit:arquillian-junit-container:1.1.8.Final en build.gradle se incluirán todos los demás jars necesarios, especialment las dependencias de Arquillian.

Para ejecutar los tests, debemos incluir un adaptador de contenedor de WildFly, que Arquillian usará para arrancar y parar el contenedor contra el que se ejecutará el test. Como usaremos el contenedor embedded de WildFly, debemos incluir org.wildfly:wildfly-arquillian-container-embedded:8.2.0.Final en la lista de dependencias.

Por último, para que Gradle pueda encontrar algunas de estas dependencias deberemos añadir un repositorio de JBoss a nuestro build.gradle, que una vez hecho todo esto quedará como sigue:

apply plugin: 'java'

sourceCompatibility = 1.6

repositories {
  mavenCentral()
  maven {
    url "http://repository.jboss.org/nexus/content/groups/public-jboss"
  }
}

dependencies {
  compile 'javax:javaee-api:6.0'
  testCompile 'junit:junit:4.11',
    'org.jboss.arquillian.junit:arquillian-junit-container:1.1.8.Final'
  testRuntime 'org.wildfly:wildfly-arquillian-container-embedded:8.2.0.Final'
}

test {
  // Si no se especifica el log manager con el adaptador embedded de WildFly 8.2,
  // no arrancara correctamente
  systemProperties 'java.util.logging.manager': 'org.jboss.logmanager.LogManager'
}

2. Código

Para demostrar cómo implementar y ejecutar tests sencillos crearemos un stateless session bean, MyStatelessEjb, que simplemente suma dos números:

import javax.ejb.Stateless;

@Stateless
public class MyStatelessEjb {
   public int sum(int a, int b) {
      return a + b;
   }
}

Para hacer un test JUnit con Arquillian necesitaremos un runner de JUnit especial, incluido con Arquillian, para lo que anotaremos la clase de test con @RunWith(Arquillian.class).

También debemos especificar la configuración básica de la aplicación, para que el test se pueda ejecutar en el contexto adecuado. Debemos indicar dónde están los .class necesarios, si vamos a crear un war u otra cosa, quizá incluir un archivo de configuración como persistence.xml, etc.

Para ello se debe crear un método anotado con @Deployment, que utilizará la clase ShrinkWrap para llevar a cabo toda esta tarea de configuración.

El código resultante para hacer el test será como sigue:

@RunWith(Arquillian.class)
public class MyStatelessEjbTest {
   @EJB
   private MyStatelessEjb ejb;

   @Deployment
   public static Archive<?> createTestArchive() {
       return ShrinkWrap.create(WebArchive.class)
               .addPackage(MyStatelessEjb.class.getPackage());
   }

   @Test
   public void testSum() {
      Assert.assertEquals(5, ejb.sum(6,-1));
   }
}

Por lo demás, los tests son tests JUnit normales y corrientes, como se puede ver con testSum. Nótese que este test usa nuestro bean, que se ha inyectado en el test con @EJB, y que el propio contenedor WildFly gestiona.

3. Configuración de Runtime

Llegados a este punto, la aplicación compilará, pero aún es necesario dar unos pasos extra para que la aplicación arranque y podamos ejecutar los tests.

Las librerías adicionales necesarias en tiempo de ejecución ya las hemos incluido en un paso anterior, pero aún debemos configurar Arquillian. Esto se hace mediante arquillian.xml, que ubicaremos en el directorio src/test/resources del proyecto. Quedará como sigue:

<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://jboss.org/schema/arquillian
      http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
  <container qualifier="jboss-embedded" default="true">
    <configuration>
      <property name="jbossHome">/home/pagdev/pagde/tool/wildfly-8.2.0.Final</property>
      <property name="modulePath">/home/pagdev/pagde/tool/wildfly-8.2.0.Final/modules</property>
      <property name="serverConfig">standalone-full.xml</property>
    </configuration>
  </container>
</arquillian>

Aquí usamos la propiedad jbossHome, requerida, para indicar cuál es el directorio donde se halla JBoss (como JBOSS_HOME).

Esta versión del adaptador también requiere que se le pase el parámetro modulePath, que es donde se encuentran los módulos utilizables de JBoss. Por defecto están en el subdirectorio modules en JBoss. Es curioso que este parámetro sea obligatorio, dado que podrían utilizar un valor por defecto sin problemas.

También he añadido el parámetro serverConfig, que nos permite especificar qué configuración de servidor vamos a utilizar, y que no es requerido.

4. Ejecutar tests

Desafortunadamente necesitamos un pequeño workaround para un bug del adaptador embedded. Es necesario pasarle al contenedor WildFly arrancado por Arquillian el parámetro java.util.logging.manager, para el que simplemente utilizaremos el LogManager por defecto de WildFly. Esto es lo que hace el siguiente fragmento de build.gradle:


test {
  systemProperties 'java.util.logging.manager':
         'org.jboss.logmanager.LogManager'
}

Una alternativa a esto sería llamar a gradle desde la línea de comando pasándole ese parámetro. Para lanzar todos los tests del proyecto, por ejemplo, tendríamos la siguiente línea de comandos:

gradle test -Djava.util.logging.manager=org.jboss.logmanager.LogManager --tests *Test

Con la configuración actual de build.gradle, podemos lanzar el test con

gradle test --tests *Test

Por otro lado, si ejecutamos los tests desde Eclipse y no usando Gradle desde la línea de comandos, habrá que indicarle al launcher correspondiente que pase a la VM el parámetro -Djava.util.logging.manager=org.jboss.logmanager.LogManager.

Si queremos ejecutar estos tests desde la línea de comandos, y depurarlos con Eclipse, vale la pena consultar este otro artículo.

Software utilizado

Esto ha sido probado con WildFly 8.2 y Arquillian 1.1.8, usando Gradle 2.3.

Debugging tests with Gradle and Eclipse

If you use Gradle to run your tests, and are an Eclipse user but the project you are working in is not an Eclipse project, you might think that you are out of luck when it comes to debugging. But that’s not the case, you can use Eclipse to debug a test you can launch with Gradle.

Step #1: launch the test in Gradle

Launch your test with Gradle. Supposing your test is x.y.MyTest, run Gradle as follows:

gradle test --debug-jvm --tests x.y.MyTest

Because you are using the –debug-jvm thing, Gradle will wait for a debugger to get attached, as shown below:

Gradle waiting for a debugger to be attached

1. Launch the test with Gradle

STEP #2: create a Java launcher for remote debugging

To atttach the Eclipse debugger, open Eclipse and go to Run|Debug Configurations…, and create a new launcher: select the Remote Java Application type. The key point here is to use the same port Gradle is using, in this case 5005. I have called this debug launcher Gradle, debug, and have configured it as follows:

Configuring Eclipse to debug Gradle tests

2. Configure Eclipse to debug the Gradle test

Step #3: tell the launcher where to find the source code

To tell Eclipse where to find the source code, go to the Source tab in the launcher configuration. Click Add…, and choose the directory for your Java source code.

3. Tell Eclipse where to find the source code

3. Tell Eclipse where to find the source code

Debug!

Now you can use Eclipse to place some breakpoints, step through your code, etc. Just open the launcher and click Debug. Voilá!

What else?

I have tested this with Gradle 2.3 and Eclipse Luna (4.4.2).

Debugging build.gradle with Eclipse

It would be nice if we could debug our Gradle scripts in Eclipse, using all the goodies that development environment provides: syntax highlighting, code auto-completion, debugging support, etc.

And it would be even better if I could create .groovy files with all the goodies Eclipse can offer and be able to use them in our build.gradle script with little or no effort. I try hard to avoid spagueti code, and being able to distribute part of my scrips in isolated Groovy classes could help.

The good news is that we can do all of this. The bad news? There are some ugly limitations with which we’ll have to live -at least as of Eclipse Luna 4.4.2 with plugins Groovy-Eclipse 2.9.2 and Gradle IDE 3.6.4.

Before we begin

Before starting, make sure you have the following plugins installed:

  • Gradle Plugin for Eclipse.
  • Groovy Plugin for Eclipse.

Properly configured, they’ll provide us with syntax highlighting, code completion and debugging support.

Debugging a simple Gradle Script

Let’s create a debug-gradle-in-eclipse directory for the build.gradle file we want to debug and the Eclipse project we will use to debug it –which can be at the same time the Eclipse project corresponding to the gradle project.

The following build.gradle file will help us understand how and what can be debugged with Eclipse and Gradle:

apply plugin: 'eclipse'

class ClassInBuildGradle {
   ClassInBuildGradle() {
      println '*BUT* you *CAN* place a breakpoint in a class method ;)'
   }
}

void scriptFunction() {
   println 'You can\'t place a breakpoint in a script function :('
}

task sayHello &lt;&lt; {
   def configMessage = 'You can\'t place a breakpoint in a task :('
   println configMessage
   scriptFunction()
   new ClassInBuildGradle()
}

Here, we have defined a class (ClassInBuildGradle) and a function, scriptFunction, to show where you can place a breakpoint –or not.

To make things easier, we have added the eclipse plugin to generate an Eclipse project for this gradle build file. To create it, execute

   gradle eclipse

Now open Eclipse, and import the project with File|Import… and then General|Existing Projects into Workspace, choosing the project directory.

Open build.gradle in Eclipse, and you’ll notice you’ve got syntax highlighting, thanks to the Groovy/Gradle plugins.

Figura_1

Now, before adding breakpoints you need to tell Eclipse this is a Groovy project: just choose the Configure|Convert to Groovy Project from the project contextual menu (I did this in the Navigator view, selecting the project itself and right-clicking the mouse).

Once this is done, you can add breakpoints: add them at line 5 (inside a class method), line 10 (inside a script function) and line 14 (inside a task), as seen in the figure above.

Now, create a remote Eclipse debug configuration, going to Run|Debug Configurations…, and then choosing Remote Java Application. Call it debug-gradle-in-eclipse, build.gradle, and set the Port to 5005 and check the Allow termination of remote VM option. Save the configuration with Apply and then Close -do not launch it by clicking Debug.

Figura_2

Note that port 5005 is the port gradle expects a debugger to use by default.

I recommend you to store this debug configuration in your project directory, by going to the Common tab and then selecting the directory in Shared file: I stored it in the eclipse-launchers subdirectory, which is where I place this and other Eclipse launch configurations.

Next, run the sayHello gradle task from the command line as follows:

gradle sayHello –Dorg.gradle.debug=true

This will start the task for debugging, and Gradle will wait for a debugger to connect to port 5005. Do it by opening our debug configuratio and clicking Debug. Eclipse will start debugging, showing you something like this:

Figura_3

You’ll notice several things going on here.

First, Eclipse will not open the build.gradle file. This is a limitation, but you can circumvent it here by taking a look at the stack trace, where you can see that source line is number 5. So, you can open build.gradle and go to that line.

Or you can click in the Breakpoints view to jump to the source line. This is my preferred way, but you need to have build.gradle open in the editor. The Variables view is fully operative, and it will allow you to check and modify variable values.

Next, you’ll notice that the other breakpoints…they are ignored. If you take a look at the Breakpoints view you’ll see they are reported as being placed in build, which is a way to say they are located in code belonging to the script object.

No, you can’t place breakpoints in the code belonging to the script code Gradle generates under the hood, you can only place them in code for other classes defined in the script or groovy classes used by the script –more on that later. Therefore, moving as much code as possible to classes can be a good idea.

Besides, by debugging step by step you’ll be able to see the values of variables in the stack, with the same names you gave them in the source code, and you’ll quickly find the task objects, the project object, etc. Surprisingly, this can be very useful.

Yeah, ugly, but might be workable and better than debugging without a debugger. I hope next version of the Eclipse Groovy plugin solves this issue. I think we are not that far from there, given what we already have.

Important
You must execute the gradle task first, and only then launch the Eclipse debugger. If you launch the debugger first, you’ll get an error, as shown below.

Figura_4

Moving part of the Gradle Script to separate Groovy classes

If your script starts to grow, you will probably want to create your own Groovy classes to avoid spaguetti code. Gradle comes with support for this out of the box, by allowing you to write Groovy code in buildSrc. The default source directory will be in buildSrc/main/groovy.

Let’s create a Greeter.groovy class in buildSrc/main/groovy, as follows:

class Greeter {
   private String name
   Greeter(String name) {
      this.name = name
   }

   void greet() {
      def message='Greeter Groovy class greeting you, '+ this.name+'!'
      println message
   }
}

Now, we’ll use it in build.gradle by adding a line that uses it, such as

new Greeter().greet()

You’ll need to configure Gradle so that it can process these Groovy files, adding the following lines at the beginning of build.gradle:

repositories {
   mavenCentral()
}

apply plugin: 'groovy'

dependencies {
   compile gradleApi()
   compile localGroovy()
}

The last step is to help Eclipse show the source code for these groovy files when a breakpoint is hit. Just edit the debug configuration, going to the Source tab in it, and adding an entry to the Source Lookup Path: click Add…, choose the Workspace Folder option and then choose the debug-gradle-in-eclipse project and its buildSrc/main/groovy directory.

Figura_5

Now, run the gradle sayHello task from the command line as explained before, execute the Eclipse debugging configuration, and when a breakpoint in Greeter.groovy is hit the source file will open automatically.

Now, that’s much better than what we’ve got for the build.gradle script, and very helpful to create complex scripts or even Gradle plugins.

Now that we are at it…

I recommend you enable several options by using the project contextual menu and clicking Gradle|Enable DSL Support and Groovy|Enable DSL Support, which can help with working with .gradle source code.

Last, but not least, you can run the gradle tasks with the gradle daemon, as follows:

gradle sayHello --daemon –Dorg.gradle.debug=true

In this scenario, the Eclipse debugger will attach itself to the daemon, and it will be active until the daemon is stopped. This can make debugging faster, though some instability might result –both things inherent to using the gradle daemon.

DirectJNgine 3.0 just released

DirectJNgine 3.0 is finally out!

Version 3.0 signals a change from ExtJs 4.x to 5.x as the officially supported version. This means that I perform development, and especially testing, using ExtJs 5.x -at this moment the exact version is 5.1.0.

It is very likely, however, that ExtJs 4.x will work ok with DirectJNgine 3.0. But due to limited resources, I just can’t keep developing and testing against multiple versions of ExtJs.

What’s New

The main changes from 2.x to 3.0 are as follows:

  • We have moved to ExtJs 5.x as the plataform we use for development and testing.
  • We have a new connector that supports using both CDI and Spring beans at the same time (class SpringAndCdiDispatcher).
  • We have updated to the newer versions of the libraries used by DirectJNgine.
  • We have had to change how we integrate with the ExtJs Direct examples, because the Sencha guys have changed their underlying infrastructure.
  • With regards to CDI and Spring, we are testing against CDI 1.0 and 1.2 and Spring 3.2.x and 4.1.x.
  • Downloads: we have moved to http://www.softwarementors.com/directjngine/downloads/ as the go to place for downloads.

As you can see, there are not many changes, but we felt that it was important to make it clear we are moving from ExtJs 4.x to 5.x: hence the move from version 2.x to 3.x.

Spring and JPA: configuring Spring programmatically for Hibernate, EclipseLink, OpenJpa and DataNucleus

Here is my take at configuring Spring programmatically to support the more popular JPA providers out there: Hibernate, EclipseLink, OpenJpa and DataNucleus.

I am assuming you already know how to programmatically configure a data source, as well as how to use the @Configuration annotation. I’m just providing the @Bean definition for the entity manager factory.

Shared code

The following bean definition code provides common code shared by all JPA providers, and then calls configureProvider: we will isolate all provider specific code in that method.

@Bean
public LocalContainerEntityManagerFactoryBean 
  entityManagerFactory() throws PropertyVetoException 
{
  LocalContainerEntityManagerFactoryBean result =
    new LocalContainerEntityManagerFactoryBean();

  // loadTimeWeaver will be available if 
  //   @EnableLoadTimeWeaving is specified in this 
  //   config class (annotated with @Configuration)
  result.setLoadTimeWeaver(loadTimeWeaver);

  // coreDs should be a DataSource bean, 
  //   configured elsewhere.
  result.setDataSource(coreDs);

  Properties jpaProperties = new Properties();
  // ** Configuration common to all JPA 2.0 managers
  // coreDsDriverName is the database driver name!
  //    used to configure the datasource AND the 
  //    JPA provider
  jpaProperties.put( "javax.persistence.jdbc.driver", 
                     coreDsDriverName);

  // ** Provider specific config isolated here
  configureProvider(jpaProperties, result);

  result.setJpaProperties(jpaProperties);
  result.afterPropertiesSet();
  return result;
}

With this configuration you will have to provide your persistence.xml file. Just do not put a <provider> entry there: it will not be needed, we are specifying the provider programmatically.

However, if you want to remove the persistence.xml file, you can do that by specifying the packages to scan for entities programmatically, calling result.setPackagesToScan.

EclipseLink configuration

This is my very basic EclipseLink configuration. You should add EclipseLink specific configuration properties to jpaProperties, and provide configuration data to the entity manager factory bean (emf) so that it can instantiate the right provider.

private void configureProvider(Properties jpaProperties, 
     LocalEntityManagerFactoryBean emf) {
  // We want EclipseLink to recreate the database schema
  jpaProperties.put("eclipselink.ddl-generation", 
                    "drop-and-create-tables");
  emf.setJpaVendorAdapter(
    new EclipseLinkJpaVendorAdapter());
}

Hibernate configuration

This is my very basic Hibernate configuration:

private void configureProvider(Properties jpaProperties, 
     LocalEntityManagerFactoryBean emf) {
  // We want Hibernate to recreate the database schema
  jpaProperties.put(
        org.hibernate.cfg.Environment.HBM2DDL_AUTO, 
        "create-drop");
  // And we want Hibernate!
  emf.setJpaVendorAdapter(
     new HibernateJpaVendorAdapter());
}

OpenJpa configuration

OpenJpa basic configuration follows:

private void configureProvider(Properties jpaProperties, 
     LocalEntityManagerFactoryBean emf) {
  // We want EclipseLink to recreate the database schema
  jpaProperties.put("openjpa.jdbc.SynchronizeMappings", 
                    "buildSchema");
  jpaProperties.put("openjpa.InitializeEagerly", 
                    "true");

  emf.setJpaVendorAdapter(
     new OpenJpaVendorAdapter());
}

DataNucleus configuration

If you are using DataNucleus as your persistence provider, you are a bit out of luck, as Spring does not implement a vendor adapter for DataNucleus. We need to use a different approach, as follows.

private void configureProvider(Properties jpaProperties, 
     LocalEntityManagerFactoryBean emf) {
  // We want DataNucleus to recreate the database schema
  jpaProperties.put("datanucleus.autoCreateSchema", 
                    "true");
  emf.setPersistenceProviderClass(
     org.datanucleus.api.jpa.PersistenceProviderImpl.class);
}

Thats’ it!

DirectJNgine & the JEE-DJN connector 2.3 beta 1 are publicly available

The DirectJNgine 2.3 beta 1 as well as the JEE-DJN connector are now publicly available!

The main feature in DJN 2.3 will be support for pluggable adapters that will allow users to support integration with Spring, CDI/JEE, Guice, etc.

That means that it will be possible to define action classes as beans and inject Spring beans, CDI/JEE beans, etc. in them, making it very easy to work with Spring, CDI, etc.

Beta 1 is providing support just for the JEE-DJN connector, and can be downloaded from the DirectJNgine site.