Although I'm a great fan of using the ($q) Promise API in AngularJS, I never really liked using $q.defer()
and its Deferred API. I always found using var deferred = $q.defer()
together with $.resolve(..)
and $.reject(..)
to be too verbose. After recently checking the $q service documentation I stumbled upon the $q constructor that results in way less verbose code. To illustrate the usage of the $q constructor I will create a function that wraps the result of a Geolocation#getCurrentPosition invocation as an AngularJS $q
promise. Using the traditional $q.defer()
approach the function wrapper will look like this.
/\*\* @return {Promise} \*/
function getGeoLocation() {
var deferred = $q.defer();
$window.navigator.geolocation.getCurrentPosition(
function(position) { // success callback
return deferred.resolve(position);
},
function(positionError) { // error callback
return deferred.reject(positionError);
});
return deferred.promise;
}
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 →
We learned about externalised configuration in a previous blog post. Ratpack provides support out of the box for several formats and configuration sources. For example we can use files in YAML, properties or JSON format, arguments passed to the application, system properties and environment variables. We can add our own configuration source by implementing the ratpack.config.ConfigSource
interface. We must override the method loadConfigData
to load configuration data from a custom source and convert it to a format that can be handled by Ratpack.
We are going to write a custom ConfigSource
implementation that will get configuration data from a database. We assume the data is in a table with the name CONFIGURATION
and has the columns KEY
and VALUE
. The format of the key is the same as for Java properties files.
Continue reading →
In a previous post we learned about the get
and getAll
methods to get objects from the registry. Ratpack also provides the first
method to get objects from the registry. This method accepts a Function
that is applied to the elements of a given type. The first element where the Function
returns a non null value is returned encapsulated in an Optional
object. If the Function
returns a null value for all elements than Optional.empty()
is returned.
package com.mrhaki.ratpack
import ratpack.registry.Registry
import ratpack.registry.RegistrySpec
import spock.lang.Specification
class FindFirstRegistrySpec extends Specification {
Registry registry
def setup() {
// Setup registry with two objects of type User.
registry = Registry.of { RegistrySpec registrySpec ->
registrySpec.add(new User(username: 'mrhaki'))
registrySpec.add('hubert')
registrySpec.add(new User(username: 'hubert'))
registrySpec.add('mrhaki')
}
}
def "find User where username starts with mr"() {
when:
// First element that returns a non null value
// is return encapsulated in an Optional.
final Optional user = registry.first(User) { user ->
// If username property starts with
// "mr" than return user as non null value.
user.username.startsWith("mr") ? user : null
}
then:
user.get().username == 'mrhaki'
}
}
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 →
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:
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 →
To get objects from the registry or context we specify the type of the object we want. Ratpack will find the object(s) that match the given type. If we use the get
method then the last object added to the registry with the given type is returned. To get multiple objects we use the getAll
method. The methods returns an Iterable
with the found objects where the last added objects are returned as first elements.
In the following example specification we have a Registry
with some objects, of which two are of type User
. Next we use the get
and getAll
methods to get the objects.
Continue reading →
We can use the wiretap
method of the Promise
interface to listen in on results. We write an Action
implementation which has the result of a Promise
encapsulated in a Result
object. The wiretap
method can be used to do something with a Promise
value without interrupting a method chain.
In the following example we tap in on Promise
results:
Continue reading →
I have seen several projects where the developers had implemented caching all over the place. Caches were causing a large increase of heap usage, and users were always complaining that they were not seeing the latest data. My opinion on this is that a decision to add caching should not be taken lightly. Adding a cache means adding a lot of additional (or so-called accidental) complexity and also has a functional impact on the users. Adding a cache raises a lot of questions that need to be answered:
- What if cached data is updated, should the cached record be updated or evicted too?
- What should we do in a distributed environment, use a distributed cache? Is this distributed cache scalable?
- Do we get the performance improvements we're expecting?
- What is an acceptable delay for users to see the updated data?
- How many elements should we store in the cache?
- What eviction policy do we need when not all data fits in the cache?
Continue reading →