JaCoCo, Maven and NetBeans 8 integration

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.

| Comments (3) »

22-May-14


Java 8: Grouping stuff

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.

| Comments (0) »

06-May-14


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

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);
    }
}

| Comments (2) »

05-May-14


Spring Boot as a backend for AngularJS

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.

| Comments (8) »

15-Apr-14


Messaging and Websockets with Spring 4

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

My old application had a J2ME(!) companion on my dump phone that send my location to the app, showing it on the page.

This was 2009… Before my iPhone time.

Planning a longer bike tour in 2014, i wanted this feature back but i have not the slightest ambition on writing an iPhone app anytime soon, so i asked around on twitter and Darko came up with OwnTracks which uses the MQ Telemetry Transport protocol for publishing (and subscribing to) location updates.

So what ingredients do we need to implement this in a standalone Java application? Actually, not many. I’ve added Apache Active MQ, Spring JMS and Messaging as well as Spring Websocket support for the frontend fun:

Spring Boot has a managed dependency for ActiveMQ but only 5.7 which has some bugs regarding the MQTT broker, therefor i use 5.9.

With those components given, it’s incredible easy to configure brokers for:

  • STOMP over WebSocket
  • Local (VM based) messaging
  • External messaging via MQTT

like this

In the simples case you would now add @EnableWebSocketMessageBroker to a configuration class and be done, but i wanted to use

  1. My own broker
  2. A username/password protected broker
  3. Also use @EnableScheduling

1. To use a custom broker, implement WebSocketMessageBrokerConfigurer (or extend AbstractWebSocketMessageBrokerConfigurer) in a configuration class and configure the relay

If you do this, be sure to add “org.projectreactor:reactor-tcp” to you dependencies, otherwise a weird ClassNotFoundException pops up…

While you’re at it, configure the thread pool size for in- and outbound channels in #configureClientInboundChannel and #configureClientOutboundChannel according to your needs.

2. See above, just use a simple Java based approach to configure the embedded broker.

3. Now this is fun… If you use some scheduled jobs in your application as i do, you’ll end up with the following exception: “More than one TaskScheduler and/or ScheduledExecutorService exist within the context”. Yeah, great… If you don’t configure a default scheduler, the ScheduledAnnotationBeanPostProcessor tries to find all beans of type TaskScheduler or ScheduledExecutorService… If it finds none, it uses the default, if it finds one, uses this, if it finds more, everything breaks… @EnableWebSocketMessageBroker creates 2 schedulers… So you need to configure your own:

I wish there is more to say, but the rest is standard… Putting together some listener that reacts on incoming locations, calls the Spring Data Repository and uses SimpMessagingTemplate to notify all subscribed STOMP clients. For details regarding WebSocket and STOMP have a look at the Spring reference. As i didn’t have any luck with the Atmosphere frameworks in 3 different applications since 2011, i’m really happy how the Spring solution turned out. Maybe she is still a little buggy, but i’m quite sure this will be fixed.

At the moment the location site runs on an uberspace behind a proxy, but STOMP together with SockJS handles this situation gracefully (and are actually dead simple to use):

It’s amazing what you can achieve with Java and Spring with little effort those days.

| Comments (3) »

21-Mar-14