mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

  • Thursday, 6 February, 2014

    Java 8 Type Annotations

    Lambda expressions are by far the most discussed and promoted feature of Java 8. While I agree that Lambdas are a large improvement I think that some other Java 8 feature go a bit short because of the Lambda hype. In this post I want to show a number of examples from another nice Java 8 feature: Type Annotations.

    Type Annotations are annotations that can be placed anywhere you use a type. This includes the new operator, type casts, implements clauses and throws clauses. Type Annotations allow improved analysis of Java code and can ensure even stronger type checking.

    In source code this means we get two new ElementTypes for annotations:

    @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
    public @interface Test {
    } 

    The enum value TYPE_PARAMETER allows an annotation to be applied at type variables (e.g. MyClass<T>). Annotations with target TYPE_USE can be applied at any type use.

    Please note that the annotations from the following examples will not work out of the box when Java 8 is released. Java 8 only provides the ability to define these types of annotations. It is then up to framework and tool developers to actually make use of it. So this is a collection of annotations frameworks could give us in the future. Most of the examples are taken from the Type Annotations specification and various Java 8 presentations.

    Simple type definitions with type annotations look like this:

    @NotNull String str1 = ...
    @Email String str2 = ...
    @NotNull @NotBlank String str3 = ...

    Type annotations can also be applied to nested types

    Map.@NonNull Entry = ...

    Constructors with type annotations:

    new @Interned MyObject()
    new @NonEmpty @Readonly List<String>(myNonEmptyStringSet)

    They work with nested (non static) class constructors too:

    myObject.new @Readonly NestedClass()

    Type casts:

    myString = (@NonNull String) myObject;
    query = (@Untainted String) str;

    Inheritance:

    class UnmodifiableList<T> implements @Readonly List<T> { ... }

    We can use type Annotations with generic type arguments:

    List<@Email String> emails = ...
    List<@ReadOnly @Localized Message> messages = ...
    Graph<@Directional Node> directedGraph = ...

    Of course we can nest them:

    Map<@NonNull String, @NonEmpty List<@Readonly Document>> documents;

    Or apply them to intersection Types:

    public <E extends @ReadOnly Composable<E> & @Localized MessageSource> void foo(...) { ... }

    Including parameter bounds and wildcard bounds:

    class Folder<F extends @Existing File> { ... }
    Collection<? super @Existing File> c = ...
    List<@Immutable ? extends Comparable<T>> unchangeable = ...

    Generic method invocation with type annotations looks like this:

    myObject.<@NotBlank String>myMethod(...);

    For generic constructors, the annotation follows the explicit type arguments:

    new <String> @Interned MyObject()

    Throwing exceptions:

    void monitorTemperature() throws @Critical TemperatureException { ... }
    void authenticate() throws @Fatal @Logged AccessDeniedException { ... }

    Type annotations in instanceof statements:

    boolean isNonNull = myString instanceof @NonNull String;
    boolean isNonBlankEmail = myString instanceof @NotBlank @Email String;

    And finally Java 8 method and constructor references:

    @Vernal Date::getDay
    List<@English String>::size
    Arrays::<@NonNegative Integer>sort

    Conclusion

    Type annotations are an interesting addition to the Java type system. They can be applied to any use of a type and enable a more detailed code analysis. If you want to use Type annotations right now you should have a look at the Checker Framework.

    If you want to continue reading about this topic you should check out the discussion on reddit.

  • Saturday, 1 February, 2014

    Java: Exception translation with AspectJ

    Within this blog post I describe how you can use AspectJ to automatically translate one type of exception to another.

    The problem
    Sometimes we are in situations where we have to convert an exception (often thrown by a third-party library) to another type of exception. Assume you are using a persistence framework like hibernate and you do not want to leak hibernate specific exceptions out of a certain application layer. Maybe you are using more than one persistence technology and you want to wrap technology specific exceptions into a common base exception. In such situations, one can end with code like this:

    public class MyRepository {
      public Object getSomeData() {     
        try {
          // assume hibernate is used to access some data
        } catch(HibernateException e) {
          // wrap hibernate specific exception into a general DataAccessException
          throw new DataAccessException(e);
        }
      }
    }

    Of course this becomes ugly if you have to do this every time you access a certain framework.

    The AspectJ way
    AspectJ is an aspect oriented programming (AOP) extension for Java. With AspectJ we can define Cross-cutting concerns that take care of the exception translation process for us.

    To get started we first have to add the AspectJ dependency to our project:

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.7.4</version>
    </dependency>

    Next we have to set up ajc, the compiler and bytecode weaver for AspectJ. This step depends on the developing environment you are using, so I will not go into details here. Eclipse users should have a look at the AspectJ Development Tools (AJDT) for Eclipse. IntelliJ IDEA users should make sure the AspectJ plugin is enabled. There is also an AspectJ Maven plugin available (check this pom.xml for an example configuration).

    Now let's define our aspect using AspectJ annotations:

    @Aspect
    public class ExceptionTranslationAspect {
    
      @Around("execution(* com.mscharhag.exceptiontranslation.repository..*(..))")
      public Object translateToDataAccessException(ProceedingJoinPoint pjp) throws Throwable {
        try {
          return pjp.proceed();
        } catch (HibernateException e) {
          throw new DataAccessException(e);
        }
      }
    }

    Using the @Aspect annotation we can declare a new aspect. Within this aspect we use the @Around annotation to define an advice that is always executed if the passed pointcut is matched. Here, the pointcut

    execution(* com.mscharhag.exceptiontranslation.repository..*(..))

    tells AspectJ to call translateToDataAccessException() every time a method of a class inside the com.mscharhag.exceptiontranslation.repository package is executed.
    Within translateToDataAccessException() we can use the passed ProceedingJoinPoint object to proceed the method execution we intercepted. In this example we just add a try/catch block around the method execution. Using the ProceedingJoinPoint instance we could also do more interesting things like analyzing the method signature using pjp.getSignature() or accessing method parameters with pjp.getArgs().

    We can now remove the try/catch block from the example repository implementation shown above and use a simple test to verify our aspect is working:

    public class MyRepositoryTest {
    
      private MyRepository repository = new MyRepository();
    
      @Test(expected = DataAccessException.class)
      public void testExceptionTranslation() {
        this.repository.getSomeData();
      }
    }


    Conclusion
    Using AspectJ we can easily automate the conversion of Java runtime exceptions. This simplifies our code by removing try/catch blocks that would otherwise be required for exception translation.

    You can find the full source of the example project on GitHub.

  • Thursday, 23 January, 2014

    Using database views in Grails

    This post is a quick explanation on how to use database views in Grails.

    For an introduction I tried to summarize what database views are. However, I noticed I cannot describe it better than it is already done on Wikipedia. Therefore I will just quote the Wikipedia summary of View (SQL) here:

    In database theory, a view is the result set of a stored query on the data, which the database users can query just as they would in a persistent database collection object. This pre-established query command is kept in the database dictionary. Unlike ordinary base tables in a relational database, a view does not form part of the physical schema: as a result set, it is a virtual table computed or collated from data in the database, dynamically when access to that view is requested. Changes applied to the data in a relevant underlying table are reflected in the data shown in subsequent invocations of the view.
    (Wikipedia)

    Example
    Let's assume we have a Grails application with the following domain classes:

    class User {
      String name
      Address address
      ...
    }

     

    class Address {
      String country
      ...
    }

    For whatever reason we want a domain class that contains direct references to the name and the country of an user. However, we do not want to duplicate these two values in another database table. A view can help us here.

    Creating the view
    At this point I assume you are already using the Grails database-migration plugin. If you don't you should clearly check it out. The plugin is automatically included with newer Grails versions and provides a convenient way to manage databases using change sets.

    To create a view we just have to create a new change set:

    changeSet(author: '..', id: '..') {
      createView("""
          SELECT u.id, u.name, a.country
          FROM user u
          JOIN address a on u.address_id = a.id
        """, viewName: 'user_with_country')
    }

    Here we create a view named user_with_country which contains three values: user id, user name and country.

    Creating the domain class
    Like normal tables views can be mapped to domain classes. The domain class for our view looks very simple:

    class UserWithCountry {
      String name
      String country
      
      static mapping = {
        table 'user_with_country'
        version false
      }
    } 

    Note that we disable versioning by setting version to false (we don't have a version column in our view).

    At this point we just have to be sure that our database change set is executed before hibernate tries to create/update tables on application start. This is typically be done by disabling the table creation of hibernate in DataSource.groovy and enabling the automatic migration on application start by setting grails.plugin.databasemigration.updateOnStart to true. Alternatively this can be achieved by manually executing all new changesets by running the dbm-update command.

    Usage
    Now we can use our UserWithCountry class to access the view:

    Address johnsAddress = new Address(country: 'england')
    User john = new User(name: 'john', address: johnsAddress)
    john.save(failOnError: true)
    
    assert UserWithCountry.count() == 1
    
    UserWithCountry johnFromEngland = UserWithCountry.get(john.id)
    assert johnFromEngland.name == 'john'
    assert johnFromEngland.country == 'england'

    Advantages of views
    I know the example I am using here is not the best. The relationship between User and Address is already very simple and a view isn't required here. However, if you have more sophisticated data structures views can be a nice way to hide complex relationships that would require joining a lot of tables. Views can also be used as security measure if you don't want to expose all columns of your tables to the application.

  • Saturday, 4 January, 2014

    Using Hibernate Filters in Grails

    The Grails Hibernate Filters plugin makes it possible to use Hibernate Filters with GORM. Hibernate Filters provide additional restriction rules that can be applied to classes and collections. The Hibernate Filters plugin makes it possible to use this functionality with GORM inside Grails applications. Let's look at an example to see how filters can help us.

    Assume we have the following Grails domain class:

    class User {
      String username
      boolean locked
    }

    The locked flag indicates if an User has been locked by an administrator for some reason. Assume that most parts of our application should treat locked users as they would not exist. To accomplish this we could add an additional condition that takes care of the locked flag to all queries that are used to retrieve User objects from the database. However, this would not be a good solution for various reasons (think of DRY, what if we have more than one flag?). Hibernate filters can be a nice help in this situation.

    Plugin installation
    To install the Hibernate Filters Plugin in a Grails application we have to do two things:

    Add the plugin dependency to BuildConfig.groovy:

    compile ":hibernate-filter:0.3.2" 

    Add the following configuration property to our dataSource definition:

    dataSource {
      ...
      configClass = HibernateFilterDomainConfiguration
    }

    Filter configuration
    Now we can add filters to our domain class using the static hibernateFilters property:

     

    class User {
      String username
      boolean locked
      static hibernateFilters = {
        lockedFilter(condition: 'locked=0', default: true)
      }
    }

    Here we define a filter with the name lockedFilter. The filter is enabled by default which means that the condition will be always applied when we query the database for User objects.

    // returns only users that are not locked
    List users = User.findAll() 
    
    // returns null if the user is locked
    User john = User.findByUsername('John') 

    However there is one exception: User.get(id) will return the User object even if the user for the given id has been locked. To apply the filter when retrieving a User by id we have to use  User.findById(id).

    In some situations we might need all users, even the locked ones (for example in the administration interface). Here we can use the withoutHibernateFilter method to disable our filter:

    User.withoutHibernateFilter('lockedFilter') {
      // get all users, including locked users
      List allUsers = User.findAll()
    }

    Filtering collections
    Hibernate Filters can also be used to filter collections. Assume users are able to upload images in our application. These images are saved in a collection in our User domain class:

    class User {
      ...
      static hasMany = [images: Image]
    }

     

    class Image {
      boolean visible
      static belongsTo = [user: User]
    }

    Administrators are able to hide inappropriate images by setting the visible property of Image to false. Images with the visible flag set to false should not be used anywhere (similar to locked users). The problem we face here is that user.getImages() returns all images of a given user by default.

    Filters can help us here again:

    class User {
      ...
      static hasMany = [images: Image]
      static hibernateFilters = {
        ...
        imagesVisibleFilter(collection: 'images', condition: 'visible=1', default: true)
      }
    }

    Here we define a filter named imagesVisibleFilter that is applied to the images collection by default. The filter condition will be applied whenever the images of a given user are retrieved from the database. If we now access the images collection using user.getImages() we only get visible images.

    Conclusion
    The Hibernate Filters plugin provides some nice and easy utilities for adding additional restrictions to domain classes and collections. The possibility to enable filters by default is a nice improvement compared to standard Hibernate in which filters need to be enabled manually for each Session instance.

    You can find the example project I created while writing this post on GitHup.

  • Wednesday, 25 December, 2013

    Java: Using the specification pattern with JPA

    This article is an introduction to using the specification pattern in Java. We also will see how we can combine classic specifications with JPA Criteria queries to retrieve objects from a relational database.

    Within this post we will use the following Poll class as an example entity for creating specifications. It represents a poll that has a start and end date. In the time between those two dates users can vote among different choices. A poll can also be locked by an administrator before the end date has been reached. In this case, a lock date will be set.

    @Entity
    public class Poll { 
      
      @Id
      @GeneratedValue
      private long id;
      
      private DateTime startDate; 
      private DateTime endDate;
      private DateTime lockDate;
      
      @OneToMany(cascade = CascadeType.ALL)
      private List<Vote> votes = new ArrayList<>();
    
    }

    For better readability I skipped getters, setters, JPA annotations for mapping Joda DateTime instances and fields that aren't needed in this example (like the question being asked in the poll).

    Now assume we have two constraints we want to implement:

    • A poll is currently running if it is not locked and if startDate < now < endDate
    • A poll is popular if it contains more than 100 votes and is not locked

    We could start by adding appropriate methods to Poll like: poll.isCurrentlyRunning(). Alternatively we could use a service method like pollService.isCurrentlyRunning(poll). However, we also want to be able to query the database to get all currently running polls. So we might add a DAO or repository method like pollRepository.findAllCurrentlyRunningPolls().

    If we follow this way we implement the isCurrentlyRunning constraint two times in two different locations. Things become worse if we want to combine constraints. What if we want to query the database for a list of all popular polls that are currently running?

    This is where the specification pattern come in handy. When using the specification pattern we move business rules into extra classes called specifications.

    To get started with specifications we create a simple interface and an abstract class:

    public interface Specification<T> {  
      boolean isSatisfiedBy(T t);  
      Predicate toPredicate(Root<T> root, CriteriaBuilder cb);
      Class<T> getType();
    }
    abstract public class AbstractSpecification<T> implements Specification<T> {
      @Override
      public boolean isSatisfiedBy(T t) {
        throw new NotImplementedException();
      }  
      
      @Override
      public Predicate toPredicate(Root<T> poll, CriteriaBuilder cb) {
        throw new NotImplementedException();
      }
    
      @Override
      public Class<T> getType() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        return (Class<T>) type.getActualTypeArguments()[0];
      }
    }

    Please ignore the AbstractSpecification<T> class with the mysterious getType() method for a moment (we come back to it later).

    The central part of a specification is the isSatisfiedBy() method, which is used to check if an object satisfies the specification. toPredicate() is an additional method we use in this example to return the constraint as javax.persistence.criteria.Predicate instance which can be used to query a database.
    For each constraint we create a new specification class that extends AbstractSpecification<T> and implements isSatisfiedBy() and toPredicate().

    The specification implementation to check if a poll is currently running looks like this:

    public class IsCurrentlyRunning extends AbstractSpecification<Poll> {
    
      @Override
      public boolean isSatisfiedBy(Poll poll) {
        return poll.getStartDate().isBeforeNow() 
            && poll.getEndDate().isAfterNow() 
            && poll.getLockDate() == null;
      }
    
      @Override
      public Predicate toPredicate(Root<Poll> poll, CriteriaBuilder cb) {
        DateTime now = new DateTime();
        return cb.and(
          cb.lessThan(poll.get(Poll_.startDate), now),
          cb.greaterThan(poll.get(Poll_.endDate), now),
          cb.isNull(poll.get(Poll_.lockDate))
        );
      }
    }

    Within isSatisfiedBy() we check if the passed object matches the constraint. In toPredicate() we construct a Predicate using JPA's CriteriaBuilder. We will use the resulting Predicate instance later to build a CriteriaQuery for querying the database.

    The specification for checking if a poll is popular looks similar:

    public class IsPopular extends AbstractSpecification<Poll> {
      
      @Override
      public boolean isSatisfiedBy(Poll poll) {
        return poll.getLockDate() == null && poll.getVotes().size() > 100;
      }  
      
      @Override
      public Predicate toPredicate(Root<Poll> poll, CriteriaBuilder cb) {
        return cb.and(
          cb.isNull(poll.get(Poll_.lockDate)),
          cb.greaterThan(cb.size(poll.get(Poll_.votes)), 5)
        );
      }
    }

    If we now want to test if a Poll instance matches one of these constraints we can use our newly created specifications:

    boolean isPopular = new IsPopular().isSatisfiedBy(poll);
    boolean isCurrentlyRunning = new IsCurrentlyRunning().isSatisfiedBy(poll);

    For querying the database we need to extend our DAO / repository to support specifications. This can look like the following:

    public class PollRepository {
    
      private EntityManager entityManager = ...
    
      public <T> List<T> findAllBySpecification(Specification<T> specification) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        
        // use specification.getType() to create a Root<T> instance
        CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(specification.getType());
        Root<T> root = criteriaQuery.from(specification.getType());
        
        // get predicate from specification
        Predicate predicate = specification.toPredicate(root, criteriaBuilder);
        
        // set predicate and execute query
        criteriaQuery.where(predicate);
        return entityManager.createQuery(criteriaQuery).getResultList();
      }
    }

    Here we finally use the getType() method implemented in AbstractSpecification<T> to create CriteriaQuery<T> and Root<T> instances. getType() returns the generic type of the AbstractSpecification<T> instance defined by the subclass. For IsPopular and IsCurrentlyRunning it returns the Poll class. Without getType() we would have to create the CriteriaQuery<T> and Root<T> instances inside toPredicate() of every specification we create. So it is just a small helper to reduce boiler plate code inside specifications. Feel free to replace this with your own implementation if you come up with better approaches.

    Now we can use our repository to query the database for polls that match a certain specification:

    List<Poll> popularPolls = pollRepository.findAllBySpecification(new IsPopular());
    List<Poll> currentlyRunningPolls = pollRepository.findAllBySpecification(new IsCurrentlyRunning()); 

    At this point the specifications are the only components that contain the constraint definitions. We can use it to query the database or to check if an object fulfills the required rules.

    However one question remains: How do we combine two or more constraints? For example we would like to query the database for all popular polls that are still running.

    The answer to this is a variation of the composite design pattern called composite specifications. Using a composite specification we can combine specifications in different ways.

    To query the database for all running and popular pools we need to combine the isCurrentlyRunning with the isPopular specification using the logical and operation. Let's create another specification for this. We name it AndSpecification:

    public class AndSpecification<T> extends AbstractSpecification<T> {
      
      private Specification<T> first;
      private Specification<T> second;
      
      public AndSpecification(Specification<T> first, Specification<T> second) {
        this.first = first;
        this.second = second;
      }
      
      @Override
      public boolean isSatisfiedBy(T t) {
        return first.isSatisfiedBy(t) && second.isSatisfiedBy(t);
      }
    
      @Override
      public Predicate toPredicate(Root<T> root, CriteriaBuilder cb) {
        return cb.and(
          first.toPredicate(root, cb), 
          second.toPredicate(root, cb)
        );
      }
      
      @Override
      public Class<T> getType() {
        return first.getType();
      }
    }

    An AndSpecification is created out of two other specifications. In isSatisfiedBy() and toPredicate() we return the result of both specifications combined by a logical and operation.

    We can use our new specification like this:

    Specification<Poll> popularAndRunning = new AndSpecification<>(new IsPopular(), new IsCurrentlyRunning());
    List<Poll> polls = myRepository.findAllBySpecification(popularAndRunning);

    To improve readability we can add an and() method to the Specification interface:

    public interface Specification<T> {
      
      Specification<T> and(Specification<T> other);
    
      // other methods
    }

    and implement it within our abstract implementation:

    abstract public class AbstractSpecification<T> implements Specification<T> {
    
      @Override
      public Specification<T> and(Specification<T> other) {
        return new AndSpecification<>(this, other);
      }
      
      // other methods
    }

    Now we can chain multiple specification by using the and() method:

    Specification<Poll> popularAndRunning = new IsPopular().and(new IsCurrentlyRunning());
    boolean isPopularAndRunning = popularAndRunning.isSatisfiedBy(poll);
    List<Poll> polls = myRepository.findAllBySpecification(popularAndRunning);

    When needed we can easily extend this further with other composite specifications (for example OrSpecification or NotSpecification).

    Conclusion
    When using the specification pattern we move business rules in separate specification classes. These specification classes can be easily combined by using composite specifications. In general, specification improve reusability and maintainability. Additionally specifications can easily be unit tested. For more detailed information about the specification pattern I recommend this article by Eric Evans and Martin Fowler.

    You can find the source of this example project on GitHub.