Apache Camel SSL on http4

When creating a camel route using http, the destination might require a ssl connection with a self signed certificate.

Therefore on our http client we should register a TrustManager that suports the certificate.

In our case we will use the https4 component of Apache Camel
Therefore we should configure the routes and add them to the camel context

RouteBuilder routeBuilder = new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("http://localhost")
                        .to("https4://securepage");
            }
        };
routeBuilder.addRoutesToCamelContext(camelContext);

But before we proceed on starting the camel context we should register the trust store on the component we are going to use.
Therefore we should implement a function for creating an ssl context with the trustore.
Supposed the jks file that has the certificate imported is located on the root of our classpath.

   private void registerTrustStore(CamelContext camelContext) {

        try {
            KeyStore truststore = KeyStore.getInstance("JKS");
            truststore.load(getClass().getClassLoader().getResourceAsStream("example.jks"), "changeit".toCharArray());

            TrustManagerFactory trustFactory = TrustManagerFactory.getInstance("SunX509");
            trustFactory.init(truststore);

            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, trustFactory.getTrustManagers(), null);

            SSLSocketFactory factory = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            SchemeRegistry registry = new SchemeRegistry();
            final Scheme scheme = new Scheme("https4", 443, factory);
            registry.register(scheme);


            HttpComponent http4 = camelContext.getComponent("https4", HttpComponent.class);
            http4.setHttpClientConfigurer(new HttpClientConfigurer() {

                @Override
                public void configureHttpClient(HttpClientBuilder builder) {

                    builder.setSSLSocketFactory(factory);

                    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("https", factory)
                            .build();

                    HttpClientConnectionManager connectionManager = new  BasicHttpClientConnectionManager(registry);

                    builder.setConnectionManager(ccm);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

After that our route would be able to access the destination securly.

Setup Jenkins for Node.js

Jenkis is a great ci server with many options and plugins.
With a bit of time and configuration we can use Jenkins for our Node.js applications.

First of all the Node.js plugin on Jenkins enables us to run node.js scripts as a build step.

Screen Shot 2015-06-20 at 3.10.17 PM

In order to proceeed executing various node.js tasks we can use shell build step.

The next step is to install packages using npm

Screen Shot 2015-06-20 at 3.16.59 PM

The next problem is how to keep our application up and running.

To achieve this we can use forever.

Just add the latest version as a dependency inside your package.json

"dependencies": {
"forever": "0.14.1"
}

Then in the same build step we should stop any already running applications.

./node_modules/forever/bin/forever stopall

And by calling forever with BUILD_ID=dontKillMe in front of it we will ensure that Jenkins would not kill our node.js process running, which is most probably an application listening to a port.

BUILD_ID=dontKillMe ./node_modules/forever/bin/forever start bin/www

 

Screen Shot 2015-06-20 at 3.23.46 PM

For unit testing I prefer the mocha framework.
xunit-file is a great plugin that will transform the results of mocha into a JUnit result file. Therefore we will add the mocha and xunit-file dependencies.

"dependencies": {
"mocha": "~2.2.4",
"xunit-file":"0.0.6"
}

As a build step we should setup

./node_modules/.bin/mocha --recursive --reporter xunit-file

 

Screen Shot 2015-06-20 at 3.31.53 PM 1

The xunit file produced on the workspace would be used from Jenkins in order to produce a JUnit report.

Therefore we should add a post build action to Jenkins that will publish the JUnit results.

Screen Shot 2015-06-20 at 3.33.31 PM

Database migration with Flyway

Flyway in an extremely convenient database migraton tool.
First and foremost it integrates wonderfully with maven.
But one of its biggest assets is the ability to run both sql migration scripts and java migration scripts.

Let us start with a simple maven project

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>migration</groupId>
    <artifactId>com.gkatzioura</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <flyway.version>3.1</flyway.version>
        <mysql.driver.version>5.1.33</mysql.driver.version>
        <database.url>{your jdbc url}</database.url>
        <database.user>{your database user}</database.user>
        <databese.password>{your database password}</databese.password>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
            <version>${flyway.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.flywaydb</groupId>
                <artifactId>flyway-maven-plugin</artifactId>
                <version>${flyway.version}</version>
                <configuration>
                    <baselineOnMigrate>true</baselineOnMigrate>
                    <url>${database.url}</url>
                    <user>${database.user}</user>
                    <password>${databese.password}</password>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.driver.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

When you issue through maven

mvn flyway:migrate

Then flyway will will lookup on the db/migration folder of your target to find any migration files. This folder can be changed by altering the content of the locations inside the configuration of the flyway plugin.

For my first migration file I will use sql

The sql file will be located on the db/migration folder which will reside on the maven resources folder.
The name would be V1_1__Create_Persons.sql
Therefore the full path would be src/main/resources/db/migration/V1_1__Create_Persons.sql

CREATE TABLE Persons
(
PersonID bigint(20) NOT NULL AUTO_INCREMENT,
LastName varchar(255),
FirstName varchar(255),
); 

The second file would be a java file.
It will be located on the package db.migration folder which will reside on the maven src folder.
The name would be V1_2__Insert_Persons.java
Therefore the full path would be src/main/java/db/migration/V1_2__Insert_Persons.java

package db.migration;

import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import java.sql.Connection;
import java.sql.Statement;

public class V1_2__Insert_Persons implements JdbcMigration
{

	@Override
	public void migrate(Connection connection) throws Exception
	{
		Statement stmt = connection.createStatement();

		stmt.addBatch("INSERT INTO Persons (FirstName,LastName) VALUES ('Emmanouil','Gkatziouras')");

		stmt.addBatch("INSERT INTO Persons (FirstName,LastName) VALUES ('Do not know','this guy')");

		try {
			stmt.executeBatch();
		}
		finally {
			stmt.close();
		}

	}

}

Since we provide a java file it is wise to call flyway by

mvn clean compile flyway:migrate

Aspect Oriented Programming: Qi4j

Qi4j is an emerging framework for composition, injection and aspect oriented programming.

Its main asset is composition however it provides us with tools such as concerns and sideofs in order to apply aspect oriented programming.

I will use the same example with the employees as I did on the previous posts by using Spring and Java EE.
Each employee whether he is a supervisor or a worker will have a different behavior before entering the working area.

First let us start with the interface

 
package com.gkatzioura;

public interface Employee {

    public void enterWorkArea();

}

Also I will create the default implementation for the Employee interface

 
package com.gkatzioura;

import java.util.logging.Logger;

public class EmployeeMixin implements Employee {

    private static final Logger LOGGER = Logger.getLogger(EmployeeMixin.class.getName());

    @Override
    public void enterWorkArea() {

        LOGGER.info("I will enter the work area");

    }

}

Now I will create two transient composites a worker and an employee.

 
package com.gkatzioura;

import org.qi4j.api.composite.TransientComposite;

public interface Worker extends Employee,TransientComposite {
}

 
package com.gkatzioura;

import org.qi4j.api.composite.TransientComposite;

public interface Supervisor extends Employee,TransientComposite {
}

And for each composite I will create a concern. Concern is the equivalent for MethodBeforeAdvice on spring.

 
package com.gkatzioura;

import org.qi4j.api.concern.ConcernOf;
import java.util.logging.Logger;

public class WorkerBeforeConcern extends ConcernOf<Employee> implements Employee{

    private static final Logger LOGGER = Logger.getLogger(WorkerBeforeConcern.class.getName());

    @Override
    public void enterWorkArea() {

        LOGGER.info("Informing the supervisor that I have arrived");

        next.enterWorkArea();
    }
}
 
package com.gkatzioura;

import org.qi4j.api.concern.ConcernOf;
import java.util.logging.Logger;

public class SupervisorBeforeConcern extends ConcernOf<Employee> implements Employee {

    private static final Logger LOGGER = Logger.getLogger(SupervisorBeforeConcern.class.getName());

    @Override
    public void enterWorkArea() {

        LOGGER.info("Check if everything is ok");

        next.enterWorkArea();
    }
}

The last class that remains is to assemble our environment.

 
package com.gkatzioura;

import org.qi4j.api.activation.ActivationException;
import org.qi4j.api.structure.Application;
import org.qi4j.api.structure.Module;
import org.qi4j.bootstrap.*;
import java.util.logging.Logger;

public class Main {

    private static Energy4Java qi4j;
    private static Application application;

    private static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    public static void main(String[] args) throws AssemblyException, ActivationException {

        qi4j = new Energy4Java();
        Application application = qi4j.newApplication(new ApplicationAssembler() {

            @Override
            public ApplicationAssembly assemble(ApplicationAssemblyFactory factory)
                    throws AssemblyException {

                ApplicationAssembly assembly = factory.newApplicationAssembly();

                LayerAssembly rootLayer = assembly.layer("layer");
                ModuleAssembly rootModule = rootLayer.module("module");

                rootModule.transients(Supervisor.class)
                        .withMixins(EmployeeMixin.class)
                        .withConcerns(SupervisorBeforeConcern.class);
                rootModule.transients(Worker.class)
                        .withMixins(EmployeeMixin.class).
                        withConcerns(WorkerBeforeConcern.class);

                return assembly;
            }
        });

        application.activate();

        Module module = application.findModule("layer", "module");

        Employee supervisor = module.newTransient(Supervisor.class);
        Worker worker = module.newTransient(Worker.class);

        supervisor.enterWorkArea();

        worker.enterWorkArea();

    }    
}

Liang’s hyphenation algorithm implementation in node.js

Currently I am involved in a project that requires some string hyphenation. Initially I took a shot by using Liang’s hyphenation algorithm (taken from here liang hyphenation in python).
However it could not match my needs therefore I had to switch to the one open-office uses.

Anyway here it is the javascript implementation as a node.js module.


function LiangHyphenator(patterns) {

    this.tree = {}
    this.patterns = patterns

    for(var i= 0;i<patterns.length;i++) {
        var pattern = patterns[i]

        this.__insertPattern(pattern)
    }

}

LiangHyphenator.prototype.__insertPattern = function(pattern) {

    var chars = this.__clearPattern(pattern)
    var points = this.__createPoints(pattern)

    this.__addPatternToTree(points,chars)
}

LiangHyphenator.prototype.__clearPattern = function(pattern) {
    var numericsExpression = new RegExp('[0-9]','g')
    return pattern.replace(numericsExpression,'')
}

LiangHyphenator.prototype.__createPoints = function(pattern) {

    var charExpression = new RegExp('[.a-z]','g')
    var splitted = pattern.split(charExpression)

    for(var i= 0;i<splitted.length;i++) {
        if(splitted[i]==='') {
            splitted[i]=0
        } else {
            splitted[i] = parseInt(splitted[i])
        }
    }

    return splitted
}

LiangHyphenator.prototype.__addPatternToTree = function(points,chars) {
    var tree = this.tree
    for(var i=0;i<chars.length;i++) {

        var c = chars[i]
        if(!tree[c]) {
            tree[c] = {}
        }
        tree = tree[c]

    }


    tree['None'] = points
}

LiangHyphenator.prototype.hyphenateWord = function(word) {
    if(word.length<=4) {
        return [word]
    }

    var work = '.'+word.toLowerCase()+'.'

    var points = this.__createZeroArray(work.length+1)

    var tree = {}

    for(var j=0;j<work.length;j++) {

        var restWord = work.slice(j)
        tree = this.tree

        for(var i=0;i<restWord.length;i++) {
            var char = restWord[i]
            if(tree[char]) {
                tree = tree[char]
                if(tree['None']) {
                    var p = tree['None']
                    for(var pi=0;pi< p.length;pi++) {
                        points[pi+j] = Math.max(points[pi+j],p[pi])
                    }
                }
            } else {
                break
            }
        }
    }

    points[1] = 0
    points[2] = 0
    points[points.length-2] = 0
    points[points.length-3] = 0

    var pieces = ['']
    var zipped = this.__zip([word.split(''),points.slice(2)])

    for(var i=0;i<zipped.length;i++) {
        var c = zipped[i][0]
        var p = zipped[i][1]

        pieces[pieces.length-1] += c

        if(p%2!=0) {
            pieces.push('')
        }
    }

    return pieces

}

LiangHyphenator.prototype.__createZeroArray = function(size) {

    zeroArray = []

    for(var i=0;i<size;i++) {
        zeroArray.push(0)
    }

    return zeroArray
}

LiangHyphenator.prototype.__zip = function (arrays) {
    var serial = Array.apply(null,Array(arrays[0].length)).map(function(_,i){
        return arrays.map(function(array){return array[i]})
    });

    return serial
}


module.exports = LiangHyphenator

Aspect Oriented Programming: Java EE

CDI is a part of the Java EE farmework which provides us with AOP.

This example is the same one with the spirng aop example post. I will display the behaviour of two beans with the same definition but each one has a different aspect, more specific they will use a different interceptor.

The Entered annotation would be our interceptor binding

package com.gkatzioura;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface Entered {
    
}

The employee interface will be used to create the beans for this project.

package com.gkatzioura;

import javax.ejb.Local;
import javax.ejb.Singleton;

@Local
public interface Employee {
    
    @Entered
    public void enterWorkArea();
    
}

We will have two different kind of advices.
The SupervisorBeforeAdvice

package com.gkatzioura;

import java.io.Serializable;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Entered
@Interceptor
public class SupervisorBeforeAdvice implements Serializable{
    
    private static final Logger LOGGER = Logger.getLogger(SupervisorBeforeAdvice.class.toString());
    
    @AroundInvoke
    protected Object protocolInvocation(final InvocationContext invocationContext) throws Exception {

        if(invocationContext.getMethod().getName().equals("enterWorkArea")) {
            LOGGER.info("Check if everything is ok");
        }
        
        return invocationContext.proceed();
    }
    
}

And the WorkerBeforeAdvice

package com.gkatzioura;

import java.io.Serializable;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Entered
@Interceptor
public class WorkerBeforeAdvice implements Serializable {
    
    private static final Logger LOGGER = Logger.getLogger(WorkerBeforeAdvice.class.toString());
    
    @AroundInvoke
    protected Object protocolInvocation(final InvocationContext invocationContext) throws Exception {
        
        if(invocationContext.getMethod().getName().equals("enterWorkArea")) {
            LOGGER.info("Informing the supervisor that I have arrived");
        }
        
        return invocationContext.proceed();
    }
    
}

Two different beans will implement our employee interface.

Supervisor

package com.gkatzioura;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

@Stateless
public class SupervisorEmployee implements Employee{

    @Override
    @Interceptors(SupervisorBeforeAdvice.class)
    public void enterWorkArea() {
    
    }
    
}

And worker

package com.gkatzioura;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

@Stateless
public class WorkerEmployee implements Employee{

    @Override
    @Interceptors(WorkerBeforeAdvice.class)
    public void enterWorkArea() {
    }
    
}

I will use JAX-RS to cal those beans

Application configuration

package com.gkatzioura.jersey;

import javax.ws.rs.core.Application;

@javax.ws.rs.ApplicationPath("rest")
public class ApplicationConfig extends Application {

}

And calling the two beans from different endpoints

package com.gkatzioura.jersey;


import com.gkatzioura.Employee;
import com.gkatzioura.SupervisorBeforeAdvice;
import com.gkatzioura.WorkerBeforeAdvice;
import javax.ejb.EJB;
import javax.interceptor.Interceptors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/")
public class AspectEndpoint {
    
    @EJB(beanName = "WorkerEmployee")
    Employee worker;
    
    @EJB(beanName = "SupervisorEmployee")
    Employee supervisor;
    
    @GET
    @Path("/worker/enter")
    public String workerEnter() {
        worker.enterWorkArea();
        return "worker entered";
    }
    
    @GET
    @Path("/supervisor/enter")
    public String supervisorEnter() {
        supervisor.enterWorkArea();
        return "supervisor entered";
    }
    
}

Aspect Oriented Programming: Spring

One of the most powerfull tools spring provides us with is aspect orientation.
Aspect oriented programming helps us to continue development for special use cases, without breaking our modularity.

This is part of a series of blog posts on aspect orientation using different tools.
The first one is about aspect orientation on Spring.

In this example I will display the behaviour of two beans from the same definition but each one has a different aspect.

The employe class will be used to create the beans for this project.

package com.gkatzioura.spring.employees;

public class Employee {

    public void enterWorkArea() {

    }

    public void leaveWorkArea() {

    }

}

However considering a company, probably there are more than one types of employes.
For our project we will use the aspect of the supervisor employee and the aspect of the worker employee.

The worker employee before entering the work area should inform the supervisor employee that he has arrived.
The supervisor employee before entering the area should check that everything is ok.

package com.gkatzioura.spring.employees;

import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class WorkerBeforeAdvice implements MethodBeforeAdvice {

    private static final Logger LOGGER = Logger.getLogger(WorkerBeforeAdvice.class);

    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {

        if (method.getName().equals("enterWorkArea")) {
            System.out.println("Informing the supervisor that I have arrived");
        }

    }

}
package com.gkatzioura.spring.employees;

import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class SupervisorBeforeAdvice implements MethodBeforeAdvice {

    private static final Logger LOGGER = Logger.getLogger(SupervisorBeforeAdvice.class);

    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        
        if(method.getName().equals("enterWorkArea")) {
            System.out.println("Check if everything is ok");
        }
    }
}

The advices defined above would have to be wired on our employee bean according to the aspect needs.
For the worker bean we will use the WorkerBeforeAdvice before entering the factory.
For the employee bean we wil use the SupervisorBeforeAdvice before leaving the factory

On your META-INF create a spring directory and inside the spring directory create the employeeapects.xml file. This file would wire the employee bean with the behaviours described above.
The first ProxyFactory Bean will be used to create employee beans wired with the WorkerBeforeAdvice behaviour.
The second ProxyFactory Bean will be used to create employee beans wired with the SupervisorBeforeAdvice behaviour.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="employee" class="com.gkatzioura.spring.employees.Employee"/>

    <bean id="workerBeforeBean" class="com.gkatzioura.spring.employees.WorkerBeforeAdvice"/>
    <bean id="supervisorBeforeBean" class="com.gkatzioura.spring.employees.SupervisorBeforeAdvice"/>

    <bean id="workerProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="employee"/>
        <property name="interceptorNames">
            <list>
                <value>workerBeforeBean</value>
            </list>
        </property>
    </bean>

    <bean id="superVisorProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="employee"/>
        <property name="interceptorNames">
            <list>
                <value>supervisorBeforeBean</value>
            </list>
        </property>
    </bean>

</beans>

On your dispatcher-servlet.xml you need to import employeeapects.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.gkatzioura.spring"/>

    <import resource="classpath:/META-INF/spring/employeeapects.xml"/>
    <mvc:annotation-driven/>
</beans>

We will create a controller in order to create the beans.

package com.gkatzioura.spring.controllers;

import com.gkatzioura.spring.employees.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AspectController {

    @Autowired
    @Qualifier("workerProxy")
    Employee workEmployee;

    @Autowired
    @Qualifier("superVisorProxy")
    Employee superVisorEmployee;

    @RequestMapping(value = "/")
    @ResponseBody
    public String index() {

        return "Check other endpoints";
    }

    @RequestMapping(value = "/worker/enter")
    @ResponseBody
    public String workerEnter() {
        workEmployee.enterWorkArea();
        return "Worker entered the factory";
    }

    @RequestMapping(value = "/supervisor/enter")
    @ResponseBody
    public String superVisortEnter() {
        superVisorEmployee.enterWorkArea();
        return "Supervisor entered the factory";
    }

}

You should hit the endpoint /worker/enter and /supervisor/enter.
You will notice that the workerEmployee and superVisorEmployee have a different reaction once calling the enterWorkArea function.

By hitting the /worker/enter endpoint, the string “Informing the supervisor that I have arrived” is printed on the console.
By hitting the /supervisor/enter endpoint, the string “Check if everything is ok” is printed on the console.