mscharhag, Programming and Stuff;

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

Posts tagged with Grails

  • Friday, 10 April, 2015

    What's new in Grails 3

    A few days ago Grails 3.0 was officially released. Grails is now based on Spring Boot, the build system changed from Gant to Gradle and significant parts of the framework have been rewritten. In this post we will have a look at all the major changes introduced by Grails 3.

    Updated file structure

    We will start with a screenshot that shows a fresh Grails 3 project created from the Grails command line using

    grails create-app hello
     

    grails 3 project structure

    The first two folders (build and gradle) are related to Gradle, the new build system in Grails 3. As the name implies, build is the directory where build related files like compiled classes and assembled packages are located. The gradle directory contains the Gradle Wrapper that allows you to build the project without a local Gradle installation.

    The content of the conf folder has also been changed. The default format for configuration files is now YAML. If you prefer to write your configuration in Groovy, you can still create a grails-app/conf/application.groovy configuration file manually.
    Logback is now the default logging provider. The logging configuration (previously part of Config.groovy) has been moved to conf/logback.groovy.
    Note that the conf folder is not a source directory anymore.

    init is a new folder in Grails 3. It contains Bootstrap.groovy (same content as in previous Grails versions) and the new Application main class (we will look into this in the Spring Boot section).

    The structure of the src folder has been changed to match Gradle conventions. Additional Java and Groovy files are now located in:
    src/main/java
    src/main/groovy
    src/test/java
    src/test/groovy

    build.gradle and gradle.properties contain the build configuration. BuildConfig.groovy from previous Grails versions does no longer exist.

    Spring 4.1 and Spring Boot

    Spring Boot is the new basis for Grails. According to Graeme Rocher Grails 3 is nothing less than a ground up rewrite on top of Spring Boot.

    Like Spring Boot applications Grails 3 projects come with an Application class that has a standard main() method. This means you can start a Grails 3 application simply by running the main class from your IDE.

    The default Application class looks like this:

    class Application extends GrailsAutoConfiguration {
      static void main(String[] args) {
        GrailsApp.run(Application)
      }
    }

    Note that the war file you get when packaging the application can now be executed using the java -jar command:

    java -jar build/libs/myApplication-0.1.war

    This runs the main method which starts the application using an embedded Tomcat server. Of course you can still deploy the war file on an application server of your choice like in previous Grails versions.

    The Application class acts as Spring configuration class. So, we can use Spring's @Bean annotation to define custom beans. Methods like onStartup() or onShutdown() can be overwritten if you want to execute custom code at certain application events.

    class Application extends GrailsAutoConfiguration {
    
      ...
     
      @Bean
      MyBean myBeanId() {
        return new MyBeanImpl();
      }
     
      @Override
      void onStartup(Map<String, Object> event) {
        super.onStartup(event)
       // custom startup code..
      }
    } 
    

    Grails 3 uses Traits

    In Grails components like Controllers or Domain classes always had some magically attached functionality. For example, in Controllers you can use methods like render(), redirect() or getParams() without subclassing another class. In Grails 3 these features have been rewritten to make use of Traits introduced by Groovy 2.3.
    Certain Traits are automatically attached to Controllers, Services, Tag libraries and so on to make framework methods available. For example, a Controller automatically gets the following Traits: TagLibraryInvoker, AsyncController, RestResponder, Controller.

    The cool thing with Traits is that you can easily add them to your own classes.
    For example: Assume you want to access the request and params objects outside a Grails Controller. All you have to do now is adding the WebAttributes trait to your class:

    class MyCustomComponent implements WebAttributes {
    
      public MyCustomComponent() {
    
        // make use of WebAttributes methods like getWebRequest() or getParams()
        println "base url: " + webRequest.baseUrl
        println "params: " + params
        ...
      }
    }

    Interceptors

    Grails 3 introduced standalone Interceptors. Interceptors can intercept incoming requests to perform common tasks (e.g. logging, authentication, etc.).

    A new Interceptor can be created using create-interceptor command:
    grails create-interceptor MyInterceptor

    A newly created Interceptor looks like this:

    class MyInterceptor {
    
      boolean before() { 
        // executed before a request is processed by a controller
        true 
      }
    
      boolean after() {
        // executed after a request is processed by a controller
        true
      }
    
      void afterView() { 
        // executed after the view has been rendered
      }
    
    }

    Interceptors replace Filters used by previous Grails versions. Filters still work in Grails 3 for backwards compatibility. However, they are considered deprecated now.

    If you are aware of Spring web MVC, you can easily see the similarities to Springs Handler Interceptor.

    Gradle builds

    As mentioned before, Grails 3 uses Gradle instead of Gant as build system. Gradle is used for tasks like compilation, running tests and packaging the application.
    When a Grails command like grails clean is executed, the job is delegated to the corresponding Gradle task (e.g. gradle clean). The Gradle-Wrapper shipped with Grails 3 is used for this.
    If you want to use a local installation of Gradle you can execute the Gradle task directly with your own Gradle version. Gradle 2.2 or newer is recommended.

    The following table shows Grails commands and their corresponding Gradle tasks:

    Grails command      Gradle Task
    clean clean
    compile classes
    package assemble
    run-app run
    test-app test
    war assemble


    BuildConfig.groovy from previous Grails versions has been completely replaced by the Gradle configuration (build.gradle). Third party dependencies are now defined in build.gradle:

    dependencies {
      compile 'org.grails.plugins:hibernate' 
      compile 'org.grails.plugins:cache' 
      compile 'org.hibernate:hibernate-ehcache'
      runtime 'org.grails.plugins:asset-pipeline' 
      runtime 'org.grails.plugins:scaffolding'
      ...
    }

    For more details, you can have a look at Dependency Management Guide in the Gradle documentation.

    Grails profiles

    Whenever you run the create-app command Grails 3 will use a Profile to create a new app.
    A Profile encapsulates project structure, commands, templates and plugins. By default Grails 3 uses the web Profile, which creates an app like shown in the screenshot above.

    To create a project with a different Profile, you can use the --profile parameter:

    grails create-app myapp --profile=web-plugin

    Grails 3 comes with three different Profiles:

    • web for standard Grails web applications
    • web-plugin for web application plugins
    • web-micro a minimal micro service application

    Short summary

    Grails 3 comes with major changes. The code basis changed to Spring Boot, Gant was replaced with Gradle, existing features were reimplemented using Traits and new features like Profiles and Interceptors were added.
    With all those changes it can become quite challenging to upgrade an existing Grails 2.x application to Grails 3 (all Plugins need to be updated first). If you plan to Upgrade to Grails 3, you should have a look at the Grails 3 upgrade guide.

  • Saturday, 10 May, 2014

    Grails: The Tomcat kill switch

    Some time ago we had some strange effects when running an application in our local development environment. It turned out that the cause of these effects was a feature of the Grails Tomcat plugin.

    The actual application consists out of two different Grails applications. To run both Grails applications at the same time on our local machines we configured two different application ports. The first application (let's call it App1) was running on Port 8081 while App2 (the second application) was running on Port 8082.

    Now we faced the following effects:

    • If App2 was started before App1 everything worked fine. However, if App1 was started first, then App2 would not start and show a "Port is already in use" error instead. What?!
    • App1 contains links that point to App2. For our local environment these links look like http://localhost:8082/app2/someController. If App2 was not started at all and someone clicked one of these links App1 stopped working. What?!

    After some research it turned out, that the reason for this is the TomcatKillSwitch provided by the Tomcat plugin. This class starts a server socket that listens on serverPort + 1. If something is send to this port the embedded tomcat is shut down.

    So whenever we started App1 first the kill switch was listening at port 8082 (and therefore we were not able to start App2). Clicking any link that points to App2 triggered the kill switch and the embedded Tomcat of App1 shuts down. If we started App2 first the server socket of the kill switch failed silently on startup of App1 and everything worked as expected. Changing the port of App2 from 8082 to 8083 solved the problem.

  • Thursday, 8 May, 2014

    Grails Controller namespaces

    Grails 2.3 introduced controller namespaces. This feature gives Grails developers the option to have multiple controllers that use the same name (within different packages).

    It is not that hard to get into a situation where you want two or more controllers with the same name.
    Assume we have an application that gives users the option to update their personal profile settings. We might have a ProfileController for this. Now we might also need an administration backend which gives administrators the option to update user profiles. ProfileController would again be a good name for handling these kinds of requests.

    With Grails 2.3 we can now do this by adding namespaces to controllers using the static namespace property:
    package foo.bar.user
    
    class ProfileController {
    
      static namespace = 'user'
    
      // actions that can be accessed by users
    }
    package foo.bar.admin
    
    class ProfileController {
    
      static namespace = 'admin'
    
      // actions that can be accessed by administrators
    }
    We can now use the namespace to map the controllers to different URLs within UrlMappings.groovy:
    class UrlMappings {
    
      static mappings = { 
        '/profile' { 
          controller = 'profile' 
          namespace = 'user' 
        }
        '/admin/profile' { 
          controller = 'profile' 
          namespace = 'admin' 
        }
        ..
      }
    }
    To make the namespace part of the URL by default we can use the $namespace variable:
    static mappings = { 
      "/$namespace/$controller/$action?"() 
    }
    Using this way we are able to access our controllers with the following URLs:

    /user/profile/<action>
    /admin/profile/<action>

    Please note that we also need to provide the namespace when building links:
    <g:link controller="profile" namespace="admin">Profile admin functions</g:link>
  • Saturday, 12 April, 2014

    The Grails depedency injection inheritance pitfall

    This blog post is about a small pitfall you should be aware of when combining dependency injection in Grails with inheritance.

    I think the problem is best explained with a piece of example code. So let's look at the following two definitions of Grails controllers.

    class FooController {
      TestService testService
    
      def foo() {
        // do something with testService
      }
    }
    class BarController extends FooController {
      TestService testService
    
      def bar() {
        // do something with testService
      }
    }

    Both controllers look nearly identical. The only difference is that BarController extends FooController. Now assume we have an instance of BarController and we want to call the methods bar() and foo() on it. Guess what happens?

    The call of bar() works fine while the call of foo() throws a NullPointerException because testService is null.

    testService is a standard Groovy property. This means that the testService fields will become private and getter / setter methods are generated for both controllers. The getter / setter of BarController override the getter / setter of FooController. So whenever the dependency is injected using setTestService() only BarController retrieves the TestService instance. This is nothing special about Grails controllers, it works the same for services and other Groovy classes.

    The solution is easy: Remove the testService dependency from BarController. Whenever testService is accessed in BarController, it will use the appropriate getter of FooController and everything works.

    In this simple example the problem is quite obvious and can be easily solved. However, if your classes become larger this can be a bit tricky to debug. Assume you have a base class with multiple sub classes. Whenever you want to add a new dependency to your base class, you have to check all the subclasses. If one of the sub classes already defines the same dependency you have to remove it or it will not be available in your base class.

  • 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.