Use properties with your gradle project.

Most of us are used in the maven way of specifying properties by using the properties tag


    2.0.9.RELEASE

and then when it comes to a dependency it can be easily referenced as ${springdata.commons}.


	org.springframework.data
	spring-data-commons
	${springdata.commons}

This is a bit tricky when it comes to gradle. The way  to do so is by using the extra properties extension.

ext{
  springdataCommons = "2.0.9.RELEASE"
}
dependencies {
    compile "org.springframework.data:spring-data-commons:${springdataCommons}"
}

Be aware that in order for this to work you should use double quotes, since in groovy double-quoted String literals support String interpolation while single quoted don’t.

This might work for you but you might want to use the dot character, for example springdata.commons .

That’s not possible using the previous way due to confusing the springdata as a symbol.
A workaround is to use the set method from ext.

ext{
    set('springdata.commons', "2.0.9.RELEASE")
}

dependencies {
    compile "org.springframework.data:spring-data-commons:${property('springdata.commons')}"
}

Pay attention to the compile section since you are going to have the same problem there regarding your name, thus you need to use an expression.

The other way around is to use a gradle.properties file and add there your properties.

springdata.commons=2.0.9.RELEASE

You compile section will be just the same.

dependencies {
    compile "org.springframework.data:spring-data-commons:${property('springdata.commons')}"
}

Structural Design Patterns: Bridge Pattern

On the previous post we had a look at the adapter pattern. On this blog we are going to use the bridge pattern.
As mentioned by GOF the bright pattern usage is to “decouple an abstraction from its implementation so that the two can vary independently”.
How this translates to a software problem?
Imagine that you need to implement software for missiles.

You have Ballistic missiles, Cruise missiles, Rockets etc. Although they are all missiles and they may explode, their mechanisms differ a lot from type to type.

Taking the above into consideration most probably you are going to end with many layers of abstractions.
The missile and what it does vary a lot. And this is what the bridge pattern is all about. There is going to be a rocket abstraction and it’s behaviour will become largely different by providing a different component implementation, in our case the igniter.

We have one rocket interface specifying the missile actions.

package com.gkatzioura.design.structural.bridge;

public interface Missile {

    void explode();

}

And another interface which specifies the igniter actions.

package com.gkatzioura.design.structural.bridge;

public interface Igniter {

    void ignite();
}

And we are going to have a pyrogenic igniter implementation

package com.gkatzioura.design.structural.bridge;

public class PyrogenIgniter implements Igniter {

    public void ignite() {

    }
}

Last but not least we are going to have an AirToAirMissile implementation.

package com.gkatzioura.design.structural.bridge;

public class AirToAirMissile implements Missile {

    private Igniter igniter;

    public AirToAirMissile(Igniter igniter) {
        this.igniter = igniter;
    }

    public void explode() {

        //Actions relation to explosion

        igniter.ignite();
    }
}

So we will implement an air to air missile.

AirToAirMissile airToAirMissile = new AirToAirMissile(new PyrogenIgniter());

As you can understand missile components vary and based on the components their functionality changes.

You can find the source code on github.

Structural Design Patterns: Adapter Pattern

On previous blog posts we focused on creational design patterns such as the builder pattern, the abstract factory/factory pattern, the singleton and the prototype pattern.

We will switch our focus to the structural design patterns. By using structural design patterns our goal is to ease the design by identifying a simple way to realize relationships between entities.

Adapter pattern is one of the most used and well known structural patterns.
Its major usage is when you want to make classes work with other classes without having to change its source code.

Imagine the scenario of refactoring some code and you stumble upon a class sending emails.

package com.gkatzioura.design.structural.adapter;

import java.util.List;

public class MailSender {

    private String title;
    private String message;
    private List<String> recipients;

    public MailSender(String title, String message, List<String> recipients) {
        this.title = title;
        this.message = message;
        this.recipients = recipients;
    }

    public void sendMessage() {

    }

    public void sendHtmlMessage(String htmlTemplate) {

    }

}

The MailSender class has the ability to send an email but also you can use it in order to send an email containing html.

We want to add some subscribe/notify functionality in our code base so that people could receive a simple message in the form of sms, email, webhooks etc.

We have also come up with an interface for the notify functionality.

package com.gkatzioura.design.structural.adapter;

public interface Notifier {

    void notify(String recipients,String message);

}

As you can see our notify action does not really care about the subject or formatting of the message. You just have to notify the subscribes.
Among the rest implementation an email implementation should be provided.
We can either provide a new email implementation which implements the notifier interface or we can change the original email class.

However there is a third option. You can use the adapter pattern and create a class so that you can reuse your old email class.

By doing this you don’t alter your old email class and therefore the code which uses its functionality and also you skip creating a new class therefore having to maintain one extra class.

package com.gkatzioura.design.structural.adapter;

import java.util.List;

public class MailNotifierAdapter implements Notifier {

    private static final String NOTIFICATION_TITLE = "System notification";
    
    public void notify(List<String> recipients, String message) {
        
        MailSender mailSender = new MailSender(NOTIFICATION_TITLE,message,recipients);
        mailSender.sendMessage();
    }
}

You can find the sourcecode on github.

Gradle multi project build – parent pom like structure

When you come from a maven background most probably you have been used to the parent pom structure.

Now when it comes to gradle things are a little bit different.

Imagine the scenario of having a project including the interfaces and various other implementations.
This is going to be our project structure.

multi-project-gradle
-- specification
-- core
-- implementation-a
-- implementation-b

The specification project contains the interfaces, which the implementations will be based upon. The core project will contain functionality which needs to be shared among implementations.

The next step is to create each project inside the multi-project-gradle.

Each project is actually a directory with the builde.gradle file.

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Once done you need to do the linking between the parent project and the child project.
to do so you create the multi-project-gradle/settings.gradle and include the other projects.

rootProject.name = 'com.gkatzioura'
include 'specification'
include 'core'
include 'implementation-a'
include 'implementation- b'

Now if you set the build.gradle file for every sub project you’ve just realised that you include the junit dependency and the mavencentral repository everywhere.

One of the main benefits on using multi-project builds, is removing duplication.

To do so we shall create the multi-project-gradle/build.gradle file add the junit dependency and the maven central reference there.

subprojects {
    apply plugin: 'java'

    repositories {
        mavenCentral()
    }

    dependencies {
        testCompile group: 'junit', name: 'junit', version: '4.12'
    }

}

Now we can add our dependencies to each project and even specify the dependencies needed from the sub-projects.

For example the core project uses the specification project

dependencies {
  compile project(':specification')
}

and each implementation project uses the core project

dependencies {
    compile project(':core')
}

You can find the project on github.

Migrate your elastic beanstalk workers to docker containers

Amazon Elastic Beanstalk is one of the most popular services that aws provides. Elastic beanstalk comes with two options, the worker and the web application.

The worker application consumes the messages from a sqs queue and process them. If the process was successful the message is removed from the queue, if not the message shall remain in the queue or after some failed attempts it will go back to a dead letter queue. If you want to get more into elb I have made a tutorial on deploying you spring application using elb and cloudformation.

Elastic beanstalk workers are really great because they are managed, they can be scaled up/down depending on your workloads and they provide a wide variety of development environments like java, node.js and also you can use docker images.

Although elastic bean can work wonders if you have an aws based infrastructure you might face some issues when you will try to move to a container based infrastructure using a container orchestration engine.

Most probably your containerized worker application will work seamlessly without any extra configuration, however you need to find an alternative for the agent which dispatches the queue messages to your application.

In order to make things simple I implemented a mechanism which retrieves the messages from the queue and sends them to the worker application.

The container-queue-worker projects aims to provide an easy way to migrate your elastic beanstalk workers to a docker orchestration system.

Since the solution is Scala based it can either be used as a standalone jvm application or it can be run in a container using the image from dockerhub.

Once set up what you need to add the routing configurations.

This can be done using environmental variables

WORKER_TYPE=sqs
WORKER_SERVER_ENDPOINT=http://{docker-service}
WORKER_AWS_QUEUE_ENDPOINT=http://{amazon queue endpoint}

Or if you use it as a container you can add a config file on the /etc/worker/worker.conf path.

worker {
  type =  sqs
  server-endpoint = http://{docker-service}
  aws {
    queue-endpoint =  http://{amazon queue endpoint}
  }
}

In order to make thing easier for you I added a docker compose file simulating the desired outcome.

version: '3.5'
networks:
  queue-worker-network:
    name: queue-worker-network
services:
  worker-server:
    build:
      context: ./worker-server
      dockerfile: Dockerfile
    ports:
      - 8080:8080
    networks:
      - queue-worker-network
  elasticmq:
    build:
      context: ./elasticmq
      dockerfile: Dockerfile
    ports:
      - 9324:9324
    networks:
      - queue-worker-network
  container-queue-worker:
    image: gkatzioura/container-queue-worker:0.1
    depends_on:
      - elasticmq
      - worker-server
    environment:
      WORKER_TYPE: sqs
      WORKER_SERVER_ENDPOINT: http://worker-server:8080/
      WORKER_AWS_QUEUE_ENDPOINT: http://elasticmq:9324/queue/test-queue
      AWS_DEFAULT_REGION: eu-west-1
      AWS_ACCESS_KEY_ID: access-key
      AWS_SECRET_ACCESS_KEY: secret-key
    networks:
      - queue-worker-network

Fixing the if smell

From time to time we might end up with some huge ‘if’ statements in our codebase. Those statements have to be maintained and change the same code block over and over again. This is common also in cases where the ‘if’ statement checks if a variable belongs in a certain range of values.

Supposing you have an enum

public enum FoodType {

    FRUIT,
    VEGETABLES,
    RED_MEAT,
    WHITE_MEAT,
    FISH,
    DIARY,
    CERIAL
}

And you have a function making some recommendations

    public String recommend(FoodType foodType) {

        if(foodType==FoodType.FISH||foodType==FoodType.RED_MEAT||foodType==FoodType.WHITE_MEAT) {

            //execute a procedure
        } else if(foodType==FoodType.FRUIT||foodType==FoodType.VEGETABLES) {
            //execute a procedure
        } else {
            //execute a procedure
        }
    }

Now as you can see, a decision is made. The decision has to do with certain types of food which happen to belong under a specific group.
Fish, red meat and white meat are good for a user who prefers protein for his meal while fruit and vegetables are suited more for a fiber based diet.
In future cases this enum might be enhanced and more food types added to it.
The ‘if’ code block will have to be changed. Also in case, this complex ‘if’ statement is used in other files you will have to alter each file.
Not only you will have a huge if block but also a block which has to be maintained on each file and this might be error prone.

In order to avoid that you can change the contents of the if statement into a function.

package com.gkatzioura;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static com.gkatzioura.FoodType.*;

public class DietFilter {

    private static final Set FOODS_WITH_PROTEIN = Collections.unmodifiableSet(new HashSet(Arrays.asList(
            FISH,
            RED_MEAT,
            WHITE_MEAT)));

    private static final Set FOODS_WITH_FIBER = Collections.unmodifiableSet(new HashSet(Arrays.asList(
            FRUIT,
            VEGETABLES)));

    public static boolean proteinBased(FoodType foodType) {
        return FOODS_WITH_PROTEIN.contains(foodType);
    }

    public static boolean fiberBased(FoodType foodType) {
        return FOODS_WITH_FIBER.contains(foodType);
    }

}

So instead of adding each single case of food type, inside an ‘if’ statement we created a function which checks if the argument given belongs to a specific group.

Therefore your ‘if’ statement will change into this.

    public String recommend(FoodType foodType) {

        if(DietFilter.proteinBased(foodType)) {

            //execute a procedure
        } else if(DietFilter.fiberBased(foodType)) {
            //execute a procedure
        } else {
            //execute a procedure
        }
    }

If more food types are added to the enum, the developer will only have to change the construction of the set and add the extra food type.
It will be much easier than changing multiple parts of the code and it is way more readable.

Spring Security with Spring Boot 2.0: Securing your endpoints

Up until now in our previous posts we had our endpoints and controllers secured using the default spring security configuration.
When Spring Security is on the classpath, the auto-configuration secures all endpoints by default.

When it comes to complex applications we need different security policies per endpoints. We need to configure which endpoints should be secured, what type of users should be able to access the endpoints and endpoints that should be public.

A great example would be an endpoint which will displays a welcome message to the user.

package com.gkatzioura.security.securityendpoints.controller;

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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @GetMapping(path = "welcome")
    public String getMessage() {

        return "Welcome to the application";
    }
}

Regarding the fact that your application is already secured you need to provide public access to that endpoint.

In order to do so, spring provides us with the HttpSecurity class. By extending the WebSecurityConfigurerAdapter we can configure the endpoints which should be secured and the endpoint which should be public.

So let’s create the WebSecurityConfigurerAdapter configuration.

package com.gkatzioura.security.securityendpoints.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/welcome").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }
}

So let’s take it to parts by calling the authorizeRequests function. We get an http configurer and it’s possible to add the endpoints that we want public or secure.
By calling the function antMatchers we can pass an array of ant patterns. The function applied would create a rule for each endpoint specified in the antmatchers.
The next function is the anyRequest. The authenticated rule will be apply to any request received.

Last but not least spring comes with the default login form and the default logout endpoint. In order to make it feasible to login and logout we must allow access to these endpoints.

So the end result would be to have the welcome endpoint publicly accessible, a preconfigured form for login and the logout endpoint.