Https in a nutshell

One of the topics I demystified recently was question of how HTTPS works in general. What happens when you type in your browser address bar URL starting with HTTPS?

HTTPS uses SSL (Secret Socket Layer) encryption for HTTP protocol, which gives HTTPS name.

As of the moment your browser issues HTTPS request to remote server, SSL handshake process triggers. Idea is that browser will request that from then on all the data send to the server and received back from is encrypted, so that no one can tamper the data during client / server communication.

During SSL handshake process client will exchange couple of messages with the server, like: Continue reading

Mocking same method multiple times using Mockito? Can’t be easier than that!

Hi, folks. This is fairly short blog post. I recently had the case I needed to mock the same method twice during my Junit test case, with different behavior.

To shorten your path how that is being made, take a quick look at :

package com.mydomain;

import org.junit.Test;
import org.mockito.Mockito;

import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

public class RepeatedMocker {
    @Test
    public void getsRightVersionWithNoRepeat() throws Exception {
        VersionManager versionManager = Mockito.mock(VersionManager.class);
        doReturn(1).when(versionManager).getVersion();
        SystemUnderTest systemUnderTest = new SystemUnderTest(versionManager);
        Optional<Integer> version = systemUnderTest.getVersion();
        assertThat(version.get()).isEqualTo(1);
        verify(versionManager).getVersion();
    }

    @Test
    public void getsRightVersionWithRepeat() throws Exception {
        VersionManager versionManager = Mockito.mock(VersionManager.class);
        doReturn(-1).doReturn(1).when(versionManager).getVersion();
        SystemUnderTest systemUnderTest = new SystemUnderTest(versionManager);
        Optional<Integer> version = systemUnderTest.getVersion();
        assertThat(version.get()).isEqualTo(1);
        verify(versionManager, times(2)).getVersion();
    }

    @Test
    public void failsGettingRightVersion() throws Exception {
        VersionManager versionManager = Mockito.mock(VersionManager.class);
        doReturn(-1).doReturn(-1).when(versionManager).getVersion();
        SystemUnderTest systemUnderTest = new SystemUnderTest(versionManager);
        Optional<Integer> version = systemUnderTest.getVersion();
        assertThat(version.isPresent()).isFalse();
        verify(versionManager, times(2)).getVersion();
    }

    private static class SystemUnderTest {
        private VersionManager versionManager;

        SystemUnderTest(VersionManager versionManager) {
            this.versionManager = versionManager;
        }

        Optional<Integer> getVersion() {
            int version = versionManager.getVersion();
            if (version == -1) {
                System.out.println("Trying once more, version can't be 1 ....");
                version = versionManager.getVersion();
                if (version == -1) {
                    System.out.println("Error: version can't be 1!");
                    return Optional.empty();
                }
            }
            return Optional.of(version);
        }
    }

    private static class VersionManager {
        int getVersion() {
            return Math.random() < 0.5 ? 1 : -1;
        }
    }
}

Continue reading

Spring MVC Junit testing

Hi, folks, if you’re interested in Junit testing your Spring MVC Controllers, feel free to visit Github repo containing very simple example of Spring MVC Controller and Junit test class testing it’s endpoints. Project is implemented using Spring boot.

Controller looks like this:

package rs.dodalovic.demos.category;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/categories")
public class CategoriesController {

    private CategoryService categoryService;

    @RequestMapping
    public List<String> allCategories() {
        return categoryService.getAllCategories();
    }

    @RequestMapping(value = "/{categoryId}", method = RequestMethod.GET)
    public ResponseEntity<String> showCategory(@PathVariable("categoryId") String categoryId) {
        final Optional<String> category = categoryService.getCategory(categoryId);
        if (category.isPresent()) {
            return ResponseEntity.ok(category.get());
        }
        return ResponseEntity.badRequest().body(categoryId);
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> createCategory(@RequestBody Category category) throws
            URISyntaxException {
        return ResponseEntity.created(new URI("http://localhost/categories/1")).body(null);
    }

    @Autowired
    public CategoriesController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}

Continue reading

Football application using Spring boot, Thymeleaf and Spring RestTemplate

As part of my effort to adopt Spring boot I noticed that I need to learn new view technology in Java ecosystem, since Spring boot doesn’t promote JSP, which I was used to using. I’ve explored alternatives a bit, and decided to give a shot to Thymeleaf as templating engine.

I was exploring a bit what it offers, and seems that I’ll stick to it in the future – based on set of nice features it has. I am providing you a Spring boot application using thymeleaf as a view technology so that you can take a look at it and see it if it suits your needs.

Additionally, to make it non trivial application, I’ve decided to demonstrate usage of thymeleaf by building football (soccer) application that integrates with free football api. Just go ahead and register quickly for free api token that your app can use to communicate to the external service. My application communicates with 3rd party using Spring’s RestTemplate API.

After registering with API, you’ll get API key, which you need to pass it as JVM argument when starting application (see below).

In the upcoming posts I will give my best to present most important aspects of Thymeleaf itself. In a meanwhile, feel free to download application sources and take a look at it.

In order to run the application, you need to go to app’s root directory and execute maven command (make sure to exchange ABCDEF with your API key):

spring-boot:run -Dsoccerapis_token=ABCDEF

which will start embedded Tomcat container running on 8080 port. After application is started, you can access it via:

http://localhost:8080/

Application displays european soccer leagues. By choosing league, you can furhter drill down to teams in given league, and finally – by choosing particular league – you can see the players squad with player details.

You can download application sources at Github.

Stay tuned and please – don’t forget to subscribe in case you’re eager to find out what’s coming next in upcoming posts.

Having trouble branding yourself – meet John Sonmez!

Recently I was listening to Software engineering radio podcast, where guest was very interesting and inspiring person – John Sonmez. He is a software developer, but actually much more than that. I strongly encourage everyone to read his book:

Soft Skills: The software developer’s life manual (Amazon link)

In that book he aggregates set of problems / challenges an average software developer encounters in her / his career. In there he covers most of the aspects that might influence career of a developer. He explains different careers you might have as a software engineer, such as company employee, consultant, entrepreneur. He explains advantages / disadvantages of each of them.

Continue reading

Transforming collections – Java 8 Collectors API

Java 8 offers new Stream API that makes handling collections easier and less verbose and error-prone. Stream API offers set of methods for filtering, transforming underlying collection, but our interest is to cover collect(Collector collector) method. This method offers very interesting functionality, such as transforming underlying collection to another collection type, grouping elements of collection, joining elements, partitioning elements…

Let’s get started with an example, and start explaining based on it. I suggest you open new tab with source code so that you can review the code sample while following explanation here. Continue reading