Software Develoment Journey
Java, Spring Framework, How-to

Code faster with Intellij IDEA live templates

Intellij IDEA – in my opinion the most productive IDE for Java – comes with bunch of features helping getting rid of writing repetitive code – which is a everyday business no matter what language you use. One of them is live templates.

Live templates contain predefined code fragments. You can use them to insert frequently-used or custom code constructs into your source code file quickly, efficiently, and accurately.

IDEA comes with a set of live templates for Java, Maven, HTML, CSS and more and also enables to create custom templates.

Inserting live template

There are 2 ways to insert live template:

  1. Type live template abbreviation (for example dep) and next press TAB key
  2. Use shortcut Command + J (Mac) / Ctrl + J (PC) to popup list of available live templates in current context

At the beginning it’s quite difficult to remember all you wish to use and going back and forth from code to settings or browsing list is not very efficient – especially when you don’t know what you are looking for. That’s why I created gallery of (in my opinion) most useful built-in live templates for Java and Maven that can be used as a cheat sheet:

Maven

  • dep – Inserts <dependency/>

Read on →

Spring Boot - foundation for modern Java application

Spring Boot is relatively new project from Spring.io. Its aim is to simplify creating new Spring Framework based projects and unify their configuration by applying some conventions. This approach convention over configuration is already successfully applied in most of so called modern web frameworks like Ruby on Rails, Django or Play! Framework.

On the official website we can find primary goals:

  • Provide a radically faster and widely accessible getting started experience for all Spring development
  • Be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults
  • Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration)
  • Absolutely no code generation and no requirement for XML configuration

Spring-Boot is not just another Spring Framework component. It’s actually much more. It’s a base, foundation for most (maybe even all) next Spring based applications you are going to write.

Spring Framework itself is very powerful tool. It can do a lot of things for you and if it can’t – it plays nice with most of other frameworks in Java world. It suffers one thing – it is difficult to start coding in Spring and it’s often blamed for complexity. Indeed – boostraping complexity was a price you pay for wide feture set and flexibility you can achive. That explains huge popularity of blog posts like Spring configuration with annotations, Spring without web.xml etc. There are just A LOT of ways to bootstrap Spring (which is actually good).

It happened that price paid was too high – especially when such flexibility was not really needed. I believe that’s how frameworks like Dropwizard and Play! Framework were born.

Ok, so what actually does Spring Boot do?

  • simplifies project initial configuration – it is easier to start now with Spring than with Rails!
  • project portability out of the box – you can build your project to JAR with embedded Tomcat or Jetty as well as classic WAR and deploy it to any application server or cloud service
  • power-ups your development speed – mvn spring-boot:run starts embedded Tomcat with Spring in seconds. Combined with JRebel let see changes you made immediately
  • provides starters – dramatically easy integration with all Spring Framework family components. For example, if you want to use AOP just include spring-boot-starter-aop and you are good to go: all necessary dependencies are configuration is there
  • makes it easy to start application for functional/integration tests needs: SpringApplication.run(Application.class, args); in @Before method and your application is ready for Selenium or any other kind of real working application tests. You can forget about deploying application to container during pre-integration-test phase
  • provides basic metrics, health check and other nice features like remote shell support via CRaSH – hell yeah – you can now SSH to your application

Spring Boot is still under development. The latest version is 0.5.0 M7 and it is definitely ready for playing around and prototyping. Stable version will be released in the beginning of this year so don’t waste any time and have a look on Spring Guides introducing basic usage.

My recommendations for further reading/watching:

Read on →

JBoss Drools unit testing with junit-drools

Recently I’ve been working with a project heavily using JBoss Drools. I am not Drools expert – I am not also very convinced to this framework, or maybe only to particular use case in this project – and I found it quite difficult to write simple, maintainable unit tests for Drools based business rules.

That’s how junit-drools was born – simple helper library letting you write Drools test without putting too much boilerplate code (as you can find in Drools JBoss Rules 5.X Developer’s Guide examples).

Installation

Add Maven repository and dependency to your pom.xml:

1
2
3
4
<repository>
    <id>maciejwalkowiak.pl</id>
    <url>https://github.com/maciejwalkowiak/maven-repo/raw/releases/</url>
</repository>
1
2
3
4
5
6
<dependency>
    <groupId>pl.maciejwalkowiak</groupId>
    <artifactId>junit-drools</artifactId>
    <version>1.0</version>
    <scope>test</scope>
</dependency>

Usage

junit-drools provides DroolsJUnitRunner class that handles most boilerplate code you need to write to set up knowledge base and Drools session.

Lets consider following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@RunWith(DroolsJUnitRunner.class)
@DroolsFiles(value = "helloworld.drl", location = "/drl/")
public class AppTest {

    @DroolsSession
    StatefulSession session;

    @Test
    public void should_set_discount() {
        Purchase purchase = new Purchase(new Customer(17));

        session.insert(purchase);
        session.fireAllRules();

        assertTrue(purchase.getTicket().hasDiscount());
    }

    @Test
    public void should_not_set_discount() {
        Purchase purchase = new Purchase(new Customer(22));

        session.insert(purchase);
        session.fireAllRules();

        assertFalse(purchase.getTicket().hasDiscount());
    }
}
Read on →

Using SASS in Java web applications

Modern frontend technologies like SASS, Less or CoffeeScript are not as easy to setup in classic Java web application as it is in modern frameworks like Ruby On Rails or Play Framework but it is possible. After spending some time on a project using SASS I can’t really imagine going back to plain old CSS so I decided to have a look what is offered currently for Java.

There are very powerful (and complex) solutions for handling SASS compilation like Wro4j but I wanted something simple that meets requirements:

  • compiles SASS to CSS during build
  • not requiring me to add any additional libs to application
  • developer mode friendly – I want to be able to change SASS files on the fly during development and avoid server restarts
Read on →

Auditing entities in Spring Data MongoDB

Spring Data MongoDB 1.2.0 silently introduced new feature: support for basic auditing. Because you will not find too much about it in official reference in this post I will show what benefits does it bring, how to configure Spring for auditing and how to annotate your documents to make them auditable.

Auditing let you declaratively tell Spring to store:

Configuration

First of all Maven dependencies to latest Spring Data MongoDB and Spring Data Commons. Additionally in order to use date-related audit annotations we need to add joda-time to classpath.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.2.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
    <version>1.5.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.2</version>
</dependency>

In order to enable auditing we need to add <mongo:auditing/> to Spring configuration. Currently there is no way to configure it through Java Config.

1
2
3
4
5
6
7
8
<mongo:auditing />

<mongo:mongo id="mongo" />

<bean class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongo" ref="mongo" />
    <constructor-arg name="databaseName" value="blog-tests" />
</bean>
Read on →

ThoughtWorks’ Martin Fowler & Jez Humble in Berlin

On the 4th of October I had pleasure to attend to ThoughtWorks event in Berlin and listen to two lectures given by software development All-Stars:

Jez Humble, Martin Fowler in Berlin

If you did not attend and you don’t have good excuse – you should regret it. I have never seen such professionals in giving lectures like those two guys. No matter what was the reason of your absence in this post I will try to shortly summarize what this event was all about.

Read on →

Java test frameworks overview: Cucumber JVM, FEST 2.x, catch-exception

Beauty and curse same time of Java ecosystem is the variety of available frameworks and solutions. There are plenty of ready to use solutions for most of problems that we meet on our daily basis and the tricky part is only to choose the right one. It also applies to testing frameworks. Times when the only tool you use is JUnit are hopefully gone – now there are plenty of very high quality frameworks that help to write any kind of automated tests not only faster but what is more important tests reliability and maintainability factor increases a lot.

Today I would like to share with you 3 testing frameworks/tools that I find very useful and handy.

Cucumber JVM

Behavior Driven Development becomes more and more popular. In my opinion it is a great way not only writing acceptance tests but developing software in general. There are couple of BDD frameworks for Java and since march 2012 we can find real Java port of one of the most important Ruby frameworks – CucumberCucumber JVM.

Cucumber supports Gherkin language to define steps which makes it easy and natural to create specification. Another advantage of Gherkin is that there are cucumber-like frameworks for many languages and platforms which makes it grate to use in organization when team members need to learn only one way of defining steps.

Complete example of usage Cucumber-JVM can be found in version 1.0.0 official announcement. As you can see there – it does not look hard. Hard part begins when it comes to write testable step definitions – it is something for another post. That’s how example feature can look like:

1
2
3
4
5
6
7
Feature: As a player I want to be able to send mail invitation to my friends

Scenario: player sends successful invitation
        Given player "John Doe"
        When "John Doe" invites "jane.smith@somemail.com"
        Then 1 mail is sent
        And invitation from "John Doe" to "jane.smith@someemail.com" is saved
Read on →

Solving REST + Spring Security session problem

REST, sessions .. wait. There are no sessions in REST application, right? Well, thats true. If we can avoid sessions we should do that. REST is stateless. The main concern about statelessness is authentication. In usual web applications we were used to store user data in session after authentication. How to solve that if we don’t want to use sessions? We should authenticate every request.

Thanks to that we can scale our application, add new nodes, remove nodes without care about session replication and also about consumed Java heap memory.

Recently I’ve been working on high load REST application. Actually we didn’t expect to have high traffic there but surprisingly we had much much higher that we have been prepared for (it’s so called “happy problem”). Application is based on Spring Framework and its secured with Spring Security deployed on Apache Tomcat 7. All resources are totally stateless – HttpSession is not touched by any piece of my code. Unfortunately used Java heap space was increasing all the time until:

java.lang.OutOfMemoryError: Java heap space

was thrown. In order to analyze Java heap dump and runtime usage of heap I used VisualVM.

 

Read on →

Java code generation with JAnnocessor

In this article I will show you how to generate code with JAnnocessor framework created by Nikolche Mihajlovski. First time I met JAnnocessor on GeeCON 2012 conference during Nikolche’s speech: “Innovative and Pragmatic Java Source Code Generation” (slides). Afterwards I used it successfully in one of my projects. There are almost no resources about this framework so I hope my article will be useful for those who are interested in using it or just are looking for brand new toy for their project.

Background

Every Java developer uses some sort of code generation tool on a daily basis. Setters, getters, trivial constructors, toString – all of these is just a boilerplate code. Usually we generate it with our favorite IDE’s help. I can’t really imagine coding it manually and because Java is a static language we will never be able to skip this process.

Those trivial examples of code generation provided by all modern IDEs are not the only situations when code generation is useful. There are many modern frameworks generate some code to help us to write more reliable code and do it faster. I think the most well known examples are QueryDSL and JPA2 Metamodel Generator that creates objects used to perform type-safe database queries.

There are also other situations – not so well supported by IDE – where we could use code generation. Usually it might be helpful in generating:

  • builder
  • facade
  • DTOs and mappers from domain objects to DTOs

These are only examples. For some projects there might be something project specific where we can’t use any existing code generation tool and we have to write our own. How to do that? With Java APT – Annotation Processing Tool.

Read on →

GeeCON 2012: subjective review

GeeCON 2012In the middle of May one of the biggest Java conferences in Poland took place – GeeCON 2012. Although I think it is almost always worth to technical conferences even if lectures not necessarily fit your needs – it was my first time on GeeCON and first visit to technical conference since DevCrowd in April 2011. I went to GeeCON with hurray optimism and very high expectations. I was interested in lots of lectures and I hoped that I will be able to use some of knowledge shared there immediately when I am back to work (some people would call it conference driven development ;)).

Few facts about GeeCON

  • 3 days – one so called University Day and 2 main days
  • 5 paths – at most 5 lectures at same time
  • Variety of topics from Java EE by testing, tools like Vaadin, OSGI into Agile methodologies
  • No speech about Spring Framework or any related product
  • 500 attendees in total including 30 girls
Read on →