Help

Inactive Bloggers

It's my pleasure to announce a new release of Hibernate OGM.

Hibernate OGM can now convert JP-QL queries into cypher queries when working with Neo4j. We improved the JSON representation used for associations in CouchDB and MongoDB making it more concise. We also worked on several bug fixes and improvements under the hood, you can read more about it in the release note.

As always, you can either download a release bundle from SourceForge or retrieve the JARs from the JBoss Nexus repository server using Maven, Gradle etc. The GAV coordinates are:

  • org.hibernate.ogm:hibernate-ogm-core:4.1.0.Beta5 for the OGM engine and
  • org.hibernate.ogm:hibernate-ogm-<datastore>:4.1.0.Beta5, depending on the backend you want to use.

From JP-QL to Cypher

For example, if you execute the following JP-QL query:

from Hypothesis h where h.author IN ('alma', 'alfred')

OGM will execute the following Cypher query on Neo4j:

MATCH (h:Hypothesis) WHERE ANY(_x_ IN ["alma", "alfred"] WHERE h.author = _x_) RETURN h

The following subset of JP-QL constructs is available at the moment:

  • simple comparisons
  • IS NULL and IS NOT NULL
  • the boolean operators AND, OR, NOT
  • LIKE, IN and BETWEEN
  • ORDER BY

More natural mapping for associations in MongoDB and CouchDB

In the previous releases, an entity with an association looked something like the following JSON:

{
   "_id": "4f5b48ad",
   ...
   "rows": [
       {
           "bankAccounts_id": "7873a2a7"
       }
   ]
}

We got rid of the name of the id in the rows field, this will now look like:

{
   "_id": "4f5b48ad",
   ...
   "rows": [
       {
           "7873a2a7"
       }
   ]
}

What's next?

Some work on the Neo4j side is still required to make the mapping of the entities more natural. We also want to add caching in several places to improve performance (OGM-541, OGM-515, OGM-522).

We are also discussing about a solution for the generation of error reports with the failed operations on non-transactional db.

You're very welcome to raise your voice on the mailing list, ask questions in the forum or report any bugs or feature requests in the issue tracker.

If you’re looking for a simple way to secure your Java EE application’s classes and methods, then PicketLink in conjunction with DeltaSpike provides an elegant and flexible solution thanks to DeltaSpike’s support for typesafe security annotations. This powerful combination means you can easily apply security to your application in three simple steps, which we’ll be examining in more detail in this article.

Before we get started though, let’s take a closer look at each of these individual projects.

PicketLink

PicketLink (http://www.picketlink.org) is an application security framework for Java EE. It provides features such as Identity Management (IDM), credential management, authentication API, permissions and permission management, plus much more. At the time of writing, the latest available version of PicketLink is 2.6.0.Final.

Apache DeltaSpike

Apache DeltaSpike (http://deltaspike.apache.org) is a collection of portable extensions for Java EE, built on top of the CDI (Contexts and Dependency Injection) standard. It enhances the Java EE platform by providing a set of useful features for application developers. The latest release of Deltaspike is 1.0.

Setting up the Maven Dependencies

This step is required to add the PicketLink libraries to your application. Start by defining a property value for the version of PicketLink that you’ll be using - the latest version at time of writing is 2.6.0.Final. Add the following property declaration to the <properties> section of your project’s pom.xml:

  <properties>
    <!-- PicketLink dependency versions -->
    <version.picketlink.javaee.bom>2.6.0.Final</version.picketlink.javaee.bom>
  </properties>

Then add the PicketLink BOM to the <dependencyManagement> section:

  <dependencyManagement>
    <dependencies>
      <!-- Dependency Management for PicketLink and Apache Deltaspike. -->
      <dependency>
        <groupId>org.picketlink</groupId>
        <artifactId>picketlink-javaee-6.0</artifactId>
        <version>${version.picketlink.javaee.bom}</version>
        <scope>import</scope>
        <type>pom</type>
      </dependency>
    </dependencies>
  </dependencyManagement>

Finally, add the PicketLink dependency to the <dependencies> section:

    <dependency>
      <groupId>org.picketlink</groupId>
      <artifactId>picketlink</artifactId>
      <scope>compile</scope>
    </dependency>

We’re done! The next step is to enable the DeltaSpike security interceptor.

Enabling the Security Interceptor

For the security interceptor to perform authorization checks for the classes or methods that we wish to secure with our security binding annotations, we must first enable it in our application’s beans.xml file. In a web application this file can be found in the WEB-INF directory. Add the <interceptors> section as shown in the following example:

<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <interceptors>
        <class>org.apache.deltaspike.security.impl.extension.SecurityInterceptor</class>
    </interceptors>
</beans>

Step 1: Create the Security Annotation

This first step is extremely simple - all we need to do is create an annotation and meta-annotate it with @SecurityBindingType. As an example let’s create a security annotation that we can use to restrict access only to users that are currently logged in:

@Retention(value = RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@SecurityBindingType
public @interface LoggedIn { }

Make sure that the @Target is set to both TYPE and METHOD - this will ensure that the annotation can be used to secure either all the methods of a class (when applied to the class itself) or to secure individual methods. The @SecurityBindingType annotation can be found in the org.apache.deltaspike.security.api.authorization package.

Step 2: Create the Authorizer method

This step is where we’ll be implementing the business logic for our security annotation. Each security binding annotation requires a corresponding authorizer method. This method must match the security binding annotation and any of its member values (excluding those annotated with @NonBinding, mirroring the behaviour of CDI itself). There must be exactly one authorizer method per unique security binding annotation usage.

The authorizer method can be placed in a bean class of your choosing, and there are no restrictions on the scope of the bean (in the following example we’ll use an @ApplicationScoped bean). Besides the security binding annotations, the authorizer method must also be annotated with @Secures, to denote that the method is being used to secure that security binding type:

@ApplicationScoped
public class Authorizer {
    @Secures
    @LoggedIn
    public boolean isLoggedIn(InvocationContext invocationContext, Identity identity) {
        return identity.isLoggedIn();
    }
}

The parameters of the authorizer method are treated as injection points (except for parameters of type InvocationContext which may be used to inspect metadata pertaining to the method from which the security check is being invoked). In the above example, we inject the Identity bean which represents the currently authenticated user - the Identity bean provides a method called isLoggedIn() that allows us to check if the current user is logged in.

Step 3: Apply the annotation to your methods

By the time we reach this step all of the hard work has been already done. The only remaining task is to apply the new security binding annotation to the methods and/or classes that you wish to secure. Let’s start off with a really simple example:

@RequestScoped
public class PostController {
    @LoggedIn
    public void getNewPosts() {
        // business logic here
    }
}

In this code we’ve applied our @LoggedIn security binding annotation to the getNewPosts() method of a request-scoped bean called PostController. When the user invokes this method, the security interceptor will intercept the method call and invoke the authorizer method to determine if the currently authenticated user is logged in. If the authorizer method returns true then the method invocation will then proceed as normal, otherwise an AuthorizationException will be thrown. If we would like to apply the same security restriction to all of the methods of a bean, we can put the annotation on the bean class instead:

@LoggedIn
@RequestScoped
public class PostController {
    public void getNewPosts() {
        // business logic here
    }
}

A Complete Example

You can find a complete example of using PicketLink with DeltaSpike in the following quickstart project:

https://github.com/jboss-developer/jboss-picketlink-quickstarts/tree/master/picketlink-deltaspike-authorization

Summary

In this article we examined how we can get the most out of DeltaSpike’s security annotation feature by combining it with a powerful security framework such as PicketLink. By following three simple steps we learned how to define a new security annotation, implement its business logic and then apply it to the methods and classes which we wish to protect.

26. Jun 2014, 08:19 CET, by Gail Badner

Hibernate ORM 4.2.14.Final was just released! Please see the full changelog for more information: https://hibernate.atlassian.net/secure/ReleaseNote.jspa?projectId=10031&version=17152.

Another 4.2.x version was necessary to make the following changes:

  • HHH-9255 reverts HHH-9222, which caused incorrect SQL to be generated when bulk deleting collections that use a property-ref;
  • HHH-9252 fixes a bug where an error executing a batch did not abort the rest of the batch.

JBoss Nexus: https://repository.jboss.org/nexus/content/groups/public/org/hibernate
Maven Central: http://repo1.maven.org/maven2/org/hibernate/hibernate-core (should update in a couple of days)
SourceForge: https://sourceforge.net/projects/hibernate/files/hibernate4
Downloads: 4.2.14.Final ZIP, 4.2.14.Final TGZ

This post is about validation, Bean Validation specifically. And the what it solves. It is a reaction to a post by Julien Tournay which basically claims - if I sum it up - that:

  • Scala is faster than Java (he is coming from far far away on that one - du diable vauvert as we say in French)
  • Bean Validation is kind of crap
  • The new Play Unified Validation API is awesome

I usually am old and wise enough not to answer these kind of posts. But I want to feel the blood of my youth again damn it! After all I am from an era when The Server Side was all the rage, trolls had real teeth, things were black or white. That was good fun.

Why the You missed the point like Mars Climate Orbiter title? With a sensationalist title like Scala is faster than Java, I had to step up my game. Plus Mars Climate Orbiter missed Mars due to a conversion error and we will talk about conversion today.

I won't refute things point by point but rather highlight a few fundamental misunderstandings and explain why things are like they are in Bean Validation and why it makes sense.

Java was limiting

IMHO, @emmanuelbernard a créer son API avec les outils a sa disposition - @skaalf
IMHO, @emmanuelbernard has created his API with the tools he had at his disposal - @skaalf

We certainly pushed the boundaries of Java when both CDI and Bean Validation were designed and I wished I had more freedom here and there. But no Bean Validation is like it is because that's the most natural way validation is expressed in the Java ecosystem for what we wanted to achieve. It is no good to offer something that does not fit into the ecosystem.

For example, in Java, people use mutable objects. Mutable believe it or not is not a swear word in this language. My understanding is that Play Unified Validation API makes use of Scala's community incline for immutability.

Validation, conversion and marshalling

In the use case Julien takes as an example, a JSON string is unmarshalled, conversion is applied (for dates - darn JSON) and then values are validated. He considers it weird that Bean Validation only does the latter and finds the flow wrong.

We kept this separation on purpose. The expert group vastly agreed that Bean Validation was not in the business of conversion and that these steps ((un)marshalling, conversion, validation) should be separated. Here is a key reason:

  • marshalling and conversions are only at the Java boundaries (Web frameworks, services enpoints, datastores enpoints, etc)
  • validation happens both at these boundaries but also at key lifecycle events within the Java boundaries

Conceptually, separating validation from the rest makes a lot of sense to enable technology composition and avoid repetitions - more on that latter point later. What is important is that for a given boundary, they are properly integrated. It's not unlike inlining in compilation.

Bean Validation is in the business of not being called

One key point in the design of Bean Validation is that it has been built to be integrated within a cohesive stack more than to be used individually.

JPA transparently calls Bean Validation on your objects at the right time. JSF calls Bean Validation transparently before populating the beans. JAX-RS calls Bean Validation on the inbound and outbound resources transparently. Note that these three technologies do address the marshalling and conversion problem already. That's their job.

So the key is that an application rarely has to call the Bean Validation API. I consider it a failure or an unfinished work when it has to.

If you need to explicitly validate some piece of data in a fire and forget way, Bean Validation might not be the best tool. And that's OK.

Back to the JSON case. When the JSON Binding spec will be out, we will have the same integration that is currently present in Play Unified parsing, conversion and validation API (it could also be done today in Jackson, I'm not sure what extension points this library offers). While the three layers marshalling / conversion / validation will be conceptually separated - and I'm sure will report different types of error for better tracking - the implementation will use some specific APIs of Bean Validation to inline validation with the unmarshalling and conversion. That API exists BTW, it is Validator.validateValue which lets you validate a value without creating the POJO associated. It is used by web frameworks already. Pretty much what Play Unified Validation API does.

As for JAX-B and XML binding, well let's say that there is an X in it and that it's not safe for children. More seriously, we have integration plans with mapping between the XSD and the Bean Validation constraints but we haven't got around to do it yet.

Bean Validation is in the business of declaring constraints once

From what I see of the Play Unified Validation API, you put the declaration / implementation of the validation next the marshalling logic. In other words you cannot share the constraint declaration between different marshalling operations or even between object transformations.

Bean Validation has been designed to let the user declare the constraints once and have them validated across the whole stack. From the web form and service entry points down to the database input/output and schema definition. Some even use our metadata facility to propagate the constraints up to the client side (JavaScript).

And that's future proof, when we add JSON-B support, boom the constraints already declared are used automatically and for free.

Conclusion

Bean Validation cannot be understood if you take it in isolation. It is useful and works in isolation for sure but it shines when integrated in a platform from top to bottom. We did and keep doing it in Java EE but we also make sure to keep our APIs and SPIs open for other platforms to do the same. Spring famously has been doing some of it.

Let's mention a few key features of Bean Validation that are not addressed at all in Play's approach:

  • i18n
  • constraint inheritance
  • method validation
  • custom and context sensitive programmatic error report
  • partially valid object graph - yes that's important in a mutable world
  • etc

Even a few of these would make Play's stuff much much different.

Now with this context properly set, if you read back Julien's complaints about Bean Validation (especially about they design), they fall one by one pretty much. I have to admit their composition approach is much nicer than Bean Validation's which relies on annotated annotations. That's the main thing I miss.

Design is choice. Without knowledge to the designer's choices, you can too easily misunderstand her design and motives. Julien has been comparing Apples with Oranges, which is ironic for someone working on one of the most type-safe language out there :o)

But it's good that more people take data validation holistically and seriously and step up the game. Less work for app developers, safer apps, happier customers. Judging by the location, I could even share some thoughts over a few rounds of whisky with Julien :)

Peace.

I'm happy to announce a new release of Hibernate OGM.

The MongoDB backend now supports the MongoDB CLI syntax for native queries. In Neo4j, we have solved a bug related to the way we store embedded collections (OGM-549) and we now create only one relationship for bidirectional associations. We have also worked on the compatibility with WildFLy 8.1. You can find more details about this release on JIRA.

As always, you can either download a release bundle from SourceForge or retrieve the JARs from the JBoss Nexus repository server using Maven, Gradle etc. The GAV coordinates are:

  • org.hibernate.ogm:hibernate-ogm-core:4.1.0.Beta4 for the OGM engine and
  • org.hibernate.ogm:hibernate-ogm-<datastore>:4.1.0.Beta4, depending on the backend you want to use.

Support for MongoDB CLI syntax

You can now specify queries using the MongoDB CLI syntax as shown in the following example:

    @Entity
    class Poem {
       ...
       String name;
       String author;
       ...
    }

    String poemsQuery = "db.Poem.find({'$query': { 'author': 'Oscar Wilde' }, '$orderby': { 'name': 1 }})";

    EntityManager em = ...
    List<Poem> oscarWildePoems = (List<Poem>)em.createNativeQuery( poemsQuery, Poem.class )
                                 .getResultList();

Currently only find() and count() queries are supported via the CLI syntax.

One relationship for bidirectional associations

In Neo4j, it is possible to navigate a relationship in both directions at the same speed. We moved to a more natural mapping using one relationship (instead of two) for a bidirectional association.

What's next?

For the Neo4j backend, we plan to make the mapping for one-to-one relationships more natural, remove redundant properties and translate JP-QL queries into native Cypher queries.

We will also work on the generation of error reports with the failed operations on non-transactional db.

You're very welcome to raise your voice on the mailing list, ask questions in the forum or report any bugs or feature requests in the issue tracker.

Showing 6 to 10 of 1215 blog entries