Loading...

Monday, February 8, 2016

Grails Goodness: Creating A Runnable Distribution

Grails 3.1 allows us to build a runnable WAR file for our application with the package command. We can run this WAR file with Java using the -jar option. In Grails 3.0 the package command also created a JAR file that could be executed as standalone application. Let's see how we can still create the JAR with Grails 3.1.

First we use the package command to create the WAR file. The file is generated in the directory build/libs. The WAR file can be run with the command java -jar sample-0.1.war if the file name of our WAR file is sample-0.1.war. It is important to run this command in the same directory as where the WAR file is, otherwise we get an ServletException when we open the application in our web browser (javax.servlet.ServletException: Could not resolve view with name '/index' in servlet with name 'grailsDispatcherServlet').

$ grails package
:compileJava UP-TO-DATE
:compileGroovy
:findMainClass
:assetCompile
...
Finished Precompiling Assets
:buildProperties
:processResources
:classes
:compileWebappGroovyPages UP-TO-DATE
:compileGroovyPages
:war
:bootRepackage
:assemble

BUILD SUCCESSFUL

| Built application to build/libs using environment: production
$ cd build/libs
$ java -jar sample-0.1.war
Grails application running at http://localhost:8080 in environment: production

Instead of using the Grails package command we can use the assemble task if we use Gradle: $ ./gradlew assemble

To create a runnable JAR file we only have to remove the war plugin from our Gradle build file. The package command now creates the JAR file in the directory build/libs.

$ grails package
:compileJava UP-TO-DATE
:compileGroovy
:findMainClass
:assetCompile
...
Finished Precompiling Assets
:buildProperties
:processResources
:classes
:compileWebappGroovyPages UP-TO-DATE
:compileGroovyPages
:jar
:bootRepackage
:assemble

BUILD SUCCESSFUL

| Built application to build/libs using environment: production
$ java -jar build/libs/sample-0.1.jar
Grails application running at http://localhost:8080 in environment: production

Alternatively we can use the Gradle task assemble instead of the Grails package command.

Written with Grails 3.1.

Friday, February 5, 2016

Grails Goodness: Saving Server Port In A File

In a previous post we learned how to save the application PID in a file when we start our Grails application. We can also save the port number the application uses in a file when we run our Grails application. We must use the class EmbeddedServerPortFileWriter and add it as a listener to the GrailsApp instance. By default the server port is saved in a file application.port. But we can pass a custom file name or File object to the constructor of the EmbeddedServerPortFileWriter class.

In the following example we use the file name application.server.port to store the port number:

// File: grails-app/init/sample/Application.groovy
package sample

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import groovy.transform.CompileStatic
import org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter

@CompileStatic
class Application extends GrailsAutoConfiguration {

    static void main(String[] args) {
        final GrailsApp app = new GrailsApp(Application)

        // Save port number in file name application.server.port
        final EmbeddedServerPortFileWriter serverPortFileWriter =
                new EmbeddedServerPortFileWriter('application.server.port')

        // Add serverPortFileWriter as application listener
        // so the port number is saved when we start
        // our Grails application.
        app.addListeners(serverPortFileWriter)
        
        app.run(args)
    }
    
}

When the application is started we can find the file application.server.port in the directory from where the application is started. When we open it we see the port number:

$ cat application.server.port
8080
$

Written with Grails 3.1.

Monday, February 1, 2016

Awesome Asciidoctor Notebook Is Updated

I've written a couple of new blog posts about Asciidoctor the last couple of months, so it was time to also update the Awesome Asciidoctor Notebook. If you've downloaded the book before, you can download the latest version. The book is free, so you download it if you didn't download it before. The following subjects have been added to the new version:

  • Leave Section Titles Out of Table Of Contents
  • Using Asciidoctor In Javadoc Comments

Spocklight Notebook Is Updated

I've written a couple of new blog posts about Spock the last couple of months, so it was time to also update the Spocklight Notebook. If you've downloaded the book before, you can download the latest version. The book is free, so you download it if you didn't download it before. The following subjects have been added to the new version:

  • Mocks And Stubs Returning Sequence of Values
  • Grouping Assertions

Groovy Goodness Notebook Is Updated

Groovy Goodness Notebook which contains the Groovy blog posts in an organised form is updated with the following blog posts. If you have purchased the book before you get the update for free.

  • Inspect Method Returns Nicely Formatted Object Values
  • Operator Overloading in Reverse
  • Removing Elements From a Collection
  • Change Directory For Saving Dependencies Grape
  • See More Info About Downloading With Grape
  • Exclude Transitive Dependencies With Grape
  • IntelliJ IDEA Intentions For String Values
  • Turn Map Into Class With IntelliJ IDEA
  • Turn Method Parameters Into Named Map Arguments With IntelliJ IDEA
  • Defining Public Accessible Constant Fields
  • Customise Groovydoc Output With Gradle
  • Customising The Groovy Compiler

Gradle Goodness Notebook Updated

Gradle Goodness Notebook has been updated. If you have bought the book you can download the latest version for free. The following blog posts have been added:

  • Quickly Open Test Report in IntelliJ IDEA
  • Getting More Help For a Task
  • Pass Java System Properties To Java Tasks
  • Download Javadoc Files For Dependencies In IDE
  • Setting Global Properties For All Gradle Builds
  • Apply External Script With Plugin Configured Through Buildscript
  • Getting Information About Buildscript Dependencies

Grails Goodness Notebook Updated

Grails Goodness Notebook has been updated with the latest blog posts. If you have purchased the book before you can download the latest version of the book for free.

New posts in the book are:

  • Run Grails Application As Docker Container
  • Enable Hot Reloading For Non-Development Environments
  • Change Locale With Request Parameter
  • Go To Related Classes In IntelliJ IDEA
  • Quickly Create GSP From Controller In IntelliJ IDEA
  • Using Spring Cloud Config Server
  • Changing Gradle Version
  • Getting More Information About A Profile
  • Using Features When Creating An Application

Friday, January 29, 2016

Spocklight: Grouping Assertions

In a Spock specification we write our assertion in the then: or expect: blocks. If we need to write multiple assertions for an object we can group those with the with method. We specify the object we want write assertions for as argument followed by a closure with the real assertions. We don't need to use the assert keyword inside the closure, just as we don't have to use the assert keyword in an expect: or then: block.

In the following example specification we have a very simple implementation for finding an User object. We want to check that the properties username and name have the correct value.

@Grab("org.spockframework:spock-core:1.0-groovy-2.4")
import spock.lang.Specification
import spock.lang.Subject

class UserServiceSpec extends Specification {

    @Subject
    private UserService userService = new DefaultUserService()
    
    def "check user properties"() {
        when:
        final User user = userService.findUser("mrhaki")
        
        then:
        // Assert each property.
        user.username == "mrhaki"
        user.name == "Hubert A. Klein Ikkink"
    }

    def "check user properties using with()"() {
        when:
        final User user = userService.findUser("mrhaki")
        
        then:
        // Assert using with().
        with(user) {
            username == "mrhaki"
            name == "Hubert A. Klein Ikkink"
        }
    }

    def "check expected user properties using with()"() {
        expect:
        with(userService.findUser("mrhaki")) {
            username == "mrhaki"
            name == "Hubert A. Klein Ikkink"
        }
    }
    

}

interface UserService {
    User findUser(final String username)    
}

class DefaultUserService implements UserService {
    User findUser(final String username) {
        new User(username: "mrhaki", name: "Hubert A. Klein Ikkink")
    }
}

class User {
    String username
    String name
}

Written with Spock 1.0.

Grails Goodness: Using Features When Creating An Application

With the release of Grails 3.1 we can use features, defined in a profile, when we create a new application. Features will add certain dependencies to our Grails project, so we can start quickly. To see which features are available we use the profile-info command. This command lists available features for an application. We can choose the features we want to be included and pass them via the --features command line option of the create-app command.

When we look at the features available for the rest-api profile we see the following list:

$ grails profile-info rest-api
...
Provided Features:
--------------------
* asset-pipeline - Adds Asset Pipeline to a Grails project
* hibernate - Adds GORM for Hibernate to the project
* json-views - Adds support for JSON Views to the project
* markup-views - Adds support for Markup Views to the project
* mongodb - Adds GORM for MongoDB to the project
* neo4j - Adds GORM for Neo4j to the project
* security - Adds Spring Security REST to the project

$

Let's create a new Grails application with the rest-api profile and use the mongodb, json-views and security features:

$ grails create-app --profile rest-api --features mongodb,json-views,security api
| Application created at /Users/mrhaki/Projects/mrhaki.com/blog/posts/samples/grails31/api
$

When we look at the contents of the generated build.gradle we can see dependencies for the features we have selected:

// File: build.gradle
buildscript {
    ext {
        grailsVersion = project.grailsVersion
    }
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "org.grails.plugins:views-gradle:1.0.0"
    }
}

version "0.1"
group "api"

apply plugin:"eclipse"
apply plugin:"idea"
apply plugin:"org.grails.grails-web"
apply plugin:"org.grails.plugins.views-json"

ext {
    grailsVersion = project.grailsVersion
    gradleWrapperVersion = project.gradleWrapperVersion
}

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    applyMavenExclusions false
}

dependencies {
    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    compile "org.springframework.boot:spring-boot-starter-tomcat"
    compile "org.grails:grails-plugin-url-mappings"
    compile "org.grails:grails-plugin-rest"
    compile "org.grails:grails-plugin-codecs"
    compile "org.grails:grails-plugin-interceptors"
    compile "org.grails:grails-plugin-services"
    compile "org.grails:grails-plugin-datasource"
    compile "org.grails:grails-plugin-databinding"
    compile "org.grails:grails-plugin-async"
    compile "org.grails:grails-web-boot"
    compile "org.grails:grails-logging"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:views-json"
    compile "org.grails.plugins:mongodb"
    compile "org.grails:grails-plugin-gsp"
    compile "org.grails.plugins:spring-security-rest:2.0.0.M1"
    console "org.grails:grails-console"
    profile "org.grails.profiles:rest-api:3.1.0"
    testCompile "org.grails:grails-plugin-testing"
    testCompile "org.grails.plugins:geb"
    testCompile "org.grails:grails-datastore-rest-client"
    testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
    testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
}

task wrapper(type: Wrapper) {
    gradleVersion = gradleWrapperVersion
}

Written with Grails 3.1.

Grails Goodness: Getting More Information About A Profile

Since Grails 3.1 we can use the profile-info command to get more information about a profile. We see which commands are added to our project by the profile and which features can be chosen when we create a new application with the profile.

Suppose we want to know more about the rest-api profile then we invoke the profile-info command:

$ grails profile-info rest-api
Profile: rest-api
--------------------
Profile for Web API applications

Provided Commands:
--------------------
* create-controller - Creates a controller
* create-domain-resource - Creates a domain class that represents a resource
* create-functional-test - Creates an functional test
* create-integration-test - Creates an integration test
* create-interceptor - Creates an interceptor
* create-restful-controller - Creates a REST controller
* help - Prints help information for a specific command
* open - Opens a file in the project
* gradle - Allows running of Gradle tasks
* clean - Cleans a Grails application's compiled sources
* compile - Compiles a Grails application
* create-domain-class - Creates a Domain Class
* create-service - Creates a Service
* create-unit-test - Creates a unit test
* dependency-report - Prints out the Grails application's dependencies
* install - Installs a Grails application or plugin into the local Maven cache
* assemble - Creates a JAR or WAR archive for production deployment
* bug-report - Creates a zip file that can be attached to issue reports for the current project
* console - Runs the Grails interactive console
* create-script - Creates a Grails script
* list-plugins - Lists available plugins from the Plugin Repository
* plugin-info - Prints information about the given plugin
* run-app - Runs a Grails application
* shell - Runs the Grails interactive shell
* stats - Prints statistics about the project
* stop-app - Stops the running Grails application
* test-app - Runs the applications tests
* generate-all - Generates a controller that performs REST operations
* generate-controller - Generates a controller that performs REST operations
* generate-functional-test - Generates a functional test for a controller that performs REST operations
* generate-unit-test - Generates a unit test for a controller that performs REST operations
* generate-views - Generates a controller that performs REST operations

Provided Features:
--------------------
* asset-pipeline - Adds Asset Pipeline to a Grails project
* hibernate - Adds GORM for Hibernate to the project
* json-views - Adds support for JSON Views to the project
* markup-views - Adds support for Markup Views to the project
* mongodb - Adds GORM for MongoDB to the project
* neo4j - Adds GORM for Neo4j to the project
* security - Adds Spring Security REST to the project

$

Written with Grails 3.1.