Hi!

I'm very happy to share my presentation regarding Groovy metaprogramming and AST transforms. The slides are available at SlideShare and the code is available at TooMuchCoding Bitbucket and TooMuchCoding Github repositories. If you have any problems with reading any part of the slides or sth just post a comment here and I'll tr to help you :)

Enjoy!




Introduction to Groovy runtime metaprogramming and AST transforms from Marcin Grzejszczak

I had a discussion with one of the readers regarding issues related to creating an AST transformation that would be used on classes (and not on scripts). Often you can see that such a transformation does not work for you even though it should. The problem might be that you have the AST transformation compiled in the same time toghether with the class that you annotated with AST transformation related annotation.

What you have to remember about is that your AST transformation related classes have to be compiled prior to using (that's why you can often find that your AST transformation is working when you right click on your annotated class in your IDE (or Groovy console) and manually compile that particular class. That's because you compile that particular class when other classes have already been compiled. That's the very same scenario as with compiling a script that is using an AST transformation - first your tranformations are compiled and afterwards at runtime the script gets compiled.

Please check the additional repository ast_examples that consists of the same examples as in the TooMuchCoding repository together with an additional AST transformation that is set on a class.
Hi!

Quite recently I was asked by Packt publishing to write a review of the book Instant Mock Testing with PowerMock by Deep Shah. I have just managed to go through it and would like to share my thoughts :)

The layout


I enjoyed the book's layout with clear separation of the discussed issues with level of expertise required for the given section. What was also really nice was the precise division of content into the introductory part and the concrete solution to the problem.

What I liked


  • PowerMock is a very powerful tool that allows to test legacy code that was very badly written. On the other hand it can be tempting not to refactor existing code or even write bad code from the very beginning. So after this long introduction what I liked was that the author emphasised at the beginning of some chapters how a proper design should look like and that PowerMock breaks the rule
  • Names of test methods in the shown examples - they are very clear and teach good practices
  • Important parts of code are shown in bold - it attracts the reader and makes him focus immediately on the crucial elements
  • The examples clearly present the solution to the given problem
  • That I could learn about the PowerMock's suppress functionality :)
  • I had all the important PowerMock features in one place written in a concise and readable manner
  • Very thorough explanations for beginners in terms of adding PowerMock to Eclipse or IntelliJ
  • Introductory sections of each recipie (for example introducing the Active Record pattern)

What I didn't like

  • It's a very subjective opinion but I definitely prefer creating assertions through assertThat methods with proper matchers instead of using assertEquals, assertNull etc.
  • Not sure if that many javadocs were needed in the examples - for me they blur the image
  • On one hand the tests seem clean but on the other there are test scenarios in which the implementation is being tested instead of behaviour (for example in stubbing/verifying private methods or in partial mocking with spies). Of course I understand that sometimes it's done if we really care about some method execution or for the sake of showing PowerMock capabilities but in some cases (e.g. Partial mocking with spies) the refactoring process is not clear to me.

Summary

I really enjoyed the book Instant Mock Testing with PowerMock by Deep Shah because I like books related to computer science :) I'm pretty sure that someone that reads it will know about all the important PowerMock's features - Deep Shah did a good job here. I would however recommend that one reads the PowerMock's documentation first, especially the when to use it part since as authors state it:
... PowerMock is mainly intended for people with expert knowledge in unit testing. Putting it in the hands of junior developers may cause more harm than good.
Also there is good tutorial recommended by the PowerMock's authors and if you are a Mockito user you can profit from the Mockito usage at the project's wiki (although the examples there are not that specific as in Deep Shah's book).


Spring is a framework that never stops to amaze me. It's because of the fact that it offers plenty of different solutions that allow us, developers, to complete our tasks without writing millions of lines of code. Instead we are able to do the same in a much more readable, standardized manner. In this post I will try to describe one of its features that most likely is well known to all of you but in my opinion its importance is undervalued. The feature that I'll be talking about is the @Primary annotation.



The problem

On a couple of projects that I was working on we have come accross a common business problem - we had a point of entry to a more complex logic - some container, that would gather the results of several other processors into a single output (something like map-filter-reduce functions from the functional programming). To some extent it resembled the Composite pattern. Putting it all together our approach was as follows:
  1. We had a container that had an autowired list of processors implementing a common interface
  2. Our container implemented the same interface as the elements of the autowired list
  3. We wanted the client class that would use the container to have this whole processing work transparent - he is interesed only in the result
  4. The processors have some logic (predicate) basing on which a processor is applicable to the current set of input data
  5. The results of the processing were then combined into a list and then reduced to a single output
There are numerous ways of dealing with this issue - I'll present one that uses Spring with the @Primary annotation.

The solution

Let's start with defining how our use case will fit to the aforementioned preconditions. Our set of data is a Person class that looks as follows:

Person.java

package com.blogspot.toomuchcoding.person.domain;

public final class Person {
private final String name;
private final int age;
private final boolean stupid;

public Person(String name, int age, boolean stupid) {
this.name = name;
this.age = age;
this.stupid = stupid;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public boolean isStupid() {
return stupid;
}
}

Nothing out of the ordinary. Now let us define the contract:

PersonProcessingService.java

package com.blogspot.toomuchcoding.person.service;

import com.blogspot.toomuchcoding.person.domain.Person;

public interface PersonProcessingService {
boolean isApplicableFor(Person person);
String process(Person person);
}

As stated in the preconditions each implementaiton of the PersonProcessingService has to define two points of the contract :

  1. whether it is applicable for the current Person 
  2. how it processess a Person.

Now let's take a look at some of the Processors that we have - I'll not post the code here cause it's pointless - you can check out the code later on Github or on Bitbucket. We have the following @Component annotated implementations of PersonProcessingService:
  • AgePersonProcessingService
    • is applicable if Person's age is greater or equal 18
    • returns a String containing "AGE" as processing takes place - that's kind of silly but it's just a demo right? :)
  • IntelligencePersonProcessingService
    • is applicable if a Person is stupid
    • returns a String containing "STUPID" as processing takes place
  • NamePersonProcessingService
    • is applicable if a Person has a name
    • returns a String containing "NAME" as processing takes place
The logic is fairly simple. Now our container of PersonProcessingServices would want to iterate for a given Person over the processors, check if the current processor is applicable (filter) and if that is the case add the String that is a result of processing of a Person to the list of responses (map - a function converting a Person to a String) and finaly join those responses by a comma (reduce). Let's check it out how it's done:

PersonProcessingServiceContainer.java

package com.blogspot.toomuchcoding.person.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import com.blogspot.toomuchcoding.person.domain.Person;

@Component
@Primary
class PersonProcessingServiceContainer implements PersonProcessingService {

private static final Logger LOGGER = LoggerFactory.getLogger(PersonProcessingServiceContainer.class);

@Autowired
private List<PersonProcessingService> personProcessingServices = new ArrayList<PersonProcessingService>();

@Override
public boolean isApplicableFor(Person person) {
return person != null;
}

@Override
public String process(Person person) {
List<String> output = new ArrayList<String>();
for(PersonProcessingService personProcessingService : personProcessingServices){
if(personProcessingService.isApplicableFor(person)){
output.add(personProcessingService.process(person));
}
}
String result = StringUtils.join(output, ",");
LOGGER.info(result);
return result;
}

public List<PersonProcessingService> getPersonProcessingServices() {
return personProcessingServices;
}
}


As you can see we have a container that is annotated with @Primary which means that if an implementation of the PersonProcessingService will have to be injected then Spring will pick the PersonProcessingServiceContainer to be injected. The cool thing is that we have an autowired list of PersonProcessingServices which means that all other implementations of that interface will get autowired there (the container will not autowire itself to the list!).

Now let's check out the Spock tests that prove that I'm not telling any lies. If you aren't using Spock already in your project then you should move it straight away :)

PersonProcessingServiceContainerIntegrationSpec.groovy

package com.blogspot.toomuchcoding.person.service
import com.blogspot.toomuchcoding.configuration.SpringConfiguration
import com.blogspot.toomuchcoding.person.domain.Person
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification
import spock.lang.Unroll

import static org.hamcrest.CoreMatchers.notNullValue

@ContextConfiguration(classes = [SpringConfiguration])
class PersonProcessingServiceContainerIntegrationSpec extends Specification {

@Autowired
PersonProcessingService personProcessingService

def "should autowire container even though there are many implementations of service"(){
expect:
personProcessingService instanceof PersonProcessingServiceContainer
}

def "the autowired container should not have itself in the list of autowired services"(){
expect:
personProcessingService instanceof PersonProcessingServiceContainer
and:
!(personProcessingService as PersonProcessingServiceContainer).personProcessingServices.findResult {
it instanceof PersonProcessingServiceContainer
}
}

def "should not be applicable for processing if a person doesn't exist"(){
given:
Person person = null
expect:
!personProcessingService.isApplicableFor(person)
}

def "should return an empty result for a person not applicable for anything"(){
given:
Person person = new Person("", 17, false)
when:
def result = personProcessingService.process(person)
then:
result notNullValue()
result.isEmpty()
}

@Unroll("For name [#name], age [#age] and being stupid [#stupid] the result should contain keywords #keywords")
def "should perform different processing depending on input"(){
given:
Person person = new Person(name, age, stupid)
when:
def result = personProcessingService.process(person)
then:
keywords.every {
result.contains(it)
}
where:
name | age | stupid || keywords
"jan" | 20 | true || ['NAME', 'AGE', 'STUPID']
"" | 20 | true || ['AGE', 'STUPID']
"" | 20 | false || ['AGE']
null | 17 | true || ['STUPID']
"jan" | 17 | true || ['NAME']
}
}

The tests are pretty straight forward:
  1. We prove that the autowired field is in fact our container - the PersonProcessingServiceContainer.
  2. Then we show that we can't find an object in the collection of autowired implementations of the PersonProcessingService, that is of PersonProcessingServiceContainer type
  3. In the next two tests we prove that the logic behind our processors is working
  4. Last but not least is the Spock's finest - the where clause that allows us create beautiful paramterized tests.

Per module feature

Imagine the situation in which you have an implementation of the interface that is defined in your core module.

@Component
class CoreModuleClass implements SomeInterface {
...
}

What if you decide in your other module that has the dependence to the core module that you don't want to use this CoreModuleClass and want to have some custom logic wherever the SomeInterface is autowired? Well - use @Primary!
@Component
@Primary
class CountryModuleClass implements SomeInterface {
...
}

In that way you are sure that wherever the SomeInterface has to be autowired it will be your CountryModuleClass that will be injected in the field.

Conclusion

In this post you could see how to

  • use the @Primary annotation to create a composite like container of interface implementations
  • use the @Primary annotation to provide a per module implementation of the interface that will take precedence over other @Components in terms of autowiring
  • write cool Spock tests :)

The code

You can find the code presented here on Too Much Coding's Github repository or on Too Much Coding's Bitbucket repository.
Hi!

I didn't have much time to write posts recently (beacuse of work and my book "Mockito Instant") but I came across Bill Bejeck's book entitled "Getting Started with Guava". After having read it I decided that I will try also to blog about computer science related books. So without any futher ado let's move to the review :)


To begin with I really enjoyed the book's structure – one can see that the author had a clear view of the book: introduction to the functionality, its presentation with examples and a short review. By keeping such a fixed structure the reader wasn't surprised by the content in each of the chapters what made reading even more pleasant.

Let's move quickly through the book content chapter by chapter. 


Basic Guava Utilities

First of all you will be able to increase your knowledge about joining and splitting operations on collections by means of the Joiner and Splitter classes - no more unnecessary writing of loops! You will be able also to learn how to operate on Strings using  CharMatcher, Charsets, Strings which often is extremely tidious and produces a lot of boilerplate code. Next you will be able to learn about Preconditions - you won't have to write those cascades of if's in terms of defensive programming. Instead how about checking a condition and throw a runtime exception? To end with the author shows how to use Guava's utility classes to create implementation of toString, hashCode and compareTo methods.

Functional Programming with Guava

In this chapter the author shows how to introduce some functional approach to your Object oriented Java code with the Function, Predicate and Supplier interfaces and their corresponding utility classes Functions, Predicates and Suppliers.

Working with Collections

Since the Guava library emerged from issues related with collection manipulation the author could show the best examples in this chapter. You will learn about the Collections, FluentIterables, and Iterables utility classes. The author also mentions the Range class that you can use to represent boundaries. You will also be able to find information on other types of collections such as Bimaps (maps that aside from being navigated in the standard key to value way can be navigated from values to keys), Tables (replacement for map of maps), Multimaps (values are collections). There is also a part of the chapter related to the Ordering class that fives you additional posisbilities of working with Comparators.

Concurrency

The issue of concurrency is a very difficult issue as such. Guava can assist you in this difficult subject in a number of was that the author depicts: the Monitor class (version of a Mutex) can help you provide the serial access to part of your code, the Futures utility class to work with Future instances and many more cool solutions ;)

Guava Cache

The author shows several ways of creating caches, showing their statistics and how to configure them. You will also be able to learn how to register listeners for different cashe related types of events. 

The Event Bus

The author shows how to subscribe to events by using the Google Guava's Event Bus. What I really liked about this chapter was the presentation of the reason for incorporating it in a project (loose coupling) and a sample of using it in a Spring based application.

Working with Files

You will be able to find presentations of the utility classes and helpful solutions related to working with IO such as Files, CharStreams, ByteStreams, Readers , Writers the Closer class (elegant way of ensuring that the Closeable instance gets properly closed). The author presents the concept behind source and sinks too. So if you work a lot with files you will find plenty of cool stuff here.

Odds and Ends

Useful classes related to creating hash codes, working with Throwables and creating your applications in a null safe way.

I would never say that I know every aspect of Guava but I tend to use a lot of its functionalities at work. That's why I was really curious about the level of details that the author wanted to present in his book and whether I would find some really interesting details of the library that I wasn't aware of. What I found in the book was very satisfactory for me because although I was already familliar with the majority of the presented examples and functionalities, still I found plenty of those „little things” that I can use to improve my code and remove more boilerplate.

Speaking of which, what I really wanted to look at from the very beginning where the code samples showing how cool and helpful Guava really is. Being a true fan of unit testing I was very happy to see that the author put a lot of effort in those examples - the majority of functionalities were described by means of unit tests and showing some real life situations.

To sum it up I think that Bill Bejeck has put a tremendous effort in writing his book and he has done the job exceptionally well. I would recommend „Getting Started with Guava” for both newbies and experts – for sure both of these groups will be very satisfied.