2014-06-21

Sorting photos after holiday

Introduction

When my wife an I are on vacation, we always take photos using two cameras. One is my own and second belongs to my wife. After holidays we want to have one folder with all the photos sorted by date and time and named in this manner, so we do not have to select sort_by_date each time we want to view them. Of course, date and time on our cameras are synchronized.

Main

Creation date and time could be obtain from photo file using exiftool program from command line:
$ exiftool DSCN6201.JPG
and the output looks like this:
ExifTool Version Number         : 9.13
File Name                       : DSCN6201.JPG
Directory                       : .
File Size                       : 2.8 MB
...
Date/Time Original              : 2013:08:15 08:56:34
Create Date                     : 2013:08:15 08:56:34
...
I have written shell script which using exiftool rename all JPG files in current directory with prefix_yyyy_mm_dd__hh_mm_ss.JPG pattern. I only have to copy script file to photo directory and execute it with given prefix:
$ ls
DSCN6201.JPG  DSCN6203.JPG  DSCN8338.JPG  DSCN8340.JPG
DSCN6202.JPG  DSCN8337.JPG  DSCN8339.JPG  sorter.sh
$ ./sorter.sh holidays
$ ls
holidays_2013_08_15__08_55_55.JPG  holidays_2013_08_15__08_56_34.JPG
holidays_2013_08_15__08_56_08.JPG  holidays_2013_08_17__08_37_44.JPG
holidays_2013_08_15__08_56_22.JPG  holidays_2013_08_17__08_41_55.JPG
holidays_2013_08_15__08_56_29.JPG  sorter.sh
Script is available here.

Conclusion

Simple shell script can rename all your photos based on their creation date and time.

2014-05-25

Convert html page to mobi

Introduction

Sometimes I want to read webpage on my kindle. There are many pictures and source code blocks on this. What can you do? You can print webpage as pdf, but this is not good idea, because you cannot scale such document on kindle. Mobi is better file format so there must be better option and indeed is.

Kindlegen

Amazon provides little program called kindlegen, which could convert html, epub and some other formats to another and there is mobi. You have to save webpage with all css files and images somewhere on your disk. You could do this for example with Google Chrome, just push CTRL+S and select place. Now you should have html file and directory name like your html file without extension, but with _files suffix. For example I have download this webpage on my desktop and I have file Przybysz Dominik TechBlog.html and Przybysz Dominik TechBlog_files directory.
To use kindlegen you need all css and image files placed in the same directory as html file, so all local links from html files have to have deleted prefix describing directory. For example I have deleted ./Przybysz Dominik TechBlog_files/ from all src atributtes and moved html file to directory with other files.
Now you could use kindlegen:
kindlegen Przybysz\ Dominik\ TechBlog.html -o blog.mobi
Now your mobi file is ready to be placed on you kindle.

Conclusion

With one simple program you could convert any webpage to mobi format and read it on your kindle.

2014-05-17

Guice Tutorial - 09 - Providers in modules

Introduction

Module in Guice is not only a place where binding are defined. It also could have definition of many providers inside.


Provides

Suppose we have quiz class which has to be initialized before usage by call of method init.
public class Quiz {
    private boolean initialized = false;

    public boolean initialized(){
        return initialized;
    }

    public void init(){
        initialized = true;
    }
}
Provider is quite simple, because it only creates Quiz object and call method init, so we define it inside module.
public class QuizModule extends AbstractModule {
    @Override
    protected void configure() {}

    @Provides
    private Quiz getinitializedQuiz(){
        Quiz quiz = new Quiz();
        quiz.init();
        return quiz;
    }
}
Provides annotation tells Guice that annotated method is provider for its return type. Provider could be defined in this manner only in module.
Let's test it:
@Test
public void shouldClassInstanceFromProvider(){
    //given
    Injector sut = Guice.createInjector(new QuizModule());
    //when
    Quiz quiz = sut.getInstance(Quiz.class);
    //then
    assertTrue(quiz.initialized());
}

Conclusion

If you have to define provider, but you do not want to have separete provider class, than you could create method which acts like provider in your module. Sources are available here.

2014-05-10

Guice Tutorial - 08 - Combine modules

Introduction

Single injector could be created from many modules, so dependecies could be separeted depends on their domain.


Combining modules

Suppose you have two modules. One describes classes using to talk with database and second provides classes for frontend. For database there are SessionFactory interface with its implementation - SessionFactoryImpl. The bining is defined in DatabaseModule.
public interface SessionFactory {}
public class SessionFactoryImpl implements SessionFactory {}
public class DatabaseModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(SessionFactory.class).to(SessionFactoryImpl.class);
    }
}
Widget interface is bound to LabelWidget iFrontendModule .
public interface Widget {}
public class LabelWidget implements Widget{}
public class FrontendModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Widget.class).to(LabelWidget.class);
    }
}
We want to have injector, which uses this two modules, so we could create it in this way:
@Test
public void shouldJoinTwoDisjointModules(){
    //when
    Injector sut = Guice.createInjector(new DatabaseModule(), new FrontendModule());
    //then
    assertNotNull(sut.getInstance(SessionFactory.class));
    assertNotNull(sut.getInstance(Widget.class));
}
One constraint is that combined modules cannot have bindings for the same classes or interfaces.


Overriding modules

Suppose you have TestSessionFactoryImpl that you want to use in your tests.
public class TestSessionFactoryImpl implements SessionFactory{}
Binding for tests is defined in TestDatabaseModule.
public class TestDatabaseModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(SessionFactory.class).to(TestSessionFactoryImpl.class);
    }
}
Tring to combine this module with your DatabaseModule ends with CreationException.
@Test(expected = CreationException.class)
public void shouldThrowExceptionWhenJoiningTwoModulesWithTheSameBindings(){
    Guice.createInjector(new DatabaseModule(), new TestDatabaseModule());
}
To not obtain CreationException you should tell Guice that you want to override bindings of DatabaseModule with your TestDatabaseModule.
@Test
public void shouldOverrideModule(){
    //when
    Injector sut = Guice.createInjector(Modules.override(new DatabaseModule()).with(new TestDatabaseModule()));
    //then
    assertEquals(TestSessionFactoryImpl.class, sut.getInstance(SessionFactory.class).getClass());
}

Conclusion

You can combine many modules during creation of injector, but only if they have no bindings for the same classes. If they have, you have to explicitly tell Guice which module overrides bindings in another module. Sources are available here.

2014-05-01

Guice Tutorial - 07 - Module

Introduction

So far, we was using only annotations and creating injector without giving any parameters. It could be possible, because we was using classes defined by us or having no-arg constructor. But sometimes we have to use classes from external library, which do not meet these conditions. With the help comes to us Module.

Module

The module is an interface which has only one method - configure, where bindings could be defined. Binding is a form, which tells injector how to obtain instance of class that we ask for. It looks like this: bind(class).toSth(...). The best way to have defined bind method in your module is extend AbstractModule class.
public class MyModule extends AbstractModule{
    @Override
    protected void configure() {
        //...
    }
}
Module is the main definition for injector and when something is undefined then it also use bindings defined via annotations. Important is that module always overrides annotations, for example when class has annotations and module defines binding for it, then module binding is used.

Binding to constructor

First binding tells how to obtain class using constructor and there is method toConstructor where you could pass a constructor:
try {
    bind(FirstClass.class).toConstructor(FirstClass.class.getConstructor(Dependency.class));
} catch(NoSuchMethodException e) {
    // But i know it exists
    e.printStackTrace();
}
FirstClass class (and almost all class used in examples) looks like this:
public class FirstClass {
    private Dependency dependency;

    public FirstClass(final Dependency dependency) {
        this.dependency = dependency;
    }
}
It is not so easy to define constructor in this way so if I could I use Inject annotation, which means the same.
public class SecondClass {
    private Dependency dependency;

    @Inject
    public SecondClass(final Dependency dependency) {
        this.dependency = dependency;
    }
}

Binding to provider

We are using Provider to prepare class and module changes nothing, but we could replace ProvidedBy annotation in class with toProvider method in module:
bind(ThirdClass.class).toProvider(ThirdClassProvider.class);

Binding to instance

Of course, you could create one instance of class and want to pass it to every class, which could use it. We bind it using toInstance.
bind(FourthClass.class).toInstance(new FourthClass(new Dependency()));

Binding to concrete implementation

When we want to inject concrete implementation for interface or abstract class we have been using ImplementedBy annotation. In module we could simply use to and tell which class we want to bind to it. Of course, we have to define how to obtain this class (in module or via annotations).
bind(SomeClass.class).to(FifthClass.class);

Using scope

We could define that we want the class to be the singleton via annotation Singleton, so in module we should have this possibility too. And we have. We could tell in which scope class should be using method in at the end of each binding. For example:
try {
    bind(SixthClass.class).toConstructor(SixthClass.class.getConstructor(Dependency.class)).in(Singleton.class);
} catch(NoSuchMethodException e) {
    e.printStackTrace();
}

Conclusion

Annotations and module could be used to describe how injector should create instances of classes that we ask for. But annotations could be placed only on our classes, while module could describe creation for each class and is more important for Injector than annotations. 
All sources are available here.

2014-04-27

Guice Tutorial - 06 - Injecting injector

Introduction

Suppose you need a factory which gives you one implementation of interface depends on given parameter. The number of possible implementations is quite big. It could be resolved with factory with injected providers of each implementation, but in Guice we have a better way to achieve this goal...

Main

We could inject Injector to our class. We have a builder factory which could gives us implementation based on parameter:
public class BuilderFactory {
    private Injector injector;

    @Inject
    public BuilderFactory(final Injector injector) {
        this.injector = injector;
    }

    public Builder getBuilder(String param){
    if("first".equals(param)){
        return injector.getInstance(FirstBuilder.class);
        } else if("second".equals(param)){
            return injector.getInstance(SecondBuilder.class);
        } else {
            return injector.getInstance(DefaultBuilder.class);
        }
    }
}
And there are builders:
public interface Builder {}
public class FirstBuilder implements Builder{}
public class SecondBuilder implements Builder{}
public class DefaultBuilder implements Builder{}

First, to test is simply get injector from injector:
@Test
public void shouldInjectInjectorFromInjector(){
    //given
    Injector sut = Guice.createInjector();
    //when
    Injector result = sut.getInstance(Injector.class);
    //then
    assertEquals(sut, result);
}

Now let's get specific builder from our BuilderFactory:
@Test
public void shouldGetFirstBuilderFromFactory(){
    //given
    Injector sut = Guice.createInjector();
    BuilderFactory builderFactory = sut.getInstance(BuilderFactory.class);
    //when
    Builder builder = builderFactory.getBuilder("first");
    //then
    assertTrue(builder instanceof FirstBuilder);
}

@Test
public void shouldGetSecondBuilderFromFactory(){
    //given
    Injector sut = Guice.createInjector();
    BuilderFactory builderFactory = sut.getInstance(BuilderFactory.class);
    //when
    Builder builder = builderFactory.getBuilder("second");
    //then
    assertTrue(builder instanceof SecondBuilder);
}

@Test
public void shouldGetDefaultBuilderFromFactory(){
    //given
    Injector sut = Guice.createInjector();
    BuilderFactory builderFactory = sut.getInstance(BuilderFactory.class);
    //when
    Builder builder = builderFactory.getBuilder("unknown");
    //then
    assertTrue(builder instanceof DefaultBuilder);
}
And every tests pass.

Conclusion

When we have to create factory which gives us many concrete implementation we could inject injector to factory to not inject many providers of this concrete implementations. Source code is available here.

2014-04-20

Guice Tutorial - 05 - Default interface implementation

Introduction

Sometimes we have to define interface and write only one class which implements it, for example we see possibility of extending in future or we want to make our class final to prohibit making subclasses of this type or maybe we want to have one default implementation of interface. This goal could be obtained with Guice.


Interface and class

We have class:
public class PdfReportWriter implements ReportWriter{
    @Override
    public void write() {
        // ...
    }
}
which implements our interface and it is only class which do this. Interface looks so:
@ImplementedBy(PdfReportWriter.class)
public interface ReportWriter {
    void write();
}
By the ImplementedBy annotation we say to Guice that if I ask for object of type ReportWriter than we should by default obtain object of type PdfReportWriter. Let's test it:
@Test
public void shouldGetImplementationOfInterface(){
    //given
    Injector sut = Guice.createInjector();
    //when
    ReportWriter reportWriter = sut.getInstance(ReportWriter.class);
    //then
    assertTrue(reportWriter instanceof PdfReportWriter);
}
And the test passes.


Conclusion

When we have interface which has only one implementation or we want to make this class default implementation for interface than we could use ImplementedBy annotation in Guice. Sources are available here.

2014-04-11

Spock test template for IntelliJ IDEA

Spock tests should have specific structure. I generally use one form of test: with given, when, then and optional where blocks. I also like to have all cases visible, so I add Unroll annotation. I need simple way to generate test in this way.

I am developing using IntelliJ IDEA, so I describe how to configure live template using this IDE. Select File->Settings...->Live Templates. Now add new template group and add new template inside this. Abbreviation set to something meaningful and short, for example spock. As template text use code below:
@spock.lang.Unroll
def "should $END$"(){
    given:
    
    when:
    
    then:
    
    where:
    
}
Set also option "Reformat according to style", apllicable set to groovy and choose expand key.

Now, when you type spock and click expand key (in my case it is Tab) in editor, then spock will be replaced with template and coursor will be set after space in test method name.

2014-04-06

Guice Tutorial - 04 - Default providers and scopes

Introduction

This time I want to show you, what Guice will do, when we ask for provider for class, but we have not defined any provider and when we obtain new objects from injector and when already used objects. All sources are available here.

Default providers

First, let's create a small class:
public class UserSession {}
We do not define any profider, but when we ask for provider, than provider will be given to us.
@Test
public void shouldGetEachTimeNewSessionFromProvider(){
    //given
    Injector injector = Guice.createInjector();
    Provider<UserSession> sut = injector.getProvider(UserSession.class);
    //when
    UserSession userSession = sut.get();
    //then
    assertNotNull(userSession);
}

Scopes

For each request to injector or default provider we obtain new object. This is default scope of dependencies maintained by Guice. For example:
@Test
public void shouldGetEachTimeNewSession(){
    //given
    Injector sut = Guice.createInjector();
    //when
    UserSession userSession1 = sut.getInstance(UserSession.class);
    UserSession userSession2 = sut.getInstance(UserSession.class);
    //then
    assertNotEquals(userSession1, userSession2);
}
But suppose we should have only one instance of class, for example generator.
@Singleton
public class SequenceGenerator {
    private int counter = 0;

    public int next(){
        return counter++;
    }
}
The Singleton annotation tells Guice that we want only one instance of this class, so if we get instance of this class from injector or default provider, than we obtain the same instance.
@Test
public void shouldGetTheSameSequenceGeneratorEachTime(){
    //given
    Injector injector = Guice.createInjector();
    //when
    SequenceGenerator sequenceGenerator1 = injector.getInstance(SequenceGenerator.class);
    SequenceGenerator sequenceGenerator2 = injector.getInstance(SequenceGenerator.class);
    //then
    assertEquals(sequenceGenerator1, sequenceGenerator2);
}
@Test
public void shouldGetTheSameSequenceGeneratorEachTimeFromProvider(){
    //given
    Injector injector = Guice.createInjector();
    Provider<SequenceGenerator> sut = injector.getProvider(SequenceGenerator.class);
    //when
    SequenceGenerator sequenceGenerator1 = sut.get();
    SequenceGenerator sequenceGenerator2 = sut.get();
    //then
    assertEquals(sequenceGenerator1, sequenceGenerator2);
}
Of course dependency is singleton in Guice context, so you could create new object of this class outside from Guice and no one could stop you.

Conclusion

Guice generates for us default providers in default scope. Providers give us new objects for each request to their. We could also change scope of class to Singleton and then for each request we obtain the same object. 

2014-04-02

Guice Tutorial - 03 - Providers

Introduction

Dependencies injected by Guice are generally created using annotated constructor. But sometimes you need a generator of specific class objects or you have to initialize your class before using it. These goals you can meet using providers. First, suppose you have ReportController, which stores given message with actual date in some place (database, file).


Injecting Provider

If you want to write good unit tests, you should protect yourself against changing date, so you can inject a kind of date generator - Provider of Date.
public class DateProviderTest {
    @Test
    public void shouldGetAnotherTimeForEachGet() throws InterruptedException {
        // given
        Injector injector = Guice.createInjector();
        Provider<Date> sut = injector.getProvider(Date.class);
        // when
        Date firstDate = sut.get();
        Thread.sleep(1);
        Date secondDate = sut.get();
        // then
        assertNotNull(firstDate);
        assertNotNull(secondDate);
        assertNotEquals(firstDate.getTime(), secondDate.getTime());
    }
}
In unit tests for classes, which use this provider you only need to mock Provider interface and return fixed date on each call.


Injecting via provider

Sometimes your objects should be additionally prepared before using, for example you have to call initialize method. It also could be done in described above way or you could use ProvidedBy annotation and explicit define Provider for your class. First, let's define class which should be initialized before using:
@ProvidedBy(ReportSessionFactory.class)
public class ReportSession {
    private boolean initialized;

    public ReportSession() {}

    public void init() {
        this.initialized = true;
    }

    public boolean isInitialized() {
        return initialized;
    }
    public boolean report(final String reportMessage, final Date date) {
        if(!initialized){
            return false;
        }
        // ...
        return true;
    }
}
ProvidesBy points to class which implements Provider interface:
public class ReportSessionFactory implements Provider<ReportSession> {
    @Override
    public ReportSession get() {
        ReportSession reportSession = new ReportSession();
        reportSession.init();
        return reportSession;
    }
}
Now when we will inject object of class ReportSession it will be given to us from provider and already initialized:
public class ReportSessionProviderTest {
    @Test
    public void shouldInitReportSession() {
        // given
        Injector injector = Guice.createInjector();
        ReportSession sut = injector.getInstance(ReportSession.class);
        // when
        boolean result = sut.isInitialized();
        // then
        assertTrue(result);
    }
}

Conclusion

When you need to inject a generator of runtime dependent objects or have to call method of dependency immediately after constructor, Guice providers are the best options for you. Sources are available here.

2014-03-23

Guice Tutorial - 02 - Injection points

Introduction

There are three points, where you can inject your dependecies. In previous part of this tutorial I have use injection to costructor. Available are also injections to setters or directly to fields. Today our domain will be order processing.

Main

First some classes, which will be our dependecies:
public class Order {
    private final String item;
    private final int amount;

    public Order(final String item, final int amount) {
        this.item = item;
        this.amount = amount;
    }

    public String getItem() {
        return item;
    }

    public int getAmount() {
        return amount;
    }
}

public class OrderProcessor {
    public void process(final Order order) {
        // ...
    }
}

public class OrderDao {
    public void save(final Order order) {
        // ...
    }
}

class OrderValidator {
    public void validate(final Order order) {
        // ...
    }
}

Controller which has all these dependecies is here:
public class OrderController {
    private final OrderDao orderDao;

    private OrderProcessor orderProcessor;

    @Inject
    private OrderValidator orderValidator;

    @Inject
    public OrderController(final OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    @Inject
    public void setOrderProcessor(final OrderProcessor orderProcessor) {
        this.orderProcessor = orderProcessor;
    }

    public void invokeProcessing(final Order order) {
        orderValidator.validate(order);
        orderDao.save(order);
        orderProcessor.process(order);
    }
}

As you can see, the Inject annotation is set on constructor of whole class, setter of OrderDao and on OrderValidator field. Injecting to constructor is the best option in my opinion, because all needed dependecies should be inject, when class is created.
Setter injection sometimes is helpful, for example when you need to inject something later using injectMember (it will be cover in one of next parts).
Field injecting is often a bad idea, because during testing this field should be protected or default (or public, but this is the worst idea) to mock this dependency. Of course you can use refletion, but reflection API is not easy to use. But you have this opportunity to inject field.

Testing

One simple test to prove that all this injection points works and there are not NullPointerExceptions.
public class OrderControllerIT {
    @Test
    public void shouldInjectAllDependency() {
        //given
        Injector injector = Guice.createInjector();
        Order order = new Order("apple", 10);
        //when
        OrderController sut = injector.getInstance(OrderController.class);
        //then
        sut.invokeProcessing(order);
    }
}


Conclusion

You could inject dependecies in three placess in classes, but you almost always should use constructor injector. Injecting to setters should be hardly ever used. Field injecting is available, but should not be used.
All sources are available here.

2014-03-16

Guice Tutorial - 01 - The simplest injection

Introduction

Guice is very powerful and simple dependency injection library from Google. There is no need to create xml configuration or have container to use it. Moreover, it gives us objects already casted to desired types. In this post I will show how to start working with guice and make the simplest injection. In this case, domain will be adding persons. All sources are available here.


Main

First, we have to add maven dependency to guice and optionally to javax.inject:
<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>3.0</version>
</dependency>
<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>
Guice has own annotations to describe injections, but I like to use javax.inject annotation, which could also be used with Guice and are part of JavaEE.


Person is described by given class:
public class Person {
    private String firstName;
    private String lastName;
    private Integer age;

    public Person(final String firstName, final String lastName, 
                  final Integer age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    //...
}
We also need PersonDao and PersonValidator:
public class PersonDao {
    public void persist(final Person user) {
        // ...
    }
}
public class PersonValidator {
    void validate(final Person user) throws PersonValidationException {
        // ...
    }
}
Now we have all dependencies so let's create controller, which will use this classes:
public class PersonController {
    private final PersonValidator userValidator;
    private final PersonDao userDao;

    @Inject
    public PersonController(final PersonValidator userValidator, 
                            final PersonDao userDao){
        this.userValidator = userValidator;
        this.userDao = userDao;
    }

    public void add(final Person user) throws PersonValidationException{
        userValidator.validate(user);
        userDao.persist(user);
    }
}
The magic is in annotation Inject. In Guice, when we want to use class with not default, no argument constructor, we have to add this annotation to one of constructor.


Testing

It is time to test it. I will use JUnit.
@Test
public void shouldGetPersonControllerFromInjectorAndPersistPerson() {
    //given
    Injector injector = Guice.createInjector();
    Person user = new Person("John", "Smith", 25);
    //when
    PersonController userController = injector.getInstance(PersonController.class);
    //then
    userController.add(user);
}
All classes could be obtained from Guice via Injector. Injector collects all classes in classpath and allows to get their instances if they have default constructors or constructors annotated with Inject (from Guice or javax).
Method add of userController pass without exception so Guice has injected PersonDao and Person Validator classes. 


Conclusion

Guice is very simple and in basic cases we need only to use Inject annotation on class with dependecies. We only have to call getInstance and tell Guice which class (or interface) we want.

2014-02-09

JUnit lifecycle

Introduction

JUnit is basic and first tool which is used for testing in Java. JUnit uses annotations to describe lifecycle, but sometimes order of operations executed by this library is not obvious. For example: when constructor of test class is called or when static initalization block is executed?

Main

This JUnit test class will be used to show when methods and blocks are executed.
package com.blogspot.przybyszd.junitlifecycle;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JunitLifecycleTest{
    private static final Logger LOG = LoggerFactory.getLogger(JunitLifecycleTest.class);
    
    static{
        LOG.info("In static initialization block");
    }
    
    public JunitLifecycleTest(){
        LOG.info("In constructor");
    }
    
    {
        LOG.info("In initialization block");
    }
    
    @Test
    public void test1(){
        LOG.info("In test 1");
    }
    
    @Test
    public void test2(){
        LOG.info("In test 2");
    }
    
    @BeforeClass
    public static void oneTimeSetUp(){
        LOG.info("In before class");
    }
    
    @Before
    public void prepareTest(){
        LOG.info("In before");
    }
    
    @After
    public void tearDown(){
        LOG.info("In after");
    }
    
    @AfterClass
    public static void oneTimeTearDown(){
        LOG.info("In after class");
    }
}

And this is output after executing tests from this class.
2014-02-09 17:36:52,931 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:19 - In static initialization block
2014-02-09 17:36:52,935 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:42 - In before class
2014-02-09 17:36:52,936 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:27 - In initialization block
2014-02-09 17:36:52,937 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:23 - In constructor
2014-02-09 17:36:52,938 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:47 - In before
2014-02-09 17:36:52,938 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:32 - In test 1
2014-02-09 17:36:52,938 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:52 - In after
2014-02-09 17:36:52,940 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:27 - In initialization block
2014-02-09 17:36:52,941 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:23 - In constructor
2014-02-09 17:36:52,941 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:47 - In before
2014-02-09 17:36:52,941 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:37 - In test 2
2014-02-09 17:36:52,941 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:52 - In after
2014-02-09 17:36:52,942 [INFO ] com.blogspot.przybyszd.junitlifecycle.JunitLifecycleTest:57 - In after class

As we can see, static initialization block is executed before metchod annotated with BeforeClass. You can initialize here heavy objects, like Hibernate SessionFactory.

Before each test not only method annotated with Before is called. Earlier initialization block and constructor is called. There you can create resources, which should be not shared between tests (for example to get Hibernate Session from SessionFactory).

At the end of each test method annotated with After is called (for example to close Hibernate Session) and at the end of whole class, method annotated with AfterClass could free your resources (for example Hibernate SessionFactory).

Conclusion

It is why JUnit is great for unit testing. State for each test could be created in initial block, constructor of before method and it does not share it between test methods, because for each test new class is created. Of course, You can always store something in static variables, for example heavy objects which You want to create only once.

2014-01-13

Properties from maven

Introduction

Sometimes your code should work in many environments using varaibles defined in many places. There could be default variable in code (when configuration is not defined), variable in configuration file or pom.xml for tests and maybe each developer should have own variable value...

Property reader code

All examples will be tests and will be use PropertyReader class which is defined below.
package com.blogspot.przybyszd.sandbox.propertyplaceholders;

import java.util.Properties;

public class PropertyReader{
    
    public static Properties readProperties(final String configurationFile){
        Properties properties = new Properties();
        try{
            properties.load(PropertyReader.class.getResourceAsStream(configurationFile));
        }catch(Exception e){
            System.err.println("Configuration file was not found");
        }
        return properties;
    }   
}
All properties files will be defined in src/test/resources.

Default properties in code

First, assume that properties file is not provided or property is not given:
package com.blogspot.przybyszd.sandbox.propertyplaceholders;

import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.junit.Test;

public class PropertyReaderTest{
    
    @Test
    public void shouldUseDefaultPropertyFromCode(){
        // given
        Properties properties = PropertyReader.readProperties("/no-existing-file.properties");
        // when
        String value = properties.getProperty("address", "localhost");
        // then
        assertEquals("localhost", value);
    }
}
But when property file exists and has this property then it will be used:
@Test
public void shouldUsePropertyFromFile(){
    // given
    Properties properties = PropertyReader.readProperties("/existing-file.properties");
    // when
    String value = properties.getProperty("address", "localhost");
    // then
    assertEquals("10.10.10.10", value);
}
Property in file existing-file.properties:
address=10.10.10.10

Default properties in pom.xml

Properties could be also defined in pom.xml and then placeholders could be used in property file. Test is going first:
@Test
public void shouldUsePropertyFromPom(){
    // given
    Properties properties = PropertyReader.readProperties("/file-with-placeholder.properties");
    // when
    String value = properties.getProperty("address", "localhost");
    // then
    assertEquals("trololo.com", value);
}
Instead of value in properties file there is only placeholder (file file-with-placeholder.properties):
address=${address}

Value of property is defined in pom.xml (filtering of test resources must be set to true and, optionally, resource filtering could be set to true):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>property-placeholders</groupId>
 <artifactId>property-placeholders</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>PropertyPlaceholder</name>

 <properties>
  <address>google.com</address>
 </properties>

 <build>
  <resources>
   <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
   </resource>
  </resources>
  <testResources>
   <testResource>
    <directory>src/test/resources</directory>
    <filtering>true</filtering>
   </testResource>
  </testResources>
 </build>

 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.11</version>
   <scope>test</scope>
  </dependency>
 </dependencies>
</project>
Now variable could be also set from command line:
mvn -Daddress=my-address clean test

Default property in settings.xml

Each developer (or each environment) could define some properties in settings.xml in $HOME/.m2 directory and these properties overwrite properties defined in pom.xml.
Test first:
@Test
public void shouldUsePropertyFromSettingsXMl(){
    // given
    Properties properties = PropertyReader.readProperties("/file-with-placeholder.properties");
    // when
    String value = properties.getProperty("address2", "localhost");
    // then
    assertEquals("yahoo.com", value);
}
I add new property address2 so I have to add property placeholder in properties file and in pom.xml.
Properties file:
address=${address}
address2=${address2}
pom.xml:
<properties>
 <address>google.com</address>
 <address2>bing.com</address2>
</properties>
And now variable address2 will be redefined in settings.xml file :
<settings>
  <profiles>
    <profile>
      <id>property-placeholder</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <address2>yahoo.com</address2>
      </properties>
    </profile>
  </profiles>
</settings>
This profile is active by default so there is not need to use -P parameter.
Not the tests pass.

Conclusion

Use Maven and define properties anywhere.

2014-01-11

Try catch with resources

Introduction

Today I would like to describe a try catch with resource, which is available in Java 7. Additional I show template for Eclipse, which generate such try-resource for reading file.


Try catch in Java 6

In Java 6 (or earlier) you have to write try catch like this:
BufferedReader bin = null;
try{
    bin = new BufferedReader(new FileReader("trolo.txt"));
    String line = null;
    while((line = bin.readLine()) != null){
        // parse line
    }
}catch(IOException e){
    LOG.error("IO exception when creating reader or reading", e);
    throw new MyException(e);
}finally{
    try{
        if(bin != null){
            bin.close();
        }
    }catch(IOException e){
        LOG.error("IO exception when closing", e);
        throw new MyException(e);
    }
}

It is not quite nice... You have to declare BufferedReader before try block and close it in finally (of course if it is not null). Additionally close method could throw IOException which should be handle...

Try catch with resource in Java 7

Java 7 came to us with resources for try. Each resource have to implement interface AutoClosable. It has only one method: close, which is called at the end of try catch with resource. Ant this is an example of use:
try (BufferedReader bin = new BufferedReader(new FileReader("trolo"))){
    String line = null;
    while((line = bin.readLine()) != null){
        // parse line
    }
}catch(IOException e){
    LOG.error("IO exception", e);
    throw new MyException(e);
}
Shorter? Creating, reading or closing BufferedReader could throw exception so we still need catching of IOException, but only once. Finally block is ommited.

Eclipse template

In Eclipse you could define a template, which insert try catch with resource and you job is only name the variables and give file name. I was inspired by this post, to write this template.
${:import(java.io.BufferedReader, java.io.FileReader, java.io.Exception)}
try(BufferedReader ${buffName} = new BufferedReader(new FileReader(${fileName}))){
 String ${line} = null;
 while((${line} = ${buffName}.readLine()) != null) {
        ${cursor}
 }
}catch(IOException e){
    // TODO Auto-generated stub
    throw new UnsupportedOperationException("Not implemented yet");
}

Conclusion

Java 7 came with big improvement for try catch. Now is is shorter to use in try any resource which have to be closed at the end.

2014-01-04

Eclipse configuration for Java

Introduction

Eclipse is an great IDE, but only with some plugins (or only one) and changes in default settings. I show you how to prepare the best in my opinion environment to developing in Java with TDD style.

Settings

First open Window menu and select preferences. There you have some interesting settings.

Java -> Appearance -> Type filters

Add here class java.lang.Object to not see methods of Object class: equals, wait, notify etc. Add also package java.awt. Always annoys me when i have to import java.util.List but first class List is derived from java.awt.

Java -> Code style

Exception variable name is set to e and option 'Add @Override annotation for new overriding methods' is set.

Java -> Code style -> Clean Up

Eclipse could perform some tasks when you clean up your code from source menu. Create new profile and set:
  1. In first tab (Code Organizing): 
    • Format source code
    • Organize imports
  2. In Code Style tab:
    • Use blocks in if/while/for/do statements -> Always (because when you add code to your if body you could forget to put it into block)
    • Convert 'for' loops to enhanced
    • Use modifier 'final' where possible (select only parameters, because when you assign variable to parameter it is code smell and this protects you from doing bad things) 
  3. In Member Accesses tab:
    • Use declaring class as qualifier (select only access through instance and subtypes)
  4. In Missing Code tab:
    • Add missing annotations: @Override, @Override when implementation of method from interface and @Deprecated
    • Add serial version ID (generated)
    • Add unimplemented method (body will be taken from code template)
  5. In Unnecessary Code tab:
    • Remove unused imports
    • Remove unnecessary casts
    • Remove unnecessary '$NON-NLS$' tags

Java -> Code style -> Code templates

Method, constructor and catchblock body will be change to throw exception when is generated. When you forget to implement method or block you obtain UnsupportedOperationException.
Set method and catch block body to:
// ${todo} Auto-generated catch block
throw new UnsupportedOperationException("Not implemented yet");
Set constructor body to:
${body_statement}
// ${todo} Auto-generated constructor stub
throw new UnsupportedOperationException("Not implemented yet");

Java -> Code style -> Formatter

This options helps me read code and I just like this form of code. The same defined formatter rules should be used by all team members, so you could export configuration and give to your team mates.
  1. In tab Indentation:
    • Declarations within class body
    • Declarations within enum body
    • Declarations within class constants
    • Declarations within annotation body
    • Statements within method/constructor body
    • Statements within blocks
    • Statements within 'switch' body
    • Statements within 'case' body
    • 'break' statements
    • Empty lines
  2. In tab Braces:
    • All options set to 'Same line'
  3. In tab White Space:
    • Declarations:
      • Classes: after comma in implemented clause
      • Fields: after comma in multiple field declarations
      • Constructors: after comma in parameters and after comma in 'throws' clause
      • Methods: after comma in parameters, before ellipsis in vararg parameters, after ellipsis in vararg parameters and after comma in 'throws' clause
      • Labels: after colon
      • Annotations: after comma
      • Enum types: after comma between constants and after comma in constant arguments
    • Control statements:
      • 'for': after comma in initialization, after comma in increments, after semicolon, befor colon and after colon
      • 'try-with-resources': before opening parenthesis and after semicolon
      • 'assert': before colon and after colon
      • 'return': before parenthesized expressions
      • 'throw': before parenthesized expressions
    • Expressions:
      • Function invocations: after comma in methods arguments, after comma in object allocation arguments and after comma in in explicit constructor call
      • Assignments: before assignment operation and after assignment operation
      • Operators before binary operations and after binary operations
      • Type casts: after closing parenthesis
      • Conditionals: before question mark, after question mark, before colon and after colon
    • Arrays:
      • Arrays initializers: after comma
    • Parameterized types:
      • Type reference: after comma
      • Type arguments: after comma
      • Type parameters: after comma in parameters, before '&' in type bounds and after '&' in type bounds
  4. In tab Blank Lines:
    • 0 blank lines before package declaration, before first declaration, before field declarations and at begining of method body
    • 1 otherwise
  5. In tab New Lines:
    • after labels
    • at end of files
    • put empty statements on new line
    • insert new line after annotations on package
    • insert new line after annotations on types
    • insert new line after annotations on fields
    • insert new line after annotations on methods
    • insert new line after annotations on local variables
  6. In tab Control Statements:
    • Keep 'else if' on one line
  7. In tab Line Wrapping:
    • Prefer wrapping outer expressions (keep nestedexpression in one line)
    • Annotations: wrap all elements, every element on a new line
    • Class declarations: Do not wrap
    • Constructor declarations: Do not wrap
    • Method declarations: Do not wrap
    • 'enum' declarations: wrap all elements, every element on a new line
    • Function calls: Do not wrap
    • Expressions: Do not wrap
    • Statements:
      • Compact 'if else' and 'multi-catch': Do not wrap
      • 'try-with-resource': Wrap all elements, except first element if not necessary (additionally set indentation policy to Indent on column)
  8. In tab Comments:
    • Enable Javadoc comment formatting
    • Enable block comment formatting
    • Enable line comment formatting
    • Format line comments on first column
    • Enable header comment formatting
    • Never join lines
    • Format HTML tags
    • Format Java code snippets inside 'pre' tags
    • Indent Javadoc tags
    • /** and */ after separate lines
    • Remove blank lines
    • /* and */ after separate lines
    • Remove blank lines
    • Maximumline width for comments: 200
  9. Off/On Tags (Disable formatting between some comments):
    • Enable Off/On tags
    • Off tag: DO NOT INDENT
    • On tag: NOW INDENT

Java -> Code style -> Organize Imports

Set only number of import and static import needed for * to 100. I do not like imports with * when I am using IDE.

Java -> Compiller -> Building

There are problems which could occur with whole project.
  1. General
    • Enable use of exclusion patterns in source folders 
    • Enable use of multiple output locationsfor source folders
  2. Build path problems 
    • warnings on Incompatible required libraries and No strictly compatible JRE for execution environment available
    • errors otherwise
  3. Output folder
    • warning when duplicated resource
    • I scrub output folders when cleaning projects

Java -> Compiller -> Error/Warnings

There are problems which could occurs in code.
  1. Code style
    • warning on:
      • Non-static access to static member
      • Access to non-accessiblemember of enclosing type
      • Parameter assignment
      • Method with a constructor name
    • ignore otherwise
  2. Potential programming problems
    • error on:
      • Possible accidentalboolean assignment
      • Dead code
    • warning on:
      • Comparing identical values
      • Assignment has no effect
      • Using a char arrayin string concatenation
      • Inexact type match for varargs arguments
      • Empty statement
      • Unused object allocation
      • Incomplete 'switch' case on enum
      • Hidden catch block
      • 'finally' does not complete normally
      • Resource leak
      • Seralizable class without serialVersionID
      • Missing synchronization modifier on inherited method
      • Class overides 'equals()' but not 'hashCode()'
    • ignore otherwise
  3. Name shadowing and conflicts
    • warning on:
      • Type parameter hides another type
      • Method does not override package visible method
      • Interface method conflicts with protected 'Object' method
    • ignore otherwise
  4. Deprecated and restricted API
    • error on forbidden reference
    • warning on:
      • Deprecated API (both options checked)
      • Discourage reference
  5. Unnecessary code: all options set to warnings and selected 'Ignore in overriding and implementing methods' boxes
  6. Generic types: all options set to warnings and selected 'Ignore unavoidable generic type problems'
  7. Annotations: all options set to warnings and selected 'Include implementations of interface methods' and 'Enable @SuppressWarnings annotations' boxes
  8. Null analysis
    • warning on null pointer access
    • ignore otherwise

Java -> Compiller -> Javadoc

There are problems which could occurs in javadoc comments.
Select 'Process Javadoc comments'. Set warning on malformed Javadoc comments, but only on public members and then validate tag arguments, report non visible references, deprecated references and validate all standard tags missing description.
When tag is missing then warning should apear but only on public members, ignoring overriding and implementing methods and method type parameters.
Ignore missing Javadoc comments. Why? Because you do not need javadoc, but when you do then you should have valid comments.

Java -> Editor -> Content Assist

This options are used when CTRL+Space are pressed. I have set:
  1. Insertion
    • Completion inserts
    • Insert single proposals automatically
    • Add import instead of qualified name
    • Use static imports
    • Fill method arguments and show guessed arguments
    • Insert best guessed arguments (It really could quess what you think)
  2. Sorting and filtering
    • Sort proposals by revelance
    • Show camel case matches
    • Hide proposals not visible in the invocation context
  3. AutoActivation should be enable and activate after 200 ms or on . (dot) sign.

Java -> Editor -> Content Assist -> Advanced

Choose only these proposals which you will be use. I suggest to add templete and word proposals and set them at the beggining of content assist cycle.

Java -> Editor -> Content Assist -> Favourites

There you can set static methods, static fields or classes for quick proposals. It is extremely useful for tests. I have here:
  1. Static members from:
    • com.googlecode.catchexception.CatchException
    • org.fest.assertions.Assertions
    • org.hamcrest.CoreMatchers
    • org.hamcrest.Matchers
    • org.junit.Assert
    • org.junit.Assume
    • org.junit.matchers.JUnitMatchers
    • org.mockito.Matchers
    • org.mockito.Mockito
  2. Classes from package:
    • org.junit

Java -> Editor -> Save Actions

I have set all options like in clean up.

Java -> Editor -> Templates

I use many templates written on my own. There are some or them:
  1. after: method which have to be invoke after each JUnit test:
    ${:import (org.junit.After)}
    @After
    public void tearDown() {
        ${cursor}
    }
  2. before: method which have to be invoke before each JUnit test:
    ${:import(org.junit.Before)} 
    @Before
    public void prepareTest() {
     sut = new ${cursor} 
    }
  3. indent-off: when I do not want to have formatted code, for example when using long invocations in fluent API:
    // DO NOT INDENT
    
    //NOW INDENT
  4. logger: add log4j logger static member:
    private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class); ${imp:import(org.slf4j.Logger)} ${i:import(org.slf4j.LoggerFactory)}
  5. test: add JUnit test template:
    @${testType:newType(org.junit.Test)}
    public void should${cursor}() {
     //given
     
     //when
     
     //then
     fail(); ${staticImport:importStatic('org.junit.Assert.*','org.mockito.Mockito.*')} 
    }

Java -> Editor -> Typing

    Select all options. Everything is perfect.

    Plugins

    In fact, you need only one powerful plugin named MoreUnit. Additionally, when you start programming in TDD you could find useful plugin Pulse.

    MoreUnit

    Great plugin, which enable jumping between class implementation and tests using shortcuts:
    • CTRL+R - run tests for classes
    • CTRL+J - jump to test/implementation or create test class if not exist
    MoreUnit requires a few settings to work perfectly. Open Window menu, select Preferences and MoreUnit. In Java subpreferences set test source folder as src/test/java (when you use Maven). 
    I have unit and integration tests and I recognize them by suffix of test class name: unit test class ends with word Test and integration tests ends with IT, so as rule for MoreUnit I have set pattern '${srcFile}(Test|IT)' (the same pattern should be set in User Language subpreferences of MoreUnit).  Additionally, all test methods have content 'throw new RuntimeException("not yet implemented");' and I have enabledextended search for test methods, so that I can jump also between method implementation and tests using this method.

    Pulse

    It is simple plugin, which you have to start in pulse view and you could observe your 'TDD pulse' i.e. red (write failing test) -> green (make test pass by implementing class) -> refactor (implementation of class and test class) -> red -> ... as if it was hearbeats.

    Conclusion

    Eclipse is very powerful IDE. But when you download it, it requires some additional settings and, as you can see, one or two plugins to work perfectly and highly support programmer work.