Archive: April 2015

Spicy Spring: Using @Value for Constructor Arguments

Posted on by  
Hubert Klein Ikkink

In Spring we can use the @Value annotation to set property or arguments values based on a SpEL expression. If we want to use the @Value annotation for a constructor argument we must not forget to add the @Autowired annotation on the constructor as well.

// File: sample/Message.groovy
package sample

import org.springframework.beans.factory.annotation.*
import org.springframework.stereotype.*

@Component
class Message {

    final String text

    // Use @Autowired to get @Value to work.
    @Autowired
    Message(
        // Refer to configuration property
        // app.message.text to set value for
        // constructor argument text.
        @Value('${app.message.text}') final String text) {
        this.text = text
    }

}

Continue reading →

Scala Snippet: multiline statements in the Scala REPL console

Posted on by  
Arthur Arts

One of the coolest things a standard Scala install will give you, is the Scala interpreter. Technically speaking, this is not an interpreter. In the background, each statement is quickly compiled into bytecode and executed on the jvm. Therefore, most people refer to it as the Scala REPL: Read-Evaluate-Print-Loop. You can access it by starting a command shell on your system and typing in 'scala'. Do make sure your either run it from the place where scala is installed or have scala on your environment PATH. By using the repl, you can quickly experiment and test out different statements. Once you press ENTER it will evaluate the statement and display the result. Frequently you want to execute multi-line statements and luckily the repl has a solution for that. Simply type in :paste and the repl will accept multiline statements. To exit this mode and evaluate your code, simply type CTRL+D. Example:

$ scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) Client VM, Java 1.7.0\_75).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Camera {

//this is a multiline example in the REPL

 val brand:String = "Canon"
 val model:String = "5D mark III"
}

// Exiting paste mode, now interpreting.

defined class Camera

scala> val cam = new Camera
cam: Camera = Camera@bfd117

scala> cam.brand
res0: String = Canon

Continue reading →

Grails Goodness: Set Log Level for Grails Artifacts

Posted on by  
Hubert Klein Ikkink

A good thing in Grails is that in Grails artifacts like controllers and services we have a log property to add log statements in our code. If we want to have the output of these log statements we must use a special naming convention for the log names. Each logger is prefixed with grails.app followed by the Grails artifact. Valid artifact values are controllers, services, domain, filters, conf and taglib. This is followed by the actual class name. So for example we have a controller SampleController in the package mrhaki.grails then the complete logger name is grails.app.controllers.mrhaki.grails.SampleContoller.

The following sample configuration is for pre-Grails 3:

Continue reading →

Bruce Lee's Top 5 Agile Coaching Tips

Posted on by  
Arthur Arts

When I was a kid, I was a big Bruce Lee fan. I walked around the playground rubbing my nose with my thumb. When I had a piece of rope, I had to do my version of the nunchaku routine from Way of the Dragon and made cat-like noises. Looking back at Lee, I find it quite striking how many of the principles of his fighting style Jeet Kun Do apply to agile practices. Check out these descriptions of the fighting style:

  • "Jeet Kune Do is not fixed or patterned, and is a philosophy with guiding thoughts."
  • "Jeet Kune Do practitioners believe in minimal movements with maximum effects and extreme speed."
  • "The system works by using different "tools" for different situations, where the situations are divided into ranges, which is kicking, punching, trapping, and grappling, where martial artists use techniques to flow smoothly between them. "
  • "Through his studies Lee came to believe that styles had become too rigid and unrealistic. He called martial art competitions of the day "dry land swimming". He believed that combat was spontaneous, and that a martial artist cannot predict it, only react to it, and that a good martial artist should "be like water" and move fluidly without hesitation."

Continue reading →

Spicy Spring : Dynamically create your own BeanDefinition

Posted on by  
Willem Cheizoo

When we a have Spring managed application, we want to let Spring manage all of our beans. Beside the regular way of creating beans with known solutions like Annotated beans, Java Configuration and XML Configuration, there is also a way in which we can create our own BeanDefinition. With a BeanDefinitionRegistryPostProcessor it is possible to create a specific post processor which can add BeanDefinitions to the BeanDefinitionRegistry. It differs from the BeanPostProcessor, which only has hooks for Bean Initialization (construction of your POJO), where the BeanDefinitionRegistryPostProcessor has a hook on the BeanDefinitionRegistry. This gives us the ability to define our own BeanDefinition. First we create a BeanDefinitionRegistryPostProcessor implementation as listed in the example. We implement the required method, and will be able to add our own bean definition to the registry. The defined BeanDefinition will be picked up by the ApplicationContext and the POJO will be constructed. Our result is A Spring managed bean

package com.jdriven;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;

@Component
public class LogicServiceRegistryPostProcessor
        implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
            throws BeansException {

        RootBeanDefinition beanDefinition =
                new RootBeanDefinition(MyServiceImpl.class); //The service implementation
        serviceDefinition.setTargetType(MyService.class); //The service interface
        serviceDefinition.setRole(BeanDefinition.ROLE_APPLICATION);
        registry.registerBeanDefinition("myBeanName", beanDefinition );
    }
}

Continue reading →

Grails Goodness: Add Banner to Grails Application

Posted on by  
Hubert Klein Ikkink

Grails 3 is based on Spring Boot. This means we get a lot of the functionality of Spring Boot into our Grails applications. A Spring Boot application has by default a banner that is shown when the application starts. The default Grails application overrides Spring Boot's behavior and disables the display of a banner. To add a banner again to our Grails application we have different options.

First we can add a file banner.txt to our classpath. If Grails finds the file it will display the contents when we start the application. Let's add a simple banner with Grails3 in Ascii art in the file src/main/resources/banner.txt. By placing the file in src/main/resources we can assure it is in the classpath as classpath:/banner.txt:

Continue reading →

Groovy Goodness: Use Closures as Java Lambda Expressions

Posted on by  
Hubert Klein Ikkink

Java 8 introduced lambda expressions we can use for example with the new Java Streams API. The Groovy syntax doesn't support the lambda expressions, but we can rely on closure coersion to use Groovy closures as Java lambda expressions in our code.

In the following sample we use the Java Streams API. Instead of lambda expressions for the filter and map methods we use Groovy closures. They are automatically transformed to lambda expressions, so it is very easy to use Java streams from Groovy code.

Continue reading →

Geb Gems: Running Geb Spock tests with Maven

Posted on by  
Albert van Veen

Geb is framework which makes it easy to create functional tests for your application. Since you can use Groovy, Spock and the elegance of the JQuery selector, you can setup solid functional test very easy. In this blogpost we will make a simple test which will test a functional part of the JDriven website. We will start our test with configuring the Maven POM file. We need to add the following dependencies.

         <dependencies><dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.0-groovy-2.4</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.gebish</groupId>
            <artifactId>geb-spock</artifactId>
            <version>0.10.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>2.45.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Continue reading →

Greach 2015 Conference Report

Posted on by  
Hubert Klein Ikkink

So this year I got the opportunity to speak and visit Greach 2015 in Madrid, Spain. I've never been in Spain before, but after visiting I definitely want to go back. Although the trip to Madrid was more cumbersome than planned, because of the strikes in France, I arrived at the speaker's dinner on time. Just go to mention that the Madrid metro is a very pleasant way to go around in Madrid. It was good to see old and new faces and to catch up and just have fun. Friday April 10th was the first day of the conference. The conference is held at the university in the south of Madrid. Jochen Theodorou, one of the Groovy core developers, opened the day with the keynote about Groovy's past, present and future. He gave a very nice overview of how Groovy evolved over the years and Groovy has been around already for a long time. Of course the latest news this year is Pivotal's hands off of Groovy and Grails. Jochen explained he first gets a good vacation and then decides what to do himself. Groovy is now in the process of getting an Apache project so the continuity of the development of the language should be saved. Then the rest of the day two tracks were presented at the same time. And there were difficult choices to make. Fortunately all talks are recorded and they will be added to the Greach Youtube channel.

I went to the talk Groovy and Scala: Friends or Foes by Marco Vermeulen. He showed how we can use Spock with Groovy to test Scala code using a Gradle build. So both worlds can live together and we can intermingle where possible. The application written in Scala was pragmatic and that is something I missed when I looked at Scala for the first time. This talk really got me interested to learn more about Scala. Next up was the talk AST - Groovy Transformers: More than meets the eye! by one of the conference organizers Iván López. He showed a lot of the (local) AST transformation that are already available in Groovy and that we can use everyday in our programs. Each AST transformation was clearly explained and he showed samples on how to use them. After his talk it was my time to present Grails Goodness. In this talk I live coded a selection of the blog posts about Grails I did write. Somehow there is always to little time to show everything I wanted, but still I think I was able to show some nice features of Grails.

Continue reading →

Scala Snippet: Object, Companion Object and Static Methods

Posted on by  
Arthur Arts

If you are a Java developer moving to Scala, one notable difference in terminology that can cause confusion is the term 'object'. In Java an object is always an instance of a class, created by calling a constructor.

In Scala an object is used for defining a single instance of a class with the features you want. In practice this means you will use it:

Continue reading →

Scala Snippet: Case Class vs plain ordinary Class

Posted on by  
Arthur Arts

In Scala there exist the construct of a 'case class'. According to Martin Odersky this supports you to write a "regular, non-encapsulated data structure". It always seems to be associated with pattern matching. So when to use a case class and when to use a 'plain' class? I found this nice explanation stating: _"Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments. This functional concept allows us to

  • use a compact initialisation syntax (Node(1, Leaf(2), None)))
  • decompose them using pattern matching
  • have equality comparisons implicitly defined

Continue reading →

Communication between Angular Controller and Directive

Posted on by  
Niels Dommerholt

Since I had issues finding a good explanation on how to tie together a controller and a directive with isolated scope I decided to create my own blog post on this subject. This repo contains a runnable example of the solution. It contains a Spring Boot Web Application that can be started to act as a HTTP server but all the interesting stuff is in the src/main/webapp folder.

To create modular code with AngularJS you want to create reusable components; directives. Directives should not depend in any way on the parent controller. They should not be able to see any of the parent scope unless it's explicitly provided to them. To do this Angular directives can have an isolated scope (which in my opinion should be the default). This however leads to an issue: typically a directive needs information provided for them, needs to provide methods that can be called and often also has to fire events that the layers above the directive need to be able to respond to. Especially the latter part, informing the scopes above of changes, is done in a somewhat particular way.

Continue reading →

shadow-left