Java

Java Joy: Using Named Capturing Groups In Regular Expressions

Posted on by  
Hubert Klein Ikkink

In Java we can define capturing groups in regular expression. We can refer to these groups (if found) by the index from the group as defined in the regular expression. Instead of relying on the index of the group we can give a capturing group a name and use that name to reference the group. The format of the group name is ?<name> as first element of the group definition. The name of the group can be used with the group method of the Matcher class. Also we can use the name when we want to reference the capturing group for example with the replaceAll method of a Matcher object. The format is ${name} to reference the group by name. Finally we can use a named capturing group also as backreference in a regular expression using the syntax \k<name>.

In the following example we define a regular expression with named groups and use them with several methods:

Continue reading →

Java Joy: Turn A Pattern Into A Predicate

Posted on by  
Hubert Klein Ikkink

This week at work a colleague showed a nice feature of the Pattern class in Java: we can easily turn a Pattern into a Predicate with the asPredicate and asMatchPredicate methods. The asPredicate method return a predicate for testing if the pattern can be found given string. And the asMatchPredicate return a predicate for testing if the pattern matches a given string.

In the following example code we use both methods to create predicates:

Continue reading →

Prevent ResponseEntity being generated as OpenAPI model

Posted on by  
Tom de Vroomen

When using Springfox you can annotate your endpoints to automatically generate OpenAPI docs for your clients.
This blogpost will show how you can prevent Springfox generating a model on an endpoint with ResponseEntity as return type.
I’ll also cover how to prevent generating default responses.

Take an endpoint like below.
You want to return ResponseEntity because you want control over the status and body which is returned within your endpoint code.

Click to see the Spingfox configuration used for this example

Now your generated OpenAPI doc contains responses with a $ref to ResponseEntity.

Springfox will also generate default responses for 201, 202, 400, 401, 403, 404, which you may never need.

Click to see the generated definition for ResponseEntity (it is quite long)

Continue reading →

Don't pass null to a function

Posted on by  
Ties van de Ven

I have seen the following pattern appear quite a lot:

private String foo(String bar) {
  if(bar != null){
    return "bar";
  }
  return null;
}

Here the function is called with a nullable argument, and if the argument was null, the function will return null, and if not it will return a proper value. I do not like this, and here is why.

Continue reading →

Java streams vs for loop

Posted on by  
Ties van de Ven

Java streams vs for loop

I had quite a bit of trouble finding a good article about java streams vs for loops under this name so I guess I’ll have to write it myself. In this article I would like to talk about the difference of using the Streaming API and for loops from the standpoint of long term maintainability of the code.

tl;dr: To reduce maintenance costs of your projects, please do consider using the Stream API instead of for loops. It might take some investment in learning to do so, but this investment will pay off in the long run, both for the project and for the engineers.

Continue reading →

Java Joy: Combining Predicates

Posted on by  
Hubert Klein Ikkink

In Java we can use a Predicate to test if something is true or false. This is especially useful when we use the filter method of the Java Stream API. We can use lambda expressions to define our Predicate or implement the Predicate interface. If we want to combine different Predicate objects we can use the or, and and negate methods of the Predicate interfaces. These are default methods of the interface and will return a new Predicate.

Let’s start with an example where we have a list of String values. We want to filter all values that start with Gr or with M. In our first implementation we use a lambda expression as Predicate and implements both tests in this expression:

Continue reading →

Mutation testing in Maven & Sonarqube

Posted on by  
Casper Rooker

Introduction

You might have heard about Mutation Testing before. In the last 5 or 6 years it’s been a reasonably hot (“warm”?) topic to discuss in blogs and dev talks. So what is the added value over code coverage with just Unit Testing? Even if you could pride yourself with over 90% line and branch coverage, that coverage means nothing apart from that unit tests are touching production code. It says nothing about how well that code is tested, it doesn’t care whether any asserts exist in your tests. Imagine an engineer that tests a power drill he designed on a sheet of paper, and declaring that it does exactly what it was designed for: drilling holes. It’s obvious that this test is meaningless for a power drill that is meant to be used on wood, steel or stone.

Continue reading →

TestContainers project can make your (integration) test life easier

Posted on by  
Tom de Vroomen

There are those moments you wish you could just start up a real database or system for your (integration) test. In many tests I’ve written I used H2 or HSQLDB to have a data storage for my tests. It starts up quickly and almost supports everything you need to do your repository test or any other test needing data storage. But when your project progresses you start using other ways to store your data other than standard SQL or you use dialect specifics to create your database. This is the moment you discover H2 or HSQLDB is not supporting your database vendor specific features and you can’t get your test running. For example the support for PostgreSQL in H2 or HSQLDB isn’t great, using TIMESTAMP in a SQL script already makes H2 or HSQLDB break. Yes, there are workarounds, but you rather not apply them to keep your code clean and simple. This is the moment you wish it is cheap to start up a real database instance you can test against, so you’re sure your code works in your production environment. You could install the database software locally, make some scripts to initialise the database and clean up afterwards. Or you can make scripts to do this in a Docker container. But what if there’s something which makes this even cheaper to setup?

Well, there is something to help you: the TestContainers project. With TestContainers you can startup your favourite database from a Docker container. TestContainers made a wrapper around docker to have an easy setup for your tests. And even better, is doesn’t only work with your favourite database, it works with any docker container you need in your test. Okay, I have to admit, the startup time for your test is longer in comparison with H2 or HSQLDB, but on the other hand you get a fully functional database instance.

Continue reading →

Get your application version with Spring Boot

Posted on by  
Ties van de Ven

There are a few ways to get your application version with Spring Boot. One approach is using Maven resource filtering to add the version number as an enviroment variable in the application.yml during the build. Another approach is to use the Implementation-Version stored in the manifest file.

First of all, you need to enable resource filtering for your application.yml

Then you need to add a maven parameter to the application.yml. @ is used here instead of the standard ${} notation to prevent conflicts

And we can then retrieve it using @Value

The upside of this approach is that you always have a version number even when you start your application from your IDE, also by putting your variable in info.app.version, if you use Spring boot actuator, your version will be automatically available under the /info endpoint. However, this approach does require quite a bit of configuration.

Continue reading →

Grasping Java 8: open source Java 8 workshop

Posted on by  
Chiel van de Steeg

Although Java has always been awesome, Java 8 has brought the language several features the language was in dire need of. Apart from the long-awaited improved DateTime-API and the introduction of Optionals, Java 8 finally gave behaviour the attention it deserves by incorporating (a form of) functional programming into the language using lambdas.

The opportunities that Java 8 brought the language and the platform have long since been taken and functional styles of programming are part of our day-to-day routines as Java Developers. For-loops are a thing of the past for most of us, and although it had quite the learning curve, passing streams around and chaining operations on them to create some very readable code is common sense for us now.

Continue reading →

Spicy Spring: Create your own ResourceLoader

Posted on by  
Willem Cheizoo

As a Spring developer we know how to load a resource in a Service. The prefixes of classpath: and file: are commonly used. But what if we want to load resources from a different location like a database table RESOURCE, with our own prefix db:? The Spring Framework provides some default built-in resource implementations, which can be found in the chapter Resources in the Spring Framework Reference Guide. The URL is prefixed and handled by the corresponding ResourceLoader (JavaDoc). If we want to load a resource from a database table RESOURCE we have to create our own ResourceLoader which triggers on the prefix db:.

Let's create an interface which describes the action of getting a resource based on the resourceName.

Continue reading →

shadow-left