I am still settling down from an awesome week in Sweden, where I went for the JFokus conference and subsequent speaker conference. Both were of epic proportions, and I would like to share my experience of giving a presentation there that I would not soon forget. My presentation on Evolutionary Algorithms titled “Making Darwin Proud: Coding Evolutionary Algorithms in Java” was scheduled for Tuesday, making it a very special session. Not only was it the 10th “birthday” of JFokus, it was also the 1st birthday of my son Olivier. It was a tough decision to speak at JFokus instead of being at home to celebrate my sons very first birthday, but as my wife said “he’s not going to remember you weren’t there on the specific day…we’ll celebrate extensively before you leave for Sweden” (I love my wife). However, I still wanted to do something special for my boy, which led me to come up with the ludicrous idea of starting out the presentation by asking the audience (some 450 developers) if they would sing Happy Birthday with me while I recorded it with my phone. They did, and it was awesome! I would like to use this opportunity to thank them from the bottom of my heart, because they made the day, and gave my wife, Olivier and me so much joy by doing this. The tweet that followed is one of the most retweeted and liked I’ve ever had (as well it should be!): https://twitter.com/BWknopper/status/697107401686675457 After our singing intro, I felt a connection with the audience I haven’t felt before (and I gave this talk a couple of times) which in turn led to one of the most fun and relaxed presentations I ever gave. The abstract of the presentation:
Java Developers sometimes face programming challenges, such as creating a school roster or determining a salesperson’s optimal route, that are extremely difficult to crack using conventional approaches. Discover how Evolutionary Algorithms can be applied to solve these complex puzzles. The session starts with a success story from the NASA space archives to explain the concepts. Once the stage is set, it’s puzzle solving time! Learn to code Evolutionary Algorithms using plain Java - although existing Java frameworks such as JGAP are also addressed. The session concludes with a checklist that can be used to determine whether Evolutionary Algorithms are a good fit to the problem. With this checklist, the decision has never been easier!
Continue reading →
Interesting links for week 6 2016:
Continue reading →
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:
Continue reading →
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.
Continue reading →
When we use the Context.render
method Ratpack's rendering mechanism kicks in. The type of the argument we pass to the render
method is used to look up the correct renderer. The renderer implements the Renderer
interface and provides the real output. We can add functionality that can work with the object of the Renderer
implementation before the actual output is created. We do this by adding a class or object to the registry that implements the RenderableDecorator
interface. The interface has a method decorate
that accepts the Context
and object that needs to be rendered. The code is invoked after the Context.render
method, but before the Renderer.render
method. This is especially useful when we use template renderers with a view model and with a RenderableDecorator
implementation we can augment the view model with some general attributes. Suppose we have a Ratpack application that uses the Groovy text template engine provided by the TextTemplateModule
. The module adds a Renderer
for TextTemplate
objects. Let's write a RenderableDecorator
implementation for the TextTemplate
, where we add an extra attribute createdOn
to the view model:
// File: src/main/groovy/com/mrhaki/ratpack/CreatedOnRendererDecorator.groovy
package com.mrhaki.ratpack
import ratpack.exec.Promise
import ratpack.groovy.template.TextTemplate
import ratpack.handling.Context
import ratpack.render.RenderableDecorator
import java.time.Clock
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* Add extra attribute to view model for all TextTemplate renderers.
*/
class CreatedOnRendererDecorator implements RenderableDecorator {
/**
* Apply this decorator for TextTemplate renderers.
*
* @return TextTemplate class.
*/
@Override
Class getType() {
return TextTemplate
}
/**
* Add an extra attribute createdOn to the view model with the current
* date and time.
*
* @param context Context to get Clock instance for this Ratpack application from.
* @param template Template with view model to extend.
* @return Promise with new TextTemplate instance with the extended view model.
*/
@Override
Promise decorate(final Context context, final TextTemplate template) {
final footerModel = [createdOn: createdOn(context)]
return Promise.value(
new TextTemplate(
template.model + footerModel,
template.id,
template.type))
}
/**
* Create formatted date/time String based on
* the Clock available on the Ratpack registry.
*
* @param context Context to get Clock instance from.
* @return Formatted date/time String.
*/
private String createdOn(final Context context) {
final Clock clock = context.get(Clock)
final LocalDateTime now = LocalDateTime.now(clock)
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return formatter.format(now)
}
}
Continue reading →
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'
).
Continue reading →
Interesting links for week 5 2016:
Continue reading →
The Spring Cloud project has several sub projects. One of them is the Spring Cloud Config Server. With the Config Server we have a central place to manage external properties for applications with support for different environments. Configuration files in several formats like YAML or properties are added to a Git repository. The server provides an REST API to get configuration values. But there is also a good integration for client applications written with Spring Boot. And because Grails (3) depends on Spring Boot we can leverage the same integration support. Because of the Spring Boot auto configuration we only have to add a dependency to our build file and add some configuration.
Before we look at how to use a Spring Cloud Config server in our Grails application we start our own server for testing. We use a local Git repository as backend for the configuration. And we use the Spring Boot CLI to start the server. We have the following Groovy source file to enable the configuration server:
Continue reading →
Recently I wanted to use the Tuckey UrlRewriteFilter. It is described as: A Java Web Filter for any compliant web application server, which allows you to rewrite URLs before they get to your code.
I wanted to load my urlrewrite.xml
as a Spring (classpath) resource, instead of loading it from the default location provided by the UrlRewriteFilter. The default behavior loads the configuration file from /WEB-INF/ulrewrite.xml
. In my case I wanted to load it from the /src/main/resources
folder, which is the root of my classpath.
Continue reading →
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.
Continue reading →
Interesting links for week 4 2016:
Continue reading →
In a previous blog post we learned how to use HandlerDecorator.prepend
to add common handlers via the registry in our application. The type of handlers suitable for this approach were handlers that had common functionality for the rest of the handlers. If we want to add a Chain
implementation, containing handlers and maybe even path information, we cannot use the prepend
method, must write our own implementation of the HandlerDecorator
interface. This can be useful when we want to re-use a Chain
in multiple applications. We write a module that adds the Chain
implementation to the registry and we don't have to write any code in the handlers
section for the Chain
to work. This blog post is inspired by a conversation on the Ratpack Slack channel recently. First we create a simple handler that renders a result:
// File: src/main/groovy/com/mrhaki/ratpack/Ping.groovy
package com.mrhaki.ratpack
import ratpack.groovy.handling.GroovyChainAction
/**
* Implementation of a {@link ratpack.handling.Chain} interface
* by extending {@link GroovyChainAction}, so
* we can use Groovy DSL support in the
* {@link Ping#execute} method.
*/
class Ping extends GroovyChainAction {
@Override
void execute() throws Exception {
// What we normally would write
// in the handlers{} section
// of Ratpack.groovy.
path('pingpong') {
render 'Ratpack rules!'
}
}
}
Continue reading →