mscharhag, Programming and Stuff;

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

  • 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
      }
    }
  • Monday, 23 February, 2015

    Static code analysis with JArchitect

    A few months ago Dane from JArchitect team was nice enough to offer me a free JArchitect 4 Pro license. Over the last days I finally managed to look into JArchitect.

    JArchitect is a quite powerful static code analyser for JVM languages (besides Java it also supports Scala, Groovy and others). It is available for Windows, Linux and Mac OS X. In this post I want to show you some of JArchitect's features.

    Getting started with JArchitect

    As an example I analysed the popular Java Library JUnit using JArchitect. The Screenshots you in this post are all taken from the JUnit analysis result.

    Importing JUnit into JArchitect was actually quite simple. Note that JArchitect analyses the compiled byte code, source files are not required. So I cloned the JUnit repository and called mvn compile. After that, all I had to do was adding JUnit's pom.xml to a new JArchitect project.

    After pressing the Run Analysis button JArchitect summarizes common metrics on a dashboard screen:
     

    JArchitect Dashboard


    Here we can see the lines of code, method complexity, comment rate and various other values. This summary is followed by a couple of trend charts that show how these values changed over time.

    JArchitect trend chart

    Of course you can also configure your own charts, if you want to see trends of different values.

    Analyzing dependencies

    Next we will look at the third party dependencies of JUnit. JArchitect provides a nice interactive graph for this.

    JArchitect dependency graph (1)
     

    Since JUnit only depends on the Java Runtime (rt) and Hamcrest this graph does not have much to show. I am sure you can imagine that this could be much more complex for a larger project.

    Looking at JUnits package dependencies is a bit more interesting. The following Screen shows a section of JUnits package dependency graph.

     

    JArchitect dependency graph (2)

     


    I selected the junit.framework package to see how this package relates to other packages. The different colored arrows show which packages use junit.framework (green), which other packages are used by junit.framework (blue) and mutually dependent packages (red).

    The dependency matrix is another way to look at project dependencies:

     

    JArchitect dependency matrix (1)


    This matrix style view shows you exactly the dependencies between different components (packages, classes or methods). Here I selected the blue field with the number 10 (where the orange lines cross). This shows that the junit.framework package uses 10 members of the java.lang.reflect package (the dependency direction is shown by the white arrow at the selected field).

    We can dig deeper, and look at this at class and method level.

     

    JArchitect dependency matrix(2)


    So it looks like the class junit.framework.TestCase makes use of the method java.lang.Class.getName().

    Tree maps

    Tree map charts are another way to look into a project with JArchitect. The following chart shows the number of code lines in JUnit packages, classes and methods.

     

    JArchitect metrics

     

    In this example chart we cannot see any overly large rectangle, which is a good sign. This probably means that complex parts are well divided into multiple classes and packages (no god object is present).

    JArchitect can generate such tree maps for lines of code, cyclomatic complexity, number of variables and various other metrics.

    Code queries

    To extract various metrics out of a project, JArchitect uses a custom query language call Code Query Linq (CQLinq). As the name suggests this is a query language based on LINQ.

     

    JArchitect queries

     

    This image shows the query of JArchitect's Methods with too many parameters rule. It looks for methods with more than 8 parameters and creates a warning if one or more methods are found.

    You can see (and change) all the standard queries provided by JArchitect. Code queries are actually a very cool feature. You can easily create your own queries to extract project specific data you are interested in. 

    Quick summary

    JArchitect is a powerful tool for static code analysis. It can provide a lot of insight into complex code bases. Using custom code queries you are able to build your own rule sets in a very comfortable way.

    In this example I used the JArchitect user interface (VisualJArchitect) for running the code analysis and viewing the results. It is also possible to integrate JArchitect directly into your build process (using a Maven plugin or command line tools). This way you are able to automatically create reports in HTML format.