Posts by Ties van de Ven

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's difficulties with Functional Programming

Posted on by  
Ties van de Ven

In my early days I spent most of my time fixing bugs on a huge enterprise application, so by now I learned from experience that a lot of bugs could have been easily prevented. This is why I prefer a Functional Programming style, I love how FP handles state. As a software consultant I get to switch companies and teams quite regularly and most projects I have been working on use java 7 or 8. This almost always leads to a few dicussions regarding programming style. So today I would like to talk about good FP principles, and how Java makes them hard (and why languages like Kotlin are awesome).

Most of my variables (95%+) are usually immutable, and I would like my compiler to check this for me. In Kotlin we have val and var to declare variables, val being immutable and val being mutable. To make a variable non-mutable in Java, we need to use the final keyword before all variables, including parameters to get the behaviour I desire.

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 →

6 Steps to help you debug your application

Posted on by  
Ties van de Ven

As a developer sooner or later you will encounter bugs, be it small ones or production breaking bugs. Now it is your task to find and fix the bug as soon as possible. In this article I will list the techniques I learned over the course of many years debugging web applications in the hope that it will help you be better and more efficient in bug hunting.

The process start with the actual bug report in a bug tracker. When reading the report, be careful for incomplete information or assumptions made by the reporter. It is easy to forget crucial steps in writing down the bug, so if possible, try to reproduce the bug with the reporter. Sometimes the bug report might contain possible causes to the bug. This happens more often if the reporter has a technical background. Be careful about trusting these assumptions made in the bug report since they are not always based on actual knowledge of the system, and it might create tunnel vision in finding the root cause.

Continue reading →

How to write bug free code - State

Posted on by  
Ties van de Ven

A lot of bugs are in some way related to state. So that is what we will be talking about today. We will start off with a quote from Einstein: “Insanity: doing the same thing over and over again and expecting different results. ” Code should be consistent, calling the same function with the same input should return the same result during the whole life cycle of the object. Insanity and bugs will follow if this rule is violated. This sounds logical, but in practise it is quite easy to violate this principle. The main cause of this, is object state. This state is used in a lot of functions, and can thus affect the behaviour of our program at runtime. This principle can be even be seen in the most basic of examples (imagine the impact on a more complicated class...). Given the following class:

public class Person {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Continue reading →

Integration testing on REST urls with Spring Boot

Posted on by  
Ties van de Ven

We are building a Spring Boot application with a REST interface and at some point we wanted to test our REST interface, and if possible, integrate this testing with our regular unit tests. One way of doing this, would be to @Autowire our REST controllers and call our endpoints using that. However, this won't give full converage, since it will skip things like JSON deserialisation and global exception handling. So the ideal situation for us would be to start our application when the unit test start, and close it again, after the last unit test. It just so happens that Spring Boot does this all for us with one annotation: @IntegrationTest. Here is an example implementation of an abstract class you can use for your unit-tests which will automatically start the application prior to starting your unit tests, caching it, and close it again at the end.

package demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.fasterxml.jackson.databind.ObjectMapper;

@RunWith(SpringJUnit4ClassRunner.class)
// Your spring configuration class containing the @EnableAutoConfiguration
// annotation
@SpringApplicationConfiguration(classes = Application.class)
// Makes sure the application starts at a random free port, caches it throughout
// all unit tests, and closes it again at the end.
@IntegrationTest("server.port:0")
@WebAppConfiguration
public abstract class AbstractIntegrationTest {

    // Will contain the random free port number
    @Value("${local.server.port}")
    private int port;

    /**
     * Returns the base url for your rest interface
     *
     * @return
     */
    private String getBaseUrl() {
        return "http://localhost:" + port;
    }

    // Some convenience methods to help you interact with your rest interface

    /**
     * @param requestMappingUrl
     *            should be exactly the same as defined in your RequestMapping
     *            value attribute (including the parameters in {})
     *            RequestMapping(value = yourRestUrl)
     * @param serviceReturnTypeClass
     *            should be the the return type of the service
     * @param parametersInOrderOfAppearance
     *            should be the parameters of the requestMappingUrl ({}) in
     *            order of appearance
     * @return the result of the service, or null on error
     */
    protected T getEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object... parametersInOrderOfAppearance) {
        // Make a rest template do do the service call
        final TestRestTemplate restTemplate = new TestRestTemplate();
        // Add correct headers, none for this example
        final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
        try {
            // Do a call the the url
            final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,
                    parametersInOrderOfAppearance);
            // Return result
            return entity.getBody();
        } catch (final Exception ex) {
            // Handle exceptions
        }
        return null;
    }

    /**
     * @param requestMappingUrl
     *            should be exactly the same as defined in your RequestMapping
     *            value attribute (including the parameters in {})
     *            RequestMapping(value = yourRestUrl)
     * @param serviceListReturnTypeClass
     *            should be the the generic type of the list the service
     *            returns, eg: List * @param parametersInOrderOfAppearance
     *            should be the parameters of the requestMappingUrl ({}) in
     *            order of appearance
     * @return the result of the service, or null on error
     */
    protected List getList(final String requestMappingUrl, final Class serviceListReturnTypeClass, final Object... parametersInOrderOfAppearance) {
        final ObjectMapper mapper = new ObjectMapper();
        final TestRestTemplate restTemplate = new TestRestTemplate();
        final HttpEntity requestEntity = new HttpEntity(new HttpHeaders());
        try {
            // Retrieve list
            final ResponseEntity entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance);
            final List> entries = entity.getBody();
            final List returnList = new ArrayList();
            for (final Map entry : entries) {
                // Fill return list with converted objects
                returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass));
            }
            return returnList;
        } catch (final Exception ex) {
            // Handle exceptions
        }
        return null;
    }

    /**
     *
     * @param requestMappingUrl
     *            should be exactly the same as defined in your RequestMapping
     *            value attribute (including the parameters in {})
     *            RequestMapping(value = yourRestUrl)
     * @param serviceReturnTypeClass
     *            should be the the return type of the service
     * @param objectToPost
     *            Object that will be posted to the url
     * @return
     */
    protected T postEntity(final String requestMappingUrl, final Class serviceReturnTypeClass, final Object objectToPost) {
        final TestRestTemplate restTemplate = new TestRestTemplate();
        final ObjectMapper mapper = new ObjectMapper();
        try {
            final HttpEntity requestEntity = new HttpEntity(mapper.writeValueAsString(objectToPost));
            final ResponseEntity entity = restTemplate.postForEntity(getBaseUrl() + requestMappingUrl, requestEntity, serviceReturnTypeClass);
            return entity.getBody();
        } catch (final Exception ex) {
            // Handle exceptions
        }
        return null;
    }
}

Continue reading →

shadow-left