Skip to content
accelerando

Category Archives: Java

Mockito#validateMockitoUsage

12-Sep-14

Hi, long time no see… I really had a lot of work to do, been doing some freelance work in the nighttime and then there’s certainly my family. And apart from that, my current setup for this years projects is working quite well, thanks to Spring Boot and NetBeans for example.

Recently i had some failing tests. I used to Mockito to verify method calls and though i was sure the tested code was correct, the test kept failing.

What was wrong? The verification of calls run before the next mock. So what was failing was the previous test and I was too stupid to see the navigable exception at first (and second…).

To avoid this behavior and make the test fail that actually fails verification, add the following to your test class:

@After
public void validate() {
    Mockito.validateMockitoUsage();
}

or run your test with the MockitoJUnitRunner.

Read some about this behavior in the Mockito API: Mockito.validateMockitoUsage.

JaCoCo, Maven and NetBeans 8 integration

22-May-14

I was looking for a nice solution to measure the code coverage in my Spring Boot biking project.

It should support Java 8, Maven and for added bonus, my IDE.

I ended up using JaCoCo respectively the Maven plugin.

If you expect a lengthier post, i must disappoint you. All that was need to turn this:

before

into this

after

and also having a nice report like this (right click in NetBeans 8 on the project and choose “Code Coverage > Show Report…”)

report

was the following plugin declaration in maven:

<plugin>
	<groupId>org.jacoco</groupId>
	<artifactId>jacoco-maven-plugin</artifactId>
	<version>0.7.1.201405082137</version>
	<configuration>
	    <excludes>
		<!-- Application starter -->
		<exclude>ac/simons/biking2/Application.class</exclude>
		<!-- Configuration -->
		<exclude>ac/simons/biking2/config/*</exclude>			
	    </excludes>
	</configuration>
	<executions>
	    <execution>
		<id>pre-unit-test</id>
		<goals>
		    <goal>prepare-agent</goal>
		</goals>
	    </execution>
	    <execution>
		<id>post-unit-test</id>
		<phase>test</phase>
		<goals>
		    <goal>report</goal>		
		    <goal>check</goal>
		</goals>
		<configuration>
		    <rules>
			<!--  implmentation is needed only for Maven 2  -->
			<rule implementation="org.jacoco.maven.RuleConfiguration">
			    <element>BUNDLE</element>
			    <limits>
				<limit implementation="org.jacoco.report.check.Limit">
				    <counter>INSTRUCTION</counter>
				    <value>COVEREDRATIO</value>
				    <minimum>0.95</minimum>			
				</limit>
				<!--  implmentation is needed only for Maven 2  -->
				<limit implementation="org.jacoco.report.check.Limit">
				    <counter>COMPLEXITY</counter>
				    <value>COVEREDRATIO</value>
				    <minimum>0.75</minimum>
				</limit>
			    </limits>
			</rule>
		    </rules>
		</configuration>
	    </execution>
	</executions>
</plugin>

That’s it. NetBeans 8 recognizes JaCoCo immediately and everything works (except for my project not reaching my self set limits). No additional installs, no weird maven problems. Awesome.

Also i had no problems with JaCoCo and Java 8 features of any kind.

Java 8: Grouping stuff

06-May-14

I needed a function to sum (and therefor group) the values of a map of objects to Integers. My first solution was something like

As you can see, i use the collect method with a custom supplier, accumulator and combiner. The supplier prepares a new map, the accumulator takes the map and an entry and then uses Map#merge to sum the values.

The combiner than merges all created maps with the same logic.

There’s a nicer solution:

Use Collectors.html#groupingBy. This static helper method takes a classifier and a downstream. The classifier acts the same way as a Group-By clause in SQL, the downstream performs the actual reduction (in this case, a sum).

Neat.

Anyway, i have the slight feeling, i’m recreating a SQL syntax or at least using the idea.

Java 8: Sort or find maximum, minimum entries in maps

05-May-14

This is cool:

Map.Entry#comparingByKey and Map.Entry#comparingByValue. They both take another comparator or lambda that is used as a delegate for creating a Map.Entry comparator, that can be used to sort maps or find maximum and minimum pairs in a map by key or value like in the following example:

import java.time.LocalDate;
import java.util.Map;
import java.util.Random;
 
import java.util.TreeMap;
 
public class FindMaxMinInMaps {
    public static void main(String...a) {
	final Map<LocalDate, Integer> foobar = new TreeMap<>();
 
	// Fill a date -> int map with 12 random ints between 0 and 100, 
	new Random(System.currentTimeMillis()).ints(0,100).limit(12).forEach(value -> 
		foobar.put(
			LocalDate.now().withMonth(foobar.size() + 1), 
			value
		));
	// print them for verbosity
	foobar.entrySet().forEach(System.out::println);
	// get the maximum
	Map.Entry<LocalDate, Integer> max 
		= foobar
		    // from all entries
		    .entrySet()
		    // stream them
		    .stream()
		    // max, obviously
		    .max(
			    // this one is cool. It generates
			    // Map.Entry comparators by delegating to another
			    // comparator, exists also for keys
			    Map.Entry.comparingByValue(Integer::compareTo)
		    )
		    // Get the optional (optional because the map can be empty)
		    .get();
	System.out.println("Max is " + max);
    }
}

Spring Boot as a backend for AngularJS

15-Apr-14

This is the fourth Post in my series Developing a web application with Spring Boot, AngularJS and Java 8.

I’m more a backend and database guy than a frontend developer, but i know how to write valid HTML and add some unobtrusive JavaScript to it, for example in my daily photo project. Daily Fratze is an “old-school” website for visitors and a more interactive site for users.

For my Biking Project and this series of blog posts i wanted to try out something new (for me) and i picked AngularJS to create a single page web application.

Most of the things i’ve done in AngularJS are pretty standard (i guess), but have a look at the sources yourself: bikings js.

Therefor i want to highlight just a few things that made Spring Boot play nicely with AngularJS:

“Routes”

I wanted biking.michael-simons.eu as well as biking.michael-simons.eu/about too work when entered in the address bar or followed through a link. To achieve this, i’m using AngularJS in HTML5 mode. Really, for this project i couldn’t care less about browser which don’t support this:

The whole html “application” lives in webapp/public/index.html which is served as a static resource by Spring Boot without any further server interaction.

To create “routes” for all URLs in app.js, i’ve created a super simple @Controller:

This forwards all mapped urls to the static resource without any further view resolving. Nice!

WebJars

Spring Boot has excellent support for WebJars and automatically creates resolvers for them. Using web jars i can manage all dependencies for AngularJS and co. with Maven (yeah, i’m still using maven… ;) ):

and for example

And in index.html

Those placeholders work because i’ve enabled resource filtering in maven for selected resources in webapp. I know that there are a lot of JavaScript dependency managers out there, but this solution works very well for me. An option is to add wro4j to the mix.

Authentication

I’m using plain old http basic auth. Yes, i do know that the password is transmitted in plain text but for this app and this purpose, i just don’t care. For your interest, here’s the Spring Security configuration for stateless http basic auth:

I’ve got to disable csrf protection because i don’t want to handle that in AngularJS and also, i’ve disable frame headers because the application acts as an oembed provider with frames.

I didn’t protect the whole app, but only backend methods with write access through annotations which is enabled via @EnableGlobalMethodSecurity and looks like:

Using @RestController from AngularJS

The above quoted method can easily be used from AngularJS:

“$scope.bike” is a JSON object representing an instance NewBikeCmd. AngularJS maps this correctly as a @RequestBody, the thing is validated and everything else. Really nice.

Fancy things created with AngularJS

I’m not using AngularJS not long enough to rate this, but i really like the automatically refreshing about page which is created using through highcharts-ng and the nice OpenLayers integration for the tracks, written by myself: track-map-ng (OpenLayers), see an example here: Aachen – Domburg.

Summary

Rewriting this existing application from scratch (apart from the database model, that was fine), was real fun. Not only i could test and enjoy many new Java 8 features, but starting fresh, using well designed frameworks like Spring, Spring Boot and Spring Data JPA fixed many things for me i used to do wrong, sometimes because of some cargo cult i hand in mind, sometimes because i just didn’t get them right from the start.

Spring Boot together with Spring Data JPA are an excellent choice for me to write lightweight backends for JavaScript applications without loosing any functionality.

Look at some other projects of mine, i have no doubt that Boot is also a good choice for writing bigger applications, maybe with a more classical frontend, either JSP or Thymeleaf based.

Also: Java is not dead yet, in 2014 more far from than ever.

Thanks for reading so far.