Structural Design Patterns: Composite Pattern

Previously we checked the adapter pattern the use cases and the bridge pattern. The pattern we will examine in this post is the composite pattern.
By following the composite pattern we “compose” objects into tree structures representing part-whole hierarchies, therefore clients can treat individual objects and compositions uniformly.

By referencing the word hierarchies the first thing that comes to mind is organisations. A military organisation is a great example for the composite pattern.

One of the most basic actions of military personnel is to execute orders.
Thus we will make an interface which specifies the ability to execute orders.

package com.gkatzioura.design.structural.composite;

public interface MilitaryPersonnel {

    void executeOrder();

}

The private is the lowest rank in a military organisation. A private cannot delegate a task or give orders. Therefore he will just execute an order.

package com.gkatzioura.design.structural.composite;

public class Private implements MilitaryPersonnel {

    @Override
    public void executeOrder() {

    }

}

Above the private there are other ranks like Major, Lieutenant, Colonel etc. Those are officer ranks and officers execute orders but also they can assign orders.
So the Officer interface will specify the ability to assign orders.

package com.gkatzioura.design.structural.composite;

public interface Officer {

    void assignOrder();

}

Be aware that an officer in order to execute an order he will take some actions on his own and he might as well assign some orders to lower rank personnel.

So the Lieutenant will be able to execute orders but also to assign orders to ranks lower that him.

package com.gkatzioura.design.structural.composite;

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

public class Lieutenant implements MilitaryPersonnel, Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public Lieutenant(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    public void addPrivateUnderCommand(Private soldier) {
        lowerRankersonel.add(soldier);
    }
    
    @Override
    public void executeOrder() {
        
        //other actions

        assignOrder();

        //other actions.
    }

    @Override
    public void assignOrder() {

        lowerRankersonel.forEach(lr->lr.executeOrder());
    }
}

The same that applies to the lieutenant applies to the major who is able to execute orders and assign orders to lower ranks.

package com.gkatzioura.design.structural.composite;

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

public class Colonel implements MilitaryPersonnel, Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public Colonel(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    public void addPrivateUnderCommand(Private soldier) {
        lowerRankersonel.add(soldier);
    }

    public void addLieutenantUnderCommand(Lieutenant lieutenant) {
        lowerRankersonel.add(lieutenant);
    }

    @Override
    public void executeOrder() {
        //other actions

        assignOrder();

        //other actions
    }

    @Override
    public void assignOrder() {
        lowerRankersonel.forEach(lr->lr.executeOrder());
    }
}

In our scenario the general is the highest rank and thus when he assigns an order this order will be executed by the composite we implemented.

package com.gkatzioura.design.structural.composite;

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

public class General implements  Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public General(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    @Override
    public void assignOrder(MilitaryPersonnel militaryPersonnel) {
        militaryPersonnel.executeOrder();
    }
}

And a main class will display the composite’s functionality.

package com.gkatzioura.design.structural.composite;

import java.util.Collections;

public class CompositeScenario {

    public static void main(String[] args) {

        Private ryan = new Private();
        Lieutenant lieutenant = new Lieutenant(Collections.singletonList(ryan));
        Major major = new Major(Collections.singletonList(lieutenant));
        General general = new General();
        general.assignOrder(major);
    }
}

As you can see the general object, which is the client treated all the objects uniformly.
The whole hierarchy is represented in a tree structure.
The private is the leaf the major and the lieutenant represent the Composite that forwards the requests to the corresponding child components.

You can find the source code on github.

Also I have compiled a cheat sheet containing a summary of the Structural Design Patterns.
Sign up in the link to receive it.

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 bridge 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.

Also I have compiled a cheat sheet containing a summary of the Structural Design Patterns.
Sign up in the link to receive it.

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.

Also I have compiled a cheat sheet containing a summary of the Structural Design Patterns.
Sign up in the link to receive it.

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.

Spring Security with Spring Boot 2.0: Password Encoder

On a previous post we used the user details service in order to provide a way to load our data from a function based on a username given.

The implementation of the user details might be backed by an in-memory mechanism, a sql/no-sql database etc.
The options are unlimited.

What we have to pay attention when it comes to password storage is the password hashing.
For security reasons we want to store passwords in a hashed form.
Supposing someone gets unauthorised access to the table storing our user data. By storing the passwords clear text that person can retrieve the password of every user in the system.

So we want a way to hash our passwords before storing them to database.
Always be aware that your hashing has to be robust and up to date.
For example MD5 was very popular in the past but nowadays leads to poor security. Actually it is possible to crack MD5 passwords fairly easy if you use a gpu.

Spring Security provides us with out of the box functionality when it comes to encoding passwords.
Password encoder is an interface which is used through the authorisation process.


package org.springframework.security.crypto.password;


public interface PasswordEncoder {

	String encode(CharSequence rawPassword);

	boolean matches(CharSequence rawPassword, String encodedPassword);

}

The encode function shall be used to encode your password and the matches function will check if your raw password matches the encoded password. Once your user details service fetches the user information from the database then the password given to authorise shall be validated with the one fetched from the database. In this case spring will use the matches function.

Now spring provides us with various implementations of a password encoder.
Let’s try to create a password encoder bean.

package com.gkatzioura.security.passwordencoder.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class PasswordEncoderConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return rawPassword.toString().equals(encodedPassword);
            }
        };
    }
}

This bean is no different that the NoOpPasswordEncoder which comes with spring boot.
No we are going to do a small experiment and add a custom password encoder.
Our password encoder will compare the clear text password submitted by the user hash it and the compare it with an already hashed password from the equivalent user in our database.

To do the hashing we will user bcrypt.

    @Bean
    public PasswordEncoder customPasswordEncoder() {

        return new PasswordEncoder() {

            @Override
            public String encode(CharSequence rawPassword) {

                return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt(4));
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {

                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
            }
        };
    }

To test this we will set up our security by using the environmental variables as we’ve seen on a previous post.

First we need to have our password encoded. Our system will not have the password stored in any clear text form.

System.out.println(BCrypt.hashpw("user-password",BCrypt.gensalt(4)));
$2a$04$i4UWtMw6surai4dQMhoKSeLddi1XlAh2sSyG58K3ZvBHqVkhz8Y3y

So what we are gonna do next is to set our environmental variables before running our spring boot application.

SPRING_SECURITY_USER_NAME=test-user
SPRING_SECURITY_USER_PASSWORD=$2a$04$i4UWtMw6surai4dQMhoKSeLddi1XlAh2sSyG58K3ZvBHqVkhz8Y3y

Next step is to go to your login screen and give the credentials user-name and user-password.
As you can see you have just been authenticated.
Behind the scenes spring hashed the password you submitted and compared to the one existing through the environmental varialbles.

Secure a docker registry using ssl

As mentioned on a previous article having a registry with a username and password is not secure if the registry is not ssl configured.

DockerImage

So we are going to add the ssl certificates to our registry. To make things easier we will use let’s encrypt which is free.

Once we have generated the credentials we have to add them to the registry. We will create a directory called certificates which will contain the certificate pem file and the key pem file. Then we will move the generated certificates on the certificates directory with the names crt.pem and key.crt.

We will follow exactly the same steps we followed in the previous article to generate the password.

docker run --entrypoint htpasswd registry:2 -Bbn {your-user} {your-password} > auth/password-file

Now we are ready to create our registry by also specifying the certificates. To do so we will mount the certificates directory to our docker container. The we will specify where the registry is going to find the credentials on the containers filesystem

docker run -d -p 5000:5000 --restart=always --name registry -v `pwd`/auth:/auth -v `pwd`/certificates:/certificates -e "REGISTRY_AUTH=htpasswd" -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/password-file -e REGISTRY_HTTP_TLS_CERTIFICATE=/certificates/crt.pem -e REGISTRY_HTTP_TLS_KEY=/certificates/key.pem registry:2

So your registry will pickup the credentials specified and will also use the certificates created.
Next step is to do the dns mapping and add a dns entry which directs your subdomain to your registry’s ip.

However if you just wan’t to test it, you can run your registry locally and just change your /etc/hosts and add this entry.

127.0.0.1 registry.{your certificate's domain }

Once you navigate through your browser to https://registry.{your certificate’s domain }:5000
you will get a 200 status code and your browser will identify your connection as secure.