Loading...

Friday, February 12, 2016

Gradle Goodness: Specify Spock As Test Framework At Initialization

Since Gradle 2.11 we can specify the test framework to use when we initialise a project with the init task. There is a new option for this task: --test-framework. By default JUnit dependencies are added, but if we specify the value spock the Spock libraries are included in the dependencies section of our build.gradle file.

Let's run the init task to create a Java project with Spock as test framework:

$ gradle init --type java-library --test-framework spock

Let's see the contents of the build.gradle file that is generated:

/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'mrhaki' at '2/12/16 8:54 AM' with Gradle 2.11
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.11/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'

// Apply the groovy plugin to also add support for Groovy (needed for Spock)
apply plugin: 'groovy'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.14'

    // We use the latest groovy 2.x version for Spock testing
    compile 'org.codehaus.groovy:groovy-all:2.4.5'

    // Use the awesome Spock testing and specification framework even with Java
    testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
    testCompile 'junit:junit:4.12'
}

Notice in the dependencies section that the Groovy and Spock dependencies are added.

Written with Gradle 2.11.

Wednesday, February 10, 2016

Gradle Goodness: Running Groovy Scripts Using Groovy Command Line

In a previous post we have seen how to execute a Groovy script in our source directories. But what if we want to use the Groovy command line to execute a Groovy script? Suppose we want to evaluate a small Groovy script expressed by a String value, that we normally would invoke like $ groovy -e "println 'Hello Groovy!'". Or we want to use the command line option -l to start Groovy in listening mode with a script to handle requests. We can achieve this by creating a task with type JavaExec or by using the Gradle javaexec method. We must set the Java main class to groovy.ui.Main which is the class that is used for running the Groovy command line.

In the following sample build file we create a new task runGroovyScript of type JavaExec. We also create a new dependency configuration groovyScript so we can use a separate class path for running our Groovy scripts.

// File: build.gradle

repositories {
    jcenter()
}

// Add new configuration for 
// dependencies needed to run
// Groovy command line scripts.
configurations {
    groovyScript
}

dependencies {
    // Set Groovy dependency so 
    // groovy.ui.GroovyMain can be found.
    groovyScript localGroovy()
    // Or be specific for a version:
    //groovyScript "org.codehaus.groovy:groovy-all:2.4.5"
}

// New task to run Groovy command line
// with arguments.
task runGroovyScript(type: JavaExec) {

    // Set class path used for running
    // Groovy command line.
    classpath = configurations.groovyScript

    // Main class that runs the Groovy
    // command line.
    main = 'groovy.ui.GroovyMain'

    // Pass command line arguments.
    args '-e', "println 'Hello Gradle!'"

}

We can run the task runGroovyScript and we see the output of our small Groovy script println 'Hello Gradle!':

$ gradle runGroovyScript
:runGroovyScript
Hello Gradle!

BUILD SUCCESSFUL

Total time: 1.265 secs
$

Let's write another task where we use the simple HTTP server from the Groovy examples to start a HTTP server with Gradle. This can be useful if we have a project with static HTML files and want to serve them via a web server:

// File: build.gradle

repositories {
    jcenter()
}

configurations {
    groovyScript
}

dependencies {
    groovyScript localGroovy()
}

task runHttpServer(type: JavaExec) {
    classpath = configurations.groovyScript
    main = 'groovy.ui.GroovyMain'

    // Start Groovy in listening mode on 
    // port 8001.
    args '-l', '8001'

    // Run simple HTTP server.
    args '-e', '''\
// init variable is true before
// the first client request, so
// the following code is executed once.
if (init) {
    headers = [:]
    binaryTypes = ["gif","jpg","png"]
    mimeTypes = [
        "css" : "text/css",
        "gif" : "image/gif",
        "htm" : "text/html",
        "html": "text/html",
        "jpg" : "image/jpeg",
        "png" : "image/png"
    ]
    baseDir = System.properties['baseDir'] ?: '.'
}

// parse the request
if (line.toLowerCase().startsWith("get")) {
    content = line.tokenize()[1]
} else {
    def h = line.tokenize(":")
    headers[h[0]] = h[1]
}

// all done, now process request
if (line.size() == 0) {
    processRequest()
    return "success"
}

def processRequest() {
    if (content.indexOf("..") < 0) { //simplistic security
        // simple file browser rooted from current dir
        def file = new File(new File(baseDir), content)
        if (file.isDirectory()) {
            printDirectoryListing(file)
        } else {
            extension = content.substring(content.lastIndexOf(".") + 1)
            printHeaders(mimeTypes.get(extension,"text/plain"))

            if (binaryTypes.contains(extension)) {
                socket.outputStream.write(file.readBytes())
            } else {
                println(file.text)
            }
        }
    }
}

def printDirectoryListing(dir) {
    printHeaders("text/html")
    println "<html><head></head><body>"
    for (file in dir.list().toList().sort()) {
        // special case for root document
        if ("/" == content) {
            content = ""
        }
        println "<li><a href='${content}/${file}'>${file}</a></li>"
    }
    println "</body></html>"
}

def printHeaders(mimeType) {
    println "HTTP/1.0 200 OK"
    println "Content-Type: ${mimeType}"
    println ""
}
    '''

    // Script is configurable via Java
    // system properties. Here we set
    // the property baseDir as the base
    // directory for serving static files.
    systemProperty 'baseDir', 'src/main/resources'
}

We can run the task runHttpServer from the command line and open the page http://localhost:8001/index.html in our web browser. If there is a file index.html in the directory src/main/resources it is shown in the browser.

$ gradle runGroovyScript
:runHttpServer
groovy is listening on port 8001
> Building 0% > :runHttpServer

Written with Gradle 2.11.

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.