Solid Principles: Dependency inversion principle

Up until now we had a look on the single responsibility, open/closed, liskov substitution and interface segregation principles.
Dependency Inversion is one of the last principle we are gone look at.
The principle states that

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

Let’s get started with some code that violates that principle.
As a software team and we need to implement a project. For now the software team consists of:

A BackEnd Developer

package com.gkatzioura.solid.di;

public class BackEndDeveloper {

    public void writeJava() {
    }
}

And a FrontEnd developer

package com.gkatzioura.solid.di;

public class FrontEndDeveloper {

    public void writeJavascript() {
    }

}

And our project uses both throughout the development process.

package com.gkatzioura.solid.di;

public class Project {

    private BackEndDeveloper backEndDeveloper = new BackEndDeveloper();
    private FrontEndDeveloper frontEndDeveloper = new FrontEndDeveloper();

    public void implement() {

        backEndDeveloper.writeJava();
        frontEndDeveloper.writeJavascript();
    }

}

So as we can see the Project class is a high level module and it depends on low level modules such as BackEndDeveloper and FrontEndDeveloper. We are actually violating the first part of the dependency inversion principle.

Also by the inspecting the implement function of the Project.class we realise that the methods writeJava and writeJavascript are methods bound to the corresponding classes. Regarding the project scope those are details since in both cases they are forms of development. Thus the second part of the dependency inversion principle is violated.

In order to tackle this problem we shall implement and interface called the Developer interface.

package com.gkatzioura.solid.di;

public interface Developer {

    void develop();
}

Therefore we introduce an abstraction.

The BackEndDeveloper shall be refactored to

package com.gkatzioura.solid.di;

public class BackEndDeveloper implements Developer {

    @Override 
    public void develop() {
        writeJava();
    }
    
    private void writeJava() {
    }
    
}

And the FrontEndDeveloper shall be refactored to

package com.gkatzioura.solid.di;

public class FrontEndDeveloper implements Developer {

    @Override 
    public void develop() {
        writeJavascript();
    }
    
    public void writeJavascript() {
    }
    
}

The next step in order to tackle the violation of the first part would be to refactor the Project class so that it will not depend on the FrontEndDeveloper and the BackendDeveloper class.

package com.gkatzioura.solid.di;

import java.util.List;

public class Project {

    private List<Developer> developers;
    
    public Project(List<Developer> developers) {
    
        this.developers = developers;
    }

    public void implement() {

        developers.forEach(d->d.develop());
    }

}

The outcome is that the Project class does not depend on lower level modules but abstractions. Also low-level modules and their details depend on abstractions.

You can find the source code on github.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Interface segregation principle

Previously we examined the liskov substitution principle. Next principle is the interface-segregation. The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

Imagine an interface with many methods in our codebase and many of our classes implement this interface although only some of its methods are implemented.

In our case the Athlete interface is an interface with some actions of an athlete.

package com.gkatzioura.solid.segragation;

public interface Athlete {

    void compete();

    void swim();

    void highJump();

    void longJump();

}

We have added the method compete but also there some extra methods like swim highJump and longJump.
Suppose that JohnDoe is a swimming athlete. By implementing the Athlete interface we have to implement methods like highJump and longJump which JohnDoe will never use.

package com.gkatzioura.solid.segragation;

public class JohnDoe implements Athlete {

    @Override
    public void compete() {
        System.out.println("John Doe started competing");
    }

    @Override
    public void swim() {
        System.out.println("John Doe started swimming");
    }

    @Override
    public void highJump() {
    }

    @Override
    public void longJump() {
    }
}

The same problem will occur for another athlete who might be a field Athlete competing on high jump and long jump.
We will follow the interface segregation principle and we will refactor the original interface

package com.gkatzioura.solid.segragation;

public interface Athlete {

void compete();
}

Then we will create two other interfaces one for Jumping athletes and one for Swimming athletes.

package com.gkatzioura.solid.segragation;

public interface SwimmingAthlete extends Athlete {

    void swim();

}
package com.gkatzioura.solid.segragation;

public interface JumpingAthlete extends Athlete {

    void highJump();

    void longJump();

}

And therefore John Doe will not have to implement actions that he is not capable of performing.

package com.gkatzioura.solid.segragation;

public class JohnDoe implements SwimmingAthlete {

    @Override
    public void compete() {
        System.out.println("John Doe started competing");
    }

    @Override
    public void swim() {
        System.out.println("John Doe started swimming");
    }

}

You can find the source code on github. The last principle is the dependency inversion principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Liskov substitution principle

Previously we took a dive into solid principles including the single responsibility and the open/closed principle.
The Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping,

Supposing object S is a subtype of object T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of T.

Suppose we have the Employee class.

package com.gkatzioura.solid.liskov;

public class Employee {

    public void work() {

        System.out.println("Employee is working");
    }

}

Also we have another class which inherits the Employee class.

package com.gkatzioura.solid.liskov;

public class EmployeeOnVacation extends Employee {

    @Override
    public void work() {
        throw new IllegalArgumentException("Employees on vacation should not work");
    }
}

Supposing that we have a project.

package com.gkatzioura.solid.liskov;

import java.util.List;

public class Project {

    public void start(List<Employee> employees) {

        for(Employee employee:employees) {
            employee.work();
        }
    }
}

And we assign our employees to start working on it


        List<Employee> employees = new ArrayList<>();
        employees.add(new EmployeeOnVacation());
        employees.add(new Employee());

        Project project = new Project();
        project.start(employees);

The outcome would be an exception due to the employee who is on vacation and thus the project will not be completed.

The employee on vacation is an employee however he will not work. Even if the method didn’t throw an exception the method work would do nothing and this would affect delivering our project since our actucal team’s velocity is not the one we originally thought it was.

In order to avoid violating the principle we shall use a different approach and change the class hierarcy.

We will change the original employee class.

package com.gkatzioura.solid.liskov;

public class Employee {

    public String getTitle() {
        return "The employee's title";
    }

} 

And we will make make two different employee interfaces.
The WorkingEmployee interface.

 
package com.gkatzioura.solid.liskov;

public interface WorkingEmployee {

    public void work();
}

And the non working employee interface.

package com.gkatzioura.solid.liskov;

public interface NonWorkingEmployee {

    void relax();
}

Then the project will use only employees who are implementations of the WorkingEmployee interface and extend the employee class.

package com.gkatzioura.solid.liskov;

public class WorkingEmployeeImpl extends Employee implements WorkingEmployee {

    @Override
    public void work() {

    }
}
package com.gkatzioura.solid.liskov;

import java.util.List;

public class Project {

    public void start(List<WorkingEmployee> workingEmployees) {

        for(WorkingEmployee workingEmployee:workingEmployees) {
            workingEmployee.work();
        }
    }
}
List<WorkingEmployee> employees = new ArrayList<>();
employees.add(new WorkingEmployeeImpl());
Project project = new Project();
project.start(employees);

You can find the source code on github. Next principle is the interface segregation principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Open/closed principle

Previously we talked about the single responsibility principle. The open/closed principle is the second principle in the row regarding the solid principles acronym.

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”

By employing that principle the goal is to extend a module’s behaviour without modifying its source code.

Imagine a scenario of applying a discount to one of our products. A discount service will apply the discount specified and give back the discounted price.

Currently our system has only one kind of discount which applies to all adults.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Discount {

    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.10");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

And the discount service shall apply this discount to the price given.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public class DiscountService {

    public BigDecimal applyDiscounts(BigDecimal price,Discount discount) {

        return discount.apply(price);
    }
}

However our company wants to offer a discount to seniors, thus we have the senior Discount.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SeniorDiscount {

    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.20");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

This makes things a little more complicated for the discount service since the service has to apply both the discount for adult and both the discount for seniors.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public class DiscountService {

    public BigDecimal applyDiscounts(BigDecimal price,Discount discount) {

        BigDecimal discountPrice = price.add(BigDecimal.ZERO);
        discountPrice = discount.apply(discountPrice);
        return discountPrice;
    }

    public BigDecimal applySeniorDiscount(BigDecimal price,SeniorDiscount discount) {

        return discount.apply(price);
    }

}

By doing so we modified the discount service sourcecode to extend its behaviour. Also for every different discount that the sales department might come up with, the discount service will get extra methods.

In order to follow the open/closed principle we will create a discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public interface Discount {

    BigDecimal apply(BigDecimal price);
}

The default discount will be renamed to the AdultDiscount and implement the discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class AdultDiscount implements Discount {

    @Override
    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.10");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

The SeniorDiscount will also implement the Discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SeniorDiscount implements Discount {

    @Override
    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.20");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

Last but not least our DiscountService will be refactored in order to apply discounts based on the Discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public class DiscountService {

    public BigDecimal applyDiscounts(BigDecimal price,Discount[] discounts) {

        BigDecimal discountPrice = price.add(BigDecimal.ZERO);

        for(Discount discount:discounts) {

            discountPrice = discount.apply(discountPrice);
        }

        return discountPrice;
    }
}

By this way the discount service will be able to apply different discounts without altering its source code.

The same principle can be applied to the Discount.
Supposing we want to have a basic discount to be applied extra when a discount is applied.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BasicDiscount implements Discount {

    @Override
    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.01");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

By extending the BasicDiscount class we are able to have more discounts with the behaviour of the BasicDiscount and also extend this behaviour without modifying the BasicDiscount sourcecode.

You can find the source code on github. The next principle is the liskov substitution principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Single responsibility principle

The single responsibility principle is the first principle from the solid acronym.

“A class should have only one reason to change.”

Every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.

For example imagine the scenario of a navigation software.
We have a position which based on the direction given (north, south, west, east) the position should change.

The Position class contains values regarding the x and y axis position.

package com.gkatzioura.solid.single;

public class Position {

    private Integer xAxis;
    private Integer yAxis;

    public Position(Integer xAxis, Integer yAxis) {
        this.xAxis = xAxis;
        this.yAxis = yAxis;
    }

    public Integer getxAxis() {
        return xAxis;
    }

    public void setxAxis(Integer xAxis) {
        this.xAxis = xAxis;
    }

    public Integer getyAxis() {
        return yAxis;
    }

    public void setyAxis(Integer yAxis) {
        this.yAxis = yAxis;
    }
}

The direction is an enum representing the direction towards North, East, South and West.

package com.gkatzioura.solid.single;

public enum Direction {
    N,W,S,E
}

And at last there is a Navigator class which is responsible for navigating according to the direction and position change.


public class Navigator {

    public Position navigate(Position position, Direction direction) {
        ....
    }

}

In order to navigate properly the navigator should resolve the next position based on the direction. Also the navigator should fix the position in cases of values below 0.


public class Navigator {

    public Position navigate(Position position, Direction direction) {

        Position nextPosition = resolve(position,direction);
        Position fixedPosition =fix(nextPosition);
        return fixedPosition;
    }

    public Position resolve(Position position,Direction direction) {

        switch (direction) {
            case N:
                return new Position(position.getxAxis(),position.getyAxis()+1);
            case S:
                return new Position(position.getxAxis(),position.getyAxis()-1);
            case W:
                return new Position(position.getxAxis()-1,position.getyAxis());
            case E:
                return new Position(position.getxAxis()+1,position.getyAxis());
            default:
                throw new IllegalArgumentException();
        }
    }

    public Position fix(Position position) {

        return new Position(
                position.getxAxis()<0?0:position.getxAxis(),
                position.getyAxis()<0?0:position.getyAxis()
        );
    }

}

The problem with this approach is that in case the position validity criteria changes we have to change the Navigator class. The same applies in case of the position movement mechanisms changes. The navigator instead of just navigating is responsible for both resolving the next position and for fixing the new position.

An approach that does not break the single responsibility principle is to create a class that will resolve the next position and a class responsible for fixing the new position.

The NextPositionResolver class will resolve the next position based on the direction given.

package com.gkatzioura.solid.single;

public class NextPositionResolver {

    public Position resolve(Position position,Direction direction) {

        switch (direction) {
            case N:
                return new Position(position.getxAxis(),position.getyAxis()+1);
            case S:
                return new Position(position.getxAxis(),position.getyAxis()-1);
            case W:
                return new Position(position.getxAxis()-1,position.getyAxis());
            case E:
                return new Position(position.getxAxis()+1,position.getyAxis());
            default:
                throw new IllegalArgumentException();
        }
    }

}

The PositionRepairer class will fix the position in case of invalid x or y values.

package com.gkatzioura.solid.single;

public class PositionRepairer {

    public Position fix(Position position) {

        return new Position(
                position.getxAxis()<0?0:position.getxAxis(),
                position.getyAxis()<0?0:position.getyAxis()
        );
    }

}

The Navigator class will have as dependencies the NextPositionResolver and PositionRepairer classes in order to perform the navigation properly.

package com.gkatzioura.solid.single;

public class Navigator {

    private NextPositionResolver nextPositionResolver;
    private PositionRepairer positionRepairer;

    public Navigator(NextPositionResolver nextStepResolver,PositionRepairer positionRepairer) {
        this.nextPositionResolver = nextStepResolver;
        this.positionRepairer = positionRepairer;
    }

    public Position navigate(Position position, Direction direction) {

        Position nextPosition =  nextPositionResolver.resolve(position,direction);
        Position fixedPosition = positionRepairer.fix(nextPosition);
        return fixedPosition;
    }

}

You can find the source code on github. Next principle is the open/closed principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Integration tests with maven

Implementing unit tests with maven is something ordinary and most of us are familiar with the project structure and where the unit tests reside.

However Integration tests are a different case and most of times they have pretty different requirements.
For example it is ok to have your unit tests operate on a h2 in memory database but when it comes to integration tests and complex queries, it is best for them to be executed against an actual relational database like the one used in production.

Considering the above example, chances are that our integration tests might have different configurations and dependencies.

So our goals for our integration tests is to keep them separate from other tests and to execute them separately.

Regarding our maven structure within the source directory we have the main ‘folder’ and test ‘folder’.

In the same fashion we will add an extra directory called ‘it’.
The ‘it’ directory will contain a java directory for our java sources and a resources directory. Same structure with the test directory.

Then we should give instruction to maven on building our code and adding it to our test sources.

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>1.5</version>
                    <executions>
                        <execution>
                            <id>add-test-source</id>
                            <phase>process-resources</phase>
                            <goals>
                                <goal>add-test-source</goal>
                            </goals>
                            <configuration>
                                <sources>
                                    <source>src/it/java</source>
                                </sources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

By using the build helper maven plugin we can instruct maven to add extra test source directories to our our build.

The next step is to instruct maven to run our unit tests. To do so we will use the maven failsafe plugin.

The Failsafe Plugin is designed to run integration tests while the Surefire Plugin is designed to run unit tests. The name (failsafe) was chosen both because it is a synonym of surefire and because it implies that when it fails, it does so in a safe way.

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.15</version>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Then to execute the integration tests we should issue.

mvn verify

As expected our integration tests run separately.

To sum up, we want to have integration tests separated from our unit tests. Also we want them to run separately. This can be achieved by utilizing the maven failsafe plugin.
You can find an example project on github.

Run code on startup with Play and Scala

Depending on various projects, sometimes there is the need to execute some actions on initialization just before our application starts to serve requests.

It was a common practice to call the functions that we wanted to get executed through GlobalSettings, however it is not recommended.

The other way around to achieve this is to implement a class which will be injected and thus add the code that we want to get executed on the class constructor.

We might believe that it is sufficient to implement a class which shall use the @Singleton annotation.

For example

@Singleton
class StartUpService {

    //The code that needs to be executed

}

But this will not work as expected since our component instances on play are created lazily when they are needed.

Instances are created lazily when they are needed. If a component is never used by another component, then it won’t be created at all. This is usually what you want. For most components there’s no point creating them until they’re needed. However, in some cases you want components to be started up straight away or even if they’re not used by another component. For example, you might want to send a message to a remote system or warm up a cache when the application starts. You can force a component to be created eagerly by using an eager binding.

To tackle this problem, our singleton has to be initialized eagerly. To achieve an eager initialization we will define an eager binding.

To define an eager binding we have to implement a class that extends the AbstractModule and then bind our service as an eager singleton.

package com.gkatzioura.eager

import com.google.inject.AbstractModule
import com.google.inject.name.Names

// A Module is needed to register bindings
class EagerLoaderModule extends AbstractModule {
  override def configure() = {

    bind(classOf[StartUpService]).asEagerSingleton
  }
}

Then we have to enable our module by declaring so to our conf/application.conf configuration.

play.modules.enabled += "com.gkatzioura.eager.EagerLoaderModule"

The above approach creates a module by defining it explicitly. The other approach is to use the default functionality where Play will load any class called Module that is defined in the root package.

In conclusion, play gives us the option to execute certain functions once the application has started. To do so we need to implement a component as an eager singleton. Skip the GlobalSettings as it is not advised by the official documentation.

Spring boot and Apache Camel

As the world of software moves on, more complex systems are being developed, which have to integrate with each other. It started with SOA and it continues with microservices.

Camel is the number one integration tool that comes to my mind since nowadays spring boot with camel is a very strong combination.

 

Apache Camel

The first step is to include the camel dependencies to our spring project.

buildscript {
	ext {
		springBootVersion = '1.5.9.BUILD-SNAPSHOT'
	}
	repositories {
		mavenCentral()
		maven { url "https://repo.spring.io/snapshot" }
		maven { url "https://repo.spring.io/milestone" }
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.gkatzioura'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
	mavenCentral()
	maven { url "https://repo.spring.io/snapshot" }
	maven { url "https://repo.spring.io/milestone" }
}


dependencies {
	compile('org.apache.camel:camel-spring-boot-starter:2.20.0')
	testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.apache.camel:camel-test-spring:2.20.0')
}

In order to have a faster project setup from scratch you can always use the online spring initializer.

Now let’s add a simple route

package com.gkatzioura.springcamel.routes;

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class TimerRoute extends RouteBuilder {

    public static final String ROUTE_NAME = "TIMER_ROUTE";

    @Override
    public void configure() throws Exception {
        from("timer:initial//start?period=10000")
                .routeId(ROUTE_NAME)
                .to("log:executed");
    }
}

We don’t have to worry about the camel context configuration since the Camel auto-configuration creates a SpringCamelContext for you and takes care of the proper initialization and shutdown of that context.

Also camel auto-configuration collects all the RouteBuilder instances from the Spring context and automatically injects them into the provided CamelContext. Thus we don’t have to register our routes to the CamelContext.

As you can see our route has a timer with a period of 10000 milliseconds which routes to a log endpoint. The log endpoint will print the executed string every 10000 milliseconds.

Keep in mind that if no routeId is specified, camel will assign a name on its own, therefore giving a name to our route definition is a good practice in case we want to retrieve the root definition.

In order for camel to stay up, we need to keep our main thread blocked. Thus we add this configuration to our application.yml file.

camel:
  springboot:
    main-run-controller: true

Instead of this we can include the spring-boot-starter-web dependency, but our application has as few dependencies as possible, and we need to keep it this way.

However the most difficult part in the integration with other systems is testing. Throughout the years there have been rapid advancements on testing and the tools that we use.
Camel also comes packaged with some great tools in order to unit test.

For example we will implement a test of the route specified previously.

@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
public class SpringCamelApplicationTests {

    @EndpointInject(uri = MOCK_RESULT)
    private MockEndpoint resultEndpoint;

    @Autowired
    private CamelContext camelContext;

    @EndpointInject(uri = MOCK_TIMER)
    private ProducerTemplate producer;

    private static final String MOCK_RESULT = "mock:result";
    private static final String MOCK_TIMER = "direct:mock-timer";

    @Before
	public void setup() throws Exception {

	    camelContext.getRouteDefinition(TimerRoute.ROUTE_NAME)
                .autoStartup(true)
                .adviceWith(camelContext, new AdviceWithRouteBuilder() {
                    @Override
                    public void configure() throws Exception {
                        replaceFromWith(MOCK_TIMER);
                        interceptSendToEndpoint("log*")
                                .skipSendToOriginalEndpoint()
                                .to(MOCK_RESULT);
                    }
                });
    }

    @Test
    public void sendMessage() throws Exception {

        resultEndpoint.expectedMessageCount(1);
        producer.sendBody("A message");
        resultEndpoint.assertIsSatisfied();
    }

}

Let’s have a look on each part of the test.

Our JUnit runner of choice would be the CamelSpringBootRunner.class

@RunWith(CamelSpringBootRunner.class)

We inject a ProducerTemplate. The ProducerTemplate interface allows you to send message exchanges to endpoints in a variety of different ways to make it easy to work with Camel Endpoint instances from Java code.

Then we inject a MockEndpoint. The MockEndpoint will serve us by replacing the original endpoint. Then we will set the expected number of messages to be received. Once the processing is done we assert that the amount of received messages is satisfied.

On our setup method we will replace our original endpoint with the fake producer template endpoint. Thus our route will receive the events that we will issue from the ProducerTemplate.
Then we will also intercept the log endpoint and direct the message to the MockEndpoint previously specified.

So we ended up withe a camel application and a unit test for the route specified.
You can find the source code on github.

Spring and Threads: Transactions

In order to be able to use transactions with our thread we need to understand how transactions work with spring. Transaction information in spring is stored in ThreadLocal variables. Therefore these variables are specific for an ongoing transaction on a single thread.

icon-spring-framework

When it comes to an action run by a single thread the transaction gets propagated among the spring components called hierarchically.

Thus in case of a @Transactional  annotated service which spawns a thread, the transaction will not be propagated from the @Transactional service to the newly created thread. The result will be an error indicating that the transaction is missing.

Since the action that take place inside your thread, requires database access through jpa, a new transaction has to be created.

By looking at the @Transactional documentation  we can get more information on the transaction propagation types. The default propagation mode for @Transactional is REQUIRED.

Therefore by annotating a method with the @Transactional, a new transaction will be created and will be propagated to the other services called from our thread.

For example our async method can be annotated as Transactional


@Async
@Transactional
public void executeTransactionally() {
    System.out.println("Execute a transaction from the new thread");
}

The same applies for the method which will be invoked from the run function of a Runnable class. Although async is pretty simple to use, behind the scenes it wraps the call in a Runnable, which dispatched to an executor.

To sum up when it comes to work with threads and transaction in spring, it should be done with extra care. Also keep in mind that the transactions cannot be passed from thread to thread. Last but not least make sure that your @Async and @Transactional functions are public and go though the proxy that will make the necessary actions before being invoked.

Last but not least I’ve compiled a cheat sheet that lists some helpful spring & threads tips.
Sign up in the link to receive it.

Spring and Threads: Async

Previously we started working with spring and the TaskExecutor, thus we became more familiar on how to use threads on a spring application.

However using the task executor might be cumbersome especially when we need to execute a simple action.

Spring’s Asynchronous methods come to the rescue.

Instead of messing with runnables and the TaskExecutor, you trade the control of the executor for the simplicity of the async functions.
In order to execute your function in another thread all you have to do is to annotate your functions with the @Async annotation.

Asynchronous methods come with two modes.

A fire and forget mode: a method which returns a void type.

    @Async
    @Transactional
    public void printEmployees() {

        List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();
        employees.stream().forEach(e->System.out.println(e.getEmail()));
    }

A results retrieval mode: a method which returns a future type.

    @Async
    @Transactional
    public CompletableFuture<List<Employee>> fetchEmployess() {
        List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();
        return CompletableFuture.completedFuture(employees);
    }

Pay extra attention to the fact that @Async annotations do not work if they are invoked by ‘this’. @Async behaves just like the @Transactional annotation. Therefore you need to have your async functions as public. You can find more information on the aop proxies documentation.

However using only the @Async annotation is not enough. We need to enable Spring’s asynchronous method execution capability by using the @EnableAsync annotation in one of our configuration classes.

package com.gkatzioura.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * Created by gkatzioura on 4/26/17.
 */
@Configuration
@EnableAsync
public class ThreadConfig {

    @Bean
    public TaskExecutor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("sgfgd");
        executor.initialize();

        return executor;
    }

}

The next question is how we declare the resources and the threads pools that the async functions will use. We can get the answer from the documentation.

By default, Spring will be searching for an associated thread pool definition: either a unique TaskExecutor bean in the context, or an Executor bean named “taskExecutor” otherwise. If neither of the two is resolvable, a SimpleAsyncTaskExecutor will be used to process async method invocations.

However in some cases we don’t want the same thread pool to run all of application’s tasks. We might want separate threads pools with different configurations backing our functions.

To achieve so we pass to the @Async annotation the name of the executor we might want to use for each function.

For example  an executor with the name ‘specificTaskExecutor’ is configured.

@Configuration
@EnableAsync
public class ThreadConfig {

    @Bean(name = "specificTaskExecutor")
    public TaskExecutor specificTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.initialize();
        return executor;
    }

}

Then our function should set the qualifier value to determine the target executor of a specific Executor or TaskExecutor.

@Async("specificTaskExecutor")
public void runFromAnotherThreadPool() {
    System.out.println("You function code here");
}

On the next article we will talk about transactions on threads.

You can find the sourcecode on github.

Last but not least I’ve compiled a cheat sheet that lists some helpful spring & threads tips.
Sign up in the link to receive it.