Showing posts with label Enterprise Integration Pattern. Show all posts
Showing posts with label Enterprise Integration Pattern. Show all posts

Apache Camel Mongodb component Example

Apache camel provides many components to interact with external systems, here is one simple example to connect mongodb using from apache camel route.

Create a maven project and add below dependencies

<dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-mongodb</artifactId>
            <version>2.12.1</version>
        </dependency>
    </dependencies>

 

Create a Camel route

package com.vinod.test;

import org.apache.camel.builder.RouteBuilder;

public class CamelMongoRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://localhost:8181/mongoSelect")
                .to("mongodb:myDb?database=customerdb&collection=customer&operation=findAll");
        from("jetty:http://localhost:8181/mongoInsert")
                .to("mongodb:myDb?database=customerdb&collection=customer&operation=insert");
    }
}

Create application context.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:camel="http://camel.apache.org/schema/spring"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camel:camelContext id="camel-client">
        <camel:routeBuilder ref="vinodroute" />
    </camel:camelContext>
    <bean id="myDb" class="com.mongodb.Mongo">
        <constructor-arg index="0" value="localhost" />
    </bean>
    <bean id="vinodroute" class="com.vinod.test.CamelMongoRoute" />
</beans>

Create a Main program

This main program will start the routes

package com.vinod.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CamelMongoMain {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
                      new ClassPathXmlApplicationContext("application-context.xml");
    }

}
 

Run it

1. Start Mongodb
2. Run the main program
3. Use rest client to give inputs

To insert data into mongodb

Request body= {name:"Vinod K K"}
Response from mongodb = [{ "_id" : { "$oid" : "5419cefb0364771a127e352c"} , "name" : "Vinod K K"}]

Data in mongodb
> use customerdb
switched to db customerdb
> show collections
customer
system.indexes
> db.customer.find()
{ "_id" : ObjectId("5419cefb0364771a127e352c"), "name" : "Vinod K K" }
>


Done !!!!

Download example

Camel Timer Example

Camel Timer component is used to generate or process message exchanges when a time fires. Here is one example to print ‘Hello world ‘ in each five seconds

Example

package com.vinod.test;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class TimerTest {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new TimerRoute());
        main.run(args);
    }
}

class TimerRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("timer://foo?period=5000").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                System.out.println("Hello world  :"
                        + System.currentTimeMillis());
            }
        });
    }
}

Output

Hello world  :1453013393616

Hello world  :1453013398609

Hello world  :1453013403614

Hello world  :1453013408617

Hello world  :1453013413621

Hello world  :1453013418624

 
Done!! download source codes from
 

Ref: http://camel.apache.org/timer.html

Camel Exception clause example

Camel provides Exception clause to handle exceptions , came RouteBuilder onException method will helps to handle exceptions. In this example we will move files from source directory to destination and in case RuntimeException occured we will move the messages to exceptionDirectory.

package com.vinod.test;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class OnExceptionTest {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new TestExceptionRoute());
        main.run(args);
    }
}

class TestExceptionRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        onException(RuntimeException.class).to("file:exceptionDirectory");
        from("file:source").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                throw new RuntimeException();
            }
        }).to("file:destination");
    }

}
 

Download source code 

https://github.com/kkvinodkumaran/camel

 

 

 

Camel DeadLetterChannel errorhandler Example

Camel supports the Dead Letter Channel from EIP patterns to handle errors. Camel will move the Exchange data in case any exceptions to Dead Letter channel. In this example we will see Route Builder error handler is moving the exchange data to dead letter channel. For testing this While moving the files from source to destination we are throwing exception.
package com.vinod.test;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class ErrorHandlerTest {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new TestRoute());
        main.run(args);
    }
}

class TestRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        errorHandler(deadLetterChannel("file:deadletter"));
        from("file:source").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                throw new RuntimeException();
            }
        }).to("file:destination");
    }
}

Camel Data transformation using Custom Expression


Camel provides custom expression class to control the data transformation. Here is one example which will convert the text file to html format.

Example

package com.vinod.test;

import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class CamelDatatransformation {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyRoute());
        main.run(args);
    }
}

class MyRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("file:source").transform(new Expression() {
            public <T> T evaluate(Exchange exchange, Class<T> type) {
                String body = exchange.getIn().getBody(String.class);
                body = body.replaceAll("\n", "<br/>");
                body = "<html><body>" + body + "</body></html>";
                return (T) body;
            }
        }).to("file:destination");
    }
}

Run it and place one input text file in source folder and see the destination folder

Done!!!

Camel Jetty Component Example

The jetty component provides HTTP-based endpoints for consuming and producing HTTP requests. Here is one simple example to expose a jetty end point and serving the http request from REST client.

1. Create Maven project with below dependencies.

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.12.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. Create a Simple Route to expose Jetty endpoint.

package com.vinod.test;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class CamelJettyExample {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyCamelJettyBuilder());
        main.run(args);
    }
}

class MyCamelJettyBuilder extends RouteBuilder {
    public void configure() {
        from("jetty:http://localhost:8181/mytestservice").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                String message = exchange.getIn().getBody(String.class);
                System.out.println("Hello Mr :" + message);
                exchange.getOut().setBody("Hello world Mr " + message);
            }
        });
    }
}

3. Run it
Run the application and hit the service
http://localhost:8181/mytestservice


4. Done !! Download application
https://github.com/kkvinodkumaran/camel

Spring JmsTemplate and MessageListener Example

Spring provides a JMS integration framework that simplifies the use of the JMS API, the JmsTemplate class is the core class which is available in spring JMS package. This class simplifies sending and receiving messages via simple spring configuration. In this example we will see how to send and listen a message using spring JmsTemplate and Apache activemq.

Environment Used

Java 1.7
Spring-jms 3.1.2
Activemq 5.8.0
Maven

Prerequisite

Start ActiveMQ message broker.

1. Create a Maven project and add below dependencies

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>

2. Create Spring configuration file (applicationContext.xml)

Configure Activmq ,JMS Message listener and jms template beans here

<?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:jms="http://www.springframework.org/schema/jms"
    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.xsd
                          http://www.springframework.org/schema/jms
                          http://www.springframework.org/schema/jms/spring-jms.xsd
                          http://activemq.apache.org/schema/core
                          http://activemq.apache.org/schema/core/activemq-core.xsd">

 
    <context:component-scan base-package="com.pretech" />
    <context:annotation-config />
    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <value>tcp://localhost:61616</value>
        </property>
    </bean>
 
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="myMessageQueue" />
    </bean>
    <jms:listener-container connection-factory="connectionFactory">
        <jms:listener destination="myMessageQueue" ref="messageListenerExample" />
    </jms:listener-container>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destination" />
    </bean>
 
</beans>

3. Create a Listener class to implements MessageListener

package com.pretech;
 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
 
import org.springframework.stereotype.Component;
 
@Component("messageListenerExample")
public class MessageListenerExample implements MessageListener {
 
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            ObjectMessage msg = (ObjectMessage)message;
          try {
            System.out.println("OnMessage Received :"+msg.getObject().toString());
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }}
}
 
}

4. Create a Main class to send messages (MessageSender.java)

package com.pretech;
 
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Session;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
 
public class MessageSender {
    public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          JmsTemplate jmsTemplate=(JmsTemplate) context.getBean("jmsTemplate");
          jmsTemplate.send(
                new MessageCreator() {
                      public ObjectMessage  createMessage(Session session) throws JMSException {
                          ObjectMessage message = session.createObjectMessage();
                          message.setObject("My first Message");                      
                           return message;
                      }
        }  );
 
          System.out.println("MESSAGE SENT TO myMessageQueue");
    }
 
}

5. Run it

Run the MessageSender.java and we will see below output in the console 

OnMessage Received  :My first Message
MESSAGE SENT TO myMessageQueue

Reference

Spring JMS

Spring JmsTemplate Send and Receive Example

Spring provides a JMS integration framework that simplifies the use of the JMS API, the JmsTemplate class is the core class which is available in spring JMS package. This class simplifies sending and receiving messages via simple spring configuration. In this example we will see how to send and receive a message to message broker using spring JmsTemplate and Apache activemq.

Environment Used

Java 1.7
Spring-jms 3.1.2
Activemq 5.8.0
Maven

Prerequisite

Start ActiveMQ message broker.

1. Create a Maven project and add below dependencies

 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
2. Create Spring configuration file (applicationContext.xml)
Configure Activmq and jms template beans here
<?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:jms="http://www.springframework.org/schema/jms"
    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.xsd
                          http://www.springframework.org/schema/jms
                          http://www.springframework.org/schema/jms/spring-jms.xsd
                          http://activemq.apache.org/schema/core
                          http://activemq.apache.org/schema/core/activemq-core.xsd">

    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <value>tcp://localhost:61616</value>
        </property>
    </bean>

    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="myMessageQueue" />
    </bean>

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destination" />
    </bean>

</beans>
 

3. Create a Main class to send and receive messages (MessageReceiver.java)

package com.pretech;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class MessageReceiver {

    public static void main(String[] args) throws JMSException {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          JmsTemplate jmsTemplate=(JmsTemplate) context.getBean("jmsTemplate");
          jmsTemplate.send(
                new MessageCreator() {
                      public ObjectMessage  createMessage(Session session) throws JMSException {
                          ObjectMessage message = session.createObjectMessage();
                          message.setObject("My first Message");                    
                           return message;
                      }
        }  );
     
          System.out.println("MESSAGE SENT TO myMessageQueue");
          Message receivedMessage=jmsTemplate.receive("myMessageQueue");
          ObjectMessage msg = (ObjectMessage)receivedMessage;
          System.out.println("Message Received :"+msg.getObject().toString());
    }

}
4. Run it

Run the MessageSender.java and we will see below output in the console and Active MQ broker

MESSAGE SENT TO myMessageQueue
Message Received :My first Message
image

Reference

Spring JMS

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts