mscharhag, Programming and Stuff;

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

  • Monday, 21 September, 2015

    Resource versioning with Spring MVC

    When serving static resources, it is common practice to append some kind of version information to the resource URL. This allows the browser to cache resources for an unlimited time. Whenever the content of the resource is changed, the version information in the URL is changed too. The updated URL forces the client browser to discard the cached resource and reload the latest resource version from the server.

    With Spring it only takes two simple steps to configure versioned resource URLs. In this post we will see how it works.

    Serving versioned URLs

    First we need to tell Spring that resources should be accessible via a versioned URL. This is done in the resource handler MVC configuration:

    @Configuration
    public class MvcApplication extends WebMvcConfigurerAdapter {
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        VersionResourceResolver versionResourceResolver = new VersionResourceResolver()
            .addVersionStrategy(new ContentVersionStrategy(), "/**");
    
        registry.addResourceHandler("/javascript/*.js")
            .addResourceLocations("classpath:/static/")
            .setCachePeriod(60 * 60 * 24 * 365) /* one year */
            .resourceChain(true)
            .addResolver(versionResourceResolver);
      }
    
      ...
    }

    Here we create a resource handler for JavaScript files located in folder named static inside the classpath. The cache period for these JavaScript files is set to one year. The important part is the VersionResourceResolver which supports resource URLs with version information. A VersionStrategy is used to obtain the actual version for a resource.

    In this example we use a ContentVersionStrategy. This VersionStrategy implementation calculates an MD5 hash from the content of the resource and appends it to the file name.

    For example: Assume we have a JavaScript file test.js inside the classpath:/static/ directory. The MD5 hash for test.js is 69ea0cf3b5941340f06ea65583193168.

    We can now send a request to

    /javascript/test-69ea0cf3b5941340f06ea65583193168.js

    which will resolve to classpath:/static/test.js.

    Note that it is still possible to request the resource without the MD5 hash. So this request works too:

    /javascript/test.js

    An alternative VersionStrategy implementation is FixedVersionStrategy. FixedVersionStrategy uses a fixed version string that added as prefix to the resource path.

    For example:

    /v1.2.3/javascript/test.js

    Generating versioned URLs

    Now we need to make sure the application generates resource URLs that contain the MD5 hash.

    One approach for this is to use a ResourceUrlProvider. With a ResourceUrlProvider a resource URL (e.g. /javascript/test.js) can be converted to a versioned URL (e.g. /javascript/test-69ea0cf3b5941340f06ea65583193168.js). A ResourceUrlProvider bean with the id mvcResourceUrlProvider is automatically declared with the MVC configuration.

    In case you are using Thymeleaf as template engine, you can access the ResourceUrlProvider bean directly from templates using the @bean syntax.

    For example:

    <script type="application/javascript"
            th:src="${@mvcResourceUrlProvider.getForLookupPath('/javascript/test.js')}">
    </script>

    If you are using a template engine which does not give you direct access to Spring beans, you can add the ResourceUrlProvider bean to the model attributes. Using a ControllerAdvice, this might look like this:

    @ControllerAdvice
    public class ResourceUrlAdvice {
    
      @Inject
      ResourceUrlProvider resourceUrlProvider;
    
      @ModelAttribute("urls")
      public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
      }
    }

    Inside the view we can then access the ResourceUrlProvider using the urls model attribute:

    <script type="application/javascript" 
            th:src="${urls.getForLookupPath('/javascript/test.js')}">
    </script>

    This approach should work with all template engines that support method calls.

    An alternative approach to generate versioned URLs is the use of ResourceUrlEncodingFilter. This is a Servlet Filter that overrides the HttpServletResponse.encodeURL() method to generate versioned resource URLs.

    To make use of the ResourceUrlEncodingFilter we simply have to add an additional bean to our configuration class:

    @SpringBootApplication
    public class MvcApplication extends WebMvcConfigurerAdapter {
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // same as before ..
      }
    
      @Bean
      public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
        return new ResourceUrlEncodingFilter();
      }
    
      ...
    }

    If the template engine you are using calls the response encodeURL() method, the version information will be automatically added to the URL. This will work in JSPs, Thymeleaf, FreeMarker and Velocity.

    For example: With Thymeleaf we can use the standard @{..} syntax to create URLs:

    <script type="application/javascript" th:src="@{/javascript/test.js}"></script>

    This will result in:

    <script type="application/javascript" 
            src="/javascript/test-69ea0cf3b5941340f06ea65583193168.js">
    </script>

    Summary

    Adding version information to resource URLs is a common practice to maximize browser caching. With Spring we just have to define a VersionResourceResolver and a VersionStrategy to serve versioned URLs. The easiest way to generate versioned URLs inside template engines, is the use of an ResourceUrlEncodingFilter.

    If the standard VersionStrategy implementations do not match your requirements, you can create our own VersionStrategy implementation.

    You can find the full example source code on GitHub.

  • Tuesday, 1 September, 2015

    Java EE 8 MVC: Getting started with Ozark

    About a year ago a new action based MVC framework, simply called MVC, was announced for Java EE 8. MVC (specified in JSR 371) is based on JAX-RS and integrates with Java EE technologies like CDI and Bean Validation. The reference implementation for MVC 1.0 is Ozark.

    This is the first article of a multi-part tutorial I am planning to write about Java EE MVC. In this post we will see how to get a basic Java EE MVC application running with Ozark. Upcoming articles will provide more details to specific sections.

    Getting started with Ozark

    Please note that the MVC specification is still an early draft, the final specification is planned to be released in Q3 2016. To have a look at Java EE MVC in this early state, we need a recent nightly build version of GlassFish and the current Ozark milestone release. The Ozark team recommends GlassFish b13 03-16-2015 for the current Ozark version.

    Besides GlassFish we need the following dependencies to create an MVC application:

    <dependencies>
      <dependency>
        <groupId>com.oracle.ozark</groupId>
        <artifactId>ozark</artifactId>
        <version>1.0.0-m01</version>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
      </dependency>
    </dependencies>
    

    As mentioned above, Java EE MVC is based on JAX-RS. So things might look very familiar to you, if you already know about JAX-RS.

    To create our MVC application we first need a JAX-RS Application class:

    @ApplicationPath("getting-started")
    public class GettingStartedApplication extends Application {
    
    }

    This subclass of javax.ws.rs.core.Application can be used to define additional JAX-RS components. In this example we do not need any special configuration, so the class can stay empty. With @ApplicationPath we define the base path for our application.

    Creating the Controller

    A controller is responsible for processing incoming requests. Based on the incoming request it executes business logic, updates the model and returns the view that should be rendered. A simple Java EE MVC Controller looks like this:

    @Controller
    @Path("hello")
    public class HelloController {
    
      @Inject
      Models models;
    
      @GET
      public String sayHello(@QueryParam("name") String name) {
        String message = "Hello " + name;
        models.put("message", message);
        return "/WEB-INF/jsp/hello.jsp";
      }
    }

    The Controller class is annotated with @Controller and @Path. This indicates that the class is a Java EE MVC Controller that listens for requests on /getting-started/hello.

    With CDI an instance of Models is injected to the controller. The Models class represents the MVC model. It is filled with data by the controller and is then passed to the view. Models is basically a Map<String, Object> that can contain arbitrary data.

    The sayHello() method processes incoming HTTP GET requests (indicated by @GET). With @QueryParam request parameters can be bound to method parameters. Inside sayHello() the request parameter name is used to create a text message, which is then added to the Model. The returned String defines the path to the view that should be rendered.

    Creating the View

    Views in Java EE MVC applications are typically HTML pages with CSS and JavaScript files. In this example our view is a simple JSP file located at /WEB-INF/jsp/hello.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Getting started</title>
      </head>
      <body>
        <h1>${message}</h1>
      </body>
    </html>

    Inside JSP files, model properties can be accessed via EL. Here, we use ${message} to access the model value with the key message.

    The Java EE MVC specification defines two standard template engines for views: JSP and Facelets. However, other template engines can easily be integrated. We will have a look at the integration of other view technologies in an upcoming post.

    Running the application

    Now we are ready to start GlassFish and deploy our new MVC application. After that, we can send a GET request to our controller and see what it returns. Do not forget that the controller expects a name parameter.

    For example

    GET /getting-started/hello?name=john

    will result in a HTML page containing the message Hello John

    Summary

    Java EE MVC is the new upcoming Java MVC web framework. It uses a lot of existing Java technologies like JAX-RS, CDI and JSP. The framework itself is quite simple and easy to understand. The complete MVC 1.0 specification is only around 33 pages long and very easy to read.

    We can use the current milestone release of the MVC 1.0 reference implementation Ozark to get a feeling for the upcoming Java EE 8 framework.

    You can find the full source code of the example application on GitHub.

    In future blog posts we will have a look at parameter validation, exception handling and other view technologies.

  • Thursday, 4 June, 2015

    Exception Translation with ET

    Some time ago I wrote a small blog post about exception translation with AspectJ. In this blog post we will see how to accomplish the same using ET and its lighter Java 8 approach.

    Motivation

    Exception translation (or exception conversion) is the process of converting one type of exception into another. The Java code to translate an exception is quite simple and I think every Java developer writes something like this from time to time:

    try {
      // code that can throw FooException
    } catch(FooException e) {
      // convert FooException to BarException
      throw new BarException(e);
    }

    Exception translation is typically applied if exceptions from third party libraries do not fit into your application. Reasons for this might be:

    • Exceptions thrown by a library are too low level and/or you do not want to leak implementation details into other parts of your application. For example, you want to use a more generic DataAccessException instead of a lower level SQLException.
    • A library is using checked exception while you prefer using only runtime exception in your application.

    Exception Translation with ET

    ET is a small and simple library for exception translation. To get started with ET, you just need to add the following dependency to your code:

    <dependency>
      <groupId>com.mscharhag</groupId>
      <artifactId>et</artifactId>
      <version>0.2.0</version>
    </dependency>

    ET makes use of Java 8 features, so do not forget to set your compiler Level to Java 8.

    We start with configuring an ExceptionTranslator instance:

    ExceptionTranslator et = ET.newConfiguration()
        .translate(IOException.class).to(MyRuntimeException.class)        
        .translate(FooException.class, BarException.class).to(BazException.class)
        .done()

    Here we create an ExceptionTranslator that converts IOException, FooException and BarException. IOException will be translated to MyRuntimeException while FooException and BarException are translated to BazException.

    Please note that ET requires the translation target exceptions (here MyRuntimeException and BazException) to be RuntimeExceptions.
    ExceptionTranslator instances are thread safe and immutable. It is safe to configure an ExceptionTranslator once and then make it globally available.

    Now we can use our new ExceptionTranslator to wrap the code that can throw exceptions we want to convert.

    et.withTranslation(() -> {
      // can throw IOException, FooException and/or BarException
      myObject.dangerOperation(); 
    });

    If now an IOException is thrown by dangerOperation() et will catch it. et then throws a new MyRuntimeException from the caught IOException. The original IOException is stored in the cause field of MyRuntimeException.

    To return a value from a translation block withReturningTranslation() can be used:

    MyResultClass data = et.withReturningTranslation(() -> {
      ...
      return myObject.dangerOperation(); 
    });

    Summary

    ET is a small library that might be useful to you, if you have to do a lot of exception conversion in your code. After configuring your conversion rules once, exceptions can be converted by simply wrapping the code in a lambda expression.

    Have a look at the full ET documentation on GitHub.

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

  • Thursday, 26 February, 2015

    Using Java 8 Lambda expressions in Java 7 or older

    I think nobody declines the usefulness of Lambda expressions, introduced by Java 8. However, many projects are stuck with Java 7 or even older versions. Upgrading can be time consuming and costly. If third party components are incompatible with Java 8 upgrading might not be possible at all.
    Besides that, the whole Android platform is stuck on Java 6 and 7. Nevertheless, there is still hope for Lambda expressions!

    Retrolambda provides a backport of Lambda expressions for Java 5, 6 and 7.

    From the Retrolambda documentation: 

    Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7 or lower. It does this by transforming your Java 8 compiled bytecode so that it can run on a Java 7 runtime. After the transformation they are just a bunch of normal .class files, without any additional runtime dependencies.

    To get Retrolambda running, you can use the Maven or Gradle plugin.

    If you want to use Lambda expressions on Android, you only have to add the following lines to your gradle build files:

    <project>/build.gradle:

    buildscript {
      dependencies {
        classpath 'me.tatarka:gradle-retrolambda:2.4.0'    
      }
    }


    <project>/app/build.gradle:

    apply plugin: 'com.android.application'
    
    // Apply retro lambda plugin after the Android plugin
    apply plugin: 'retrolambda' 
    
    android {
      compileOptions {
        // change compatibility to Java 8 to get Java 8 IDE support  
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }
    }