Showing posts with label ActiveMQ. Show all posts
Showing posts with label ActiveMQ. Show all posts

Monday, February 17, 2020

External Active MQ + Hibernate with JBoss FUSE 7.4

In this post I will demonstrate how to configure External Active MQ with JPA implementation of Hibernate on Karaf platform on JBoss fuse 7.4. I will use previous JPA project as code base to start the development. You can refer about it from my previous blog post.


Prerequisites 


  1. You should have install java 1.8 or above.
  2. You should have IDE installed in your PC in my case I'm using IntelliJ IDEA.
  3. Your PC should setup Maven installed and configured.
  4. Your  PC should install and setup SQLServer.
  5.  Checkout base project from JPA project as code base.


Application module Dependency 

First Lets add relevant dependencies in to Application POM file. Following is the full feature file content and updated part on bold font. Since we are using ActiveMQ we need to add relevant dependency for that.


<?xml version="1.0" encoding="UTF-8"?>
<features name="osgi-customer-management-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.3.0 http://karaf.apache.org/xmlns/features/v1.3.0">
    <feature name="osgi-customer-management-datasource" version="${project.version}">
        <config name="org.ops4j.datasource-customer-management">
            osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver
            osgi.jdbc.driver.name=mssql
            databaseName=customer-management
            url=jdbc:sqlserver://LAPTOP-E0A1RCAN:1433;databaseName=customer-management
            user=nirmal
            password=Test123_
            dataSourceName=customer-management
            org.apache.karaf.features.configKey = org.ops4j.datasource-customer-management
        </config>
        <capability>osgi.service;javax.persistence.EntityManager;objectClass=javax.sql.DataSource;osgi.jndi.service.name=customer-management</capability><!--;effective:=active-->
    </feature>
    <feature name="Model" version="${project.version}">
        <feature>transaction</feature>
        <feature>jndi</feature>
        <feature>pax-jdbc-config</feature>
        <feature>pax-jdbc-h2</feature>
        <feature>pax-jdbc-mssql</feature>
        <feature>pax-jdbc-pool-dbcp2</feature>
        <feature>jdbc</feature>
        <feature>pax-jms-pool</feature>
        <feature>pax-jms-config</feature>
        <feature>camel-activemq</feature>
        <feature>artemis-jms-client</feature>
        <feature>pax-jms-artemis</feature>
        <feature>camel-blueprint</feature>
        <feature>camel-jms</feature>
        <feature>camel-activemq</feature>
        <feature>pax-jms-activemq</feature>
        <feature dependency="true">aries-blueprint</feature>
        <feature version="[2,3)">jpa</feature>
        <feature version="[5,6)">hibernate</feature>
        <bundle>mvn:com.fuse.hibernate.example/Model/${project.version}</bundle>
    </feature>
    <feature name="Service" version="${project.version}">
        <feature version="${project.version}">Model</feature>
        <bundle>mvn:com.fuse.hibernate.example/Service/${project.version}</bundle>
        <capability>osgi.service;objectClass=javax.persistence.spi.PersistenceProvider;effective:=active;javax.persistence.provider=org.hibernate.jpa.HibernatePersistenceProvider</capability>
    </feature>
    <feature name="Application" version="${project.version}">
        <feature version="${project.version}">Model</feature>
        <feature version="${project.version}">Service</feature>
        <bundle>mvn:com.fuse.hibernate.example/Application/${project.version}</bundle>
    </feature>
</features>



Defining the ActiveMQ endpoint in BluePrint  


We can add ActiveMQ endpoint in to our BlurPrint.xml file in the Application module. We just need to modify following content which colored in bold. 

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0" xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
             http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
  <jpa:enable />
  <tx:enable-annotations />
  <service ref="personService" interface="com.fuse.hibernate.example.service.PersonService" />
  <bean id="personService" class="com.fuse.hibernate.example.service.PersonServiceImpl" />
  <bean
          class="com.fuse.hibernate.example.app.ExchangeProcessor" id="exchangeProcessor">
    <property name="personService" ref="personService"/>
  </bean>
  <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
    <property name="brokerURL" value="tcp://localhost:61616"/>
  </bean>

  <camelContext xmlns="http://camel.apache.org/schema/blueprint"
                id="cbr-example-context" >
    <route id="cbr-route" >
      <from uri="file:work/cbr/input" />
      <log message="Sending order ${file:name} to another country" />
      <log id="logStatusIncident" message="OrderDetails Call ${body}"/>
      <to uri="file:work/cbr/output/others" />
      <convertBodyTo type="java.lang.String"/>
      <process ref="exchangeProcessor"/>
      <log  message="${body}" />

    </route>

    <route id="ACTIVEMQ">
      <from uri="activemq:queue:inbound.queue"/>
      <process ref="exchangeProcessor"/>
      <log  message="${body}" />
    </route>
  </camelContext>

</blueprint>


Explanation of the route "ACTIVEMQ"
It will read messages from "inbound.queue" and then it will pass to the "exchangeProcessor"  which have the responsibility of saving the message that passing from the queue.


Installing in to FUSE 7.4

We can use same set of commands except one new dependency addition code. In order to add dependencies first we have to run the fuse.bat file and then go to the console and enter following commands one by one. Only the third command new from previous post.


osgi:install -s mvn:com.microsoft.sqlserver/mssql-jdbc/7.4.1.jre8

osgi:install -s mvn:org.ops4j.pax.jdbc/pax-jdbc-mssql/1.3.5

osgi:install -s mvn:org.apache.cxf/cxf-rt-rs-client/3.0.4.redhat-621084



Then lets install application by entering following commands one by one


feature:repo-add mvn:com.fuse.hibernate.example/Feature/1.0-SNAPSHOT/xml



feature:install osgi-customer-management-datasource


feature:install Model

feature:install Service

feature:install Application


Then after "list" command you should be able to see all the things we installed. Similar to below figure.

After Successful installation LIST command should return something similar to this.

You can verify by accessing http://localhost:8181/cxf/ link you should be able to see following UI in browser.

http://localhost:8181/cxf/ output once successfully installed the Application 

Now you can click the WADL link and see the defined endpoints in there.

WADL output for defined REST service.
If you check the "http://localhost:8181/hawtio/camel/routes" then you should be able to see similar figure to below figure.

hawtio camel routes 

Lets run ActiveMQ server


In order to demonstrate this we need to have ActiveMQ server run in our local PC. First lets download it from official web page in following location. Then extract it in to your local PC and then go to apache-activemq-5.15.11\bin\win64 location from extraction parent directory. Then run the activemq.bat to start our ActiveMQ server.


Then you can go to http://localhost:8161/admin/queues.jsp URL and see your available Queues in PC. Since we have note created any you suppose to see similar page as bellow.




Then you can enter "inbound.queue" as Queue Name and then clieck Create button. after it successfully created queue you could be able to see the newly created ActiveMQ queue "inbound.queue" as show in bellow.





Test the functionality

We can test the functionality by sending new message in to "" queue as mentioned follows. First go to ActiveMQ web console(you need to provide login details) Then click on send To link inline with your created queue.

Click Send To link as show on figure 

Then past following structured xml in message box as show in below figure.


<Person>   <name>nirmal</name>   <city>Seatle</city>   <country>USA</country></Person>





Then click on the send button. Now you can check the database and you should be able to see persist person data as show below.


Database Person table after executing above command




You can download the entire source code from following GIT hub URL


Monday, December 23, 2019

SpringBoot with ActiveMQ

In this post I will demonstrate how to configure Spring Boot application with ActiveMQ message broker with SQLServer integrated. So in this sample project I will read a message from ActiveMQ queue and then process that message by saving in to SQLServer databse.

I will use following initial setup project which you can access from following location. This is just base configurations for SpringBoot application with SQLServer integration. Make sure you have reconfigure you PC with pre requirements.


Prerequisites 
  1. You should have install java 1.8 or above.
  2. You should have Eclipse installed in your PC.
  3. Your PC should setup Maven installed and configured.
  4. Your SQLServer need to have user who have access to the configured database and user should able to log in to the database by user name/password. (Make sure that TCP/IP port configured for default ports)


First of all lets add the required dependencies in to the POM file. Following five dependency needed to add in between <dependencies> tags

        <dependency>        
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
 <dependency>
     <groupId>com.microsoft.sqlserver</groupId>
     <artifactId>mssql-jdbc</artifactId>
     <version>6.1.0.jre8</version>
 </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
  
<dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-broker</artifactId> </dependency>
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>


Configure SpringBoot with SQLServer in JPA


First lets update the database properties in spring boot property file. you have to update following parts on the properties file.


spring.datasource.url=jdbc:sqlserver://localhost;databaseName=TestDB
spring.datasource.username=nirmal
spring.datasource.password=Test123_
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto = create-drop


Then lets create JPA model  for our table. Note that in this example I'm using same model for the JSON structure as well.
 I will create Table in following structure.

package com.blogspot.nirmal.springboot;
import net.minidev.json.annotate.JsonIgnore;
import javax.persistence.*;
@Entity@Table(name="RECEIVING_MSG")
public class ReceivingMsg {

    @Id    @GeneratedValue(strategy=GenerationType.AUTO)
    @JsonIgnore    private long id;    @Column(name = "NAME")
    private String name;    @Column(name = "EMAIL")
    private String email;    @Column(name = "AGE")
    private int age;    @Column(name = "IS_DEV")
    private boolean isDeveloper;

    public long getId() {
        return id;    }

    public void setId(long id) {
        this.id = id;    }

    public String getName() {
        return name;    }

    public void setName(String name) {
        this.name = name;    }

    public String getEmail() {
        return email;    }

    public void setEmail(String email) {
        this.email = email;    }

    public int getAge() {
        return age;    }

    public void setAge(int age) {
        this.age = age;    }

    public boolean isDeveloper() {
        return isDeveloper;    }

    public void setDeveloper(boolean developer) {
        isDeveloper = developer;    }

    @Override    public String toString() {
        return "ReceivingMsg{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                ", isDeveloper=" + isDeveloper +
                '}';    }
}

Here I will use auto generated ID as primary key of the table and it will be ignored in JSON structure.

Then I'll create basic DAO for this model.

package com.blogspot.nirmal.springboot.dao;
import com.blogspot.nirmal.springboot.ReceivingMsg;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository;
@Repositorypublic interface IReceivingMsgDao extends JpaRepository<ReceivingMsg, Long> {
    ReceivingMsg findByName(String name);
}

Here I have added interface method wich automatically mapped to retrieve Messages from name.


Configure SpringBoot with ActiveMQ 

First of all lets add the configuration details as bellow. Update the ActiveMQ details section on the properties file.


spring.datasource.url=jdbc:sqlserver://localhost;databaseName=TestDB
spring.datasource.username=nirmalspring.datasource.password=Test123_
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto = create-drop

#ActiveMQ properties
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin




Lets Add ActiveMQ Listener   

We can add the listener class in to our application in following manner.


package com.blogspot.nirmal.springboot;
import com.blogspot.nirmal.springboot.dao.IReceivingMsgDao;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.*;
import org.springframework.messaging.handler.annotation.*;
import org.springframework.stereotype.Component;
import javax.jms.*;import java.util.Map;
@Componentpublic class AmqListener {

    @Autowired    IReceivingMsgDao iReceivingMsgDao;
    @JmsListener(destination = "inbound.queue")
    public void receiveMessage(final Message jsonMessage) throws JMSException {
        String messageData = null;        
        System.out.println("Received message " + jsonMessage);        
        String response = null;        
     if(jsonMessage instanceof TextMessage) {
        TextMessage textMessage = (TextMessage)jsonMessage;
        messageData = textMessage.getText();
        ReceivingMsg msg = new Gson().fromJson(messageData, ReceivingMsg.class);
        System.out.println(msg);            
        iReceivingMsgDao.save(msg);        }
    }
}


Here is the most of important annotation used in the class related to ActiceMQ

@JmsListener(destination = "inbound.queue") :   This will make our listener method to listen to provided queue in destination parameter.

Other than that we used @Autowired annotation to inject our Dao and used it to save the message receiving on Active MQ.

Lets Update Application main class 

Then at last lets update our Application main class as follows. In There we used @EnableJms will make enable the Java Message Services in our application.


package com.blogspot.nirmal.springboot;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.context.annotation.ComponentScan;import org.springframework.data.jpa.repository.config.EnableJpaRepositories;import org.springframework.jms.annotation.EnableJms;
@ComponentScan({ "com.blogspot.nirmal.springboot" })
@EnableJpaRepositories("com.blogspot.nirmal.springboot.dao")
@SpringBootApplication(scanBasePackages = { "com.blogspot.nirmal.springboot" })
@EnableJms
public class Application {
   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);   }
}


Lets run our application


In order to demonstrate this we need to have ActiveMQ server run in our local PC. First lets download it from official web page in following location. Then extract it in to your local PC and then go to apache-activemq-5.15.11\bin\win64 location from extraction parent directory. Then run the activemq.bat to start our ActiveMQ server.


Then you can go to http://localhost:8161/admin/queues.jsp URL and see your available Queues in PC. Since we have note created any you suppose to see similar page as bellow.




and after it successfully started you can update above page and could see the newly created ActiveMQ queue "inbound.queue" as show in bellow.


Then lets run our application as on Maven using following command

mvn spring-boot:run

Then lets send some sample message in to our queue in order to test whether our application reading that message from queue and saving the message details in to the database. click on the "Send To" link as show in Blue circle. Then you can see interface similar to following.



As show in above screen past following JSON structure in message body and clieck on send button.


 "name":"AZX",
  "email":"sample.yahoo.com",
  "age":"12",
  "isDeveloper":"true"
}

Then in the loading page you could see similar to following screen. In There you could see number of messages in Message Enqueued and Message Dequeued. Since we just only send once you could only see one there if you send more messages it will increased.



Then lets see whether our application read that queue and save that message in to the database. Following figure shows the logs related to that message and at the end you could see it mentioning inserting record in to table.


Then lets verify it from Database by querying the table


As you can see it has successfully saved in to the database.
We have successully implemented our application and full source code can be access on following GITHub location.

Friday, December 9, 2016

Red Hat JBoss FUSE ActiveMQ simple example

In this post I'm going to show how to develop simple ActiveMQ queue producer and consumer. Then I will explain step by step guide to deploy it to the JBoss FUSE server. If you do not have JBoss Fuse setup in your local PC go through in my previous blog post related to setup the JBoss Fuse. While I'm learning the stuff it gave me little bit frustration due to the lack of resources to learn this technology as a beginner. Then I though to put it as blog post so in future any one can refer the guide line.

Prerequisites 
  1. You should have install java 1.8 to support latest jboss-fuse-6.3.0
  2. You should have install JBoss Developer studio
  3. Your PC should setup Maven installed and configured.

01) Setup the ActiveMQ queue in FUSE.

First we have to start the fuse server using fuse.bat in the "bin" folder inside the installation directory on Fuse. (In my previous post I have explain how to setup the Fuse server correctly. If you need to setup go through previous post before you continue)



Once it successfully started you can see similar interface to above figure. Then you have to type following command to configure the fabric.

fabric:create
Then you can see similar figure to below.



 Then go to yellow colored link "http://localhost:8181"(which showed in above figure) it will automatically redirect to "http://localhost:8181/hawtio/login". Then provide the user name and password which you should set when you setup the Fuse. 




Then Fuse will create queue for you and you can see generated queue under queue tag as show in below figure.



Now we have created the queue we need to demonstration. Then type following command on the Fuse command interface to get the ActiveMQ URI.

fabric:cluster-list
 Then you will see similar output to below.




Then you need to select the default URI related to root (Since our queue setup under root)

tcp://DESKTOP-3KNHDOV:61617

02) Develop Camel application to send data to ActiveMQ queue and read them in FUSE.

Then go to Eclipse with Fuse integration and go to File -> New -> Fuse Integration Project. Then provide name for the project. I'll provided it as "DemoActiveMq"  then click next and select the JBoss Fuse run-time environment then click next. Next Interface select Start with empty project and Spring DSL as show on below figure.


Then Go to the POM.xml file and update following two tags as show on below.

<groupId>com.amq.demo</groupId>
<artifactId>amq</artifactId>
These two will important when install the build jar in to Fuse if you use different names you may need to change the command according to your change names in installing the jar to Fuse server.

Remove the content inside the <beans> tag and add following content in to that.

<camelContext id="_camelContext1" xmlns="http://camel.apache.org/schema/spring">
        <route id="amq_test">
            <from id="_from1" uri="activemq:queue:DemoQueue"/>
            <log id="_log1" message="${body}"/>
            <log id="_log2" message="Finished"/>
        </route>
        <route id="_route1">
            <from id="_from2" uri="file:///c:/work/activemq"/>
            <to id="_to1" uri="activemq:queue:DemoQueue"/>
        </route>
    </camelContext>
    <bean class="org.apache.activemq.camel.component.ActiveMQComponent" id="activemq">
        <property name="brokerURL" value="tcp://DESKTOP-3KNHDOV:61617"/>
        <property name="userName" value="admin"/>
        <property name="password" value="admin"/>

    </bean>


Note that brokerURL is the URL which we retrieved previous stage and password is the password setup in Fuse server.  Final camel context will be similar to below.

<?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        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
    <camelContext id="_camelContext1" xmlns="http://camel.apache.org/schema/spring">
        <route id="amq_test">
            <from id="_from1" uri="activemq:queue:DemoQueue"/>
            <log id="_log1" message="${body}"/>
            <log id="_log2" message="Finished"/>
        </route>
        <route id="_route1">
            <from id="_from2" uri="file:///c:/work/activemq"/>
            <to id="_to1" uri="activemq:queue:DemoQueue"/>
        </route>
    </camelContext>
    <bean class="org.apache.activemq.camel.component.ActiveMQComponent" id="activemq">
        <property name="brokerURL" value="tcp://DESKTOP-3KNHDOV:61617"/>
        <property name="userName" value="admin"/>
        <property name="password" value="admin"/>
    </bean>

</beans>

Then go to the project folder and give the following command to build and install the project as usual Fuse integration projects.


mvn clean install
Then you should receive similar output to below.



Then go to the Fuse command line and enter following command to install the build jar in to Fuse server. (Please note that this is based on the names I have updated in the pom.xml)


osgi:install -s mvn:com.amq.demo/amq/1.0.0-SNAPSHOT

After successful installation if you log in to the "http://localhost:8181/hawtio/" then you will be able to notice that new section added under our queue in UI. refer the below fegure.



Now we can check the flow by dropping txt file in to "C:\work\activemq" location with some sample content. I'll added below content in to the text file and drop the file in to folder.

<a>
<name>Nirmal</name>
<country>Sri Lanka</country>

</a>

Then you can see the following output as expected. 


We have completed our first ActiveMQ demo. You can access the project code on following github location.