Skip to main content

Red Hat JBoss Fuse - Integrating Database, Java Bean and Restful Services in EAP, XML route with JNDI

We have talked about how to start develop application in EAP without the need of Spring or CDI libraries. And in this post we are going to take that example a bit more further, show you how to integrate with Databases, Java beans in the application, creating a servlet and lastly setup a Restful webservice. We have a choice of using simple or JNDI registry, and I choose the JNDI, you will see why in a minute. If you would like to know how to do it in Java DSL with CDI or Spring XML, please go to this blogpost.

For this currency exchange project, I have store the exchange rate in the h2 database. What we are going to do is to display the entire exchange rate on the webpage provided by a restful web service and provide a servlet that takes in the amount of money and the currency to exchange to, send them back to server, calculated and return the result. So here are the things I am going to do
  • Database
  • Java Bean
  • Servlet
  • Restful Web Services

Database
Of course we want to use the datasources in EAP. So first thing first, create the datasource in EAP. Make sure you started the JBoss EAP. Go to Configuration, select Connector and then to datasources.

  • Name :MyCamelDS
  • JNDI Name: java:jboss/datasources/MyCamelDS


 Select the Driver we are going to use, and it's h2 this case,

Enter the

  • Connection URL: jdbc:h2:file:~/h2/fuseoneap;AUTO_SERVER=TRUE
  • Username: sa
  • Password: 


Change the min and max pool size to 1 and 10. And then enable the MyCamelDS datasource.


Once we get the datasource ready, we can then use it by looking in our Route XML in the SQL component, the reason why we don't need any other work, is because we uses JNDI for Camel Registry, therefore it has the ability to lookup the datasource JNDI registry straight away.

  <route id="allcurrencies">
    <from uri="direct:getCurrencies"/>
    <log message="starting direct:getCurrencies"/>
    <to uri="sql:select * from currencyexchange?dataSource=java:jboss/datasources/MyCamelDS"/>
    <marshal>
      <json library="Jackson"/>
    </marshal>

  </route>


Java Bean
For Java bean it is a bit more tricky, create a Java class that has a method takes in amount of money and currency to exchange first.

  public class CurrencyConvertor {
    public double convertUSD(double amt, ArrayList<Map<String, Object>> data){
      Double rate = (Double)data.get(0).get("rate");
      return amt*rate;
    }
 }

And then we need to figure out a way to register this CurrencyConvertor Bean in the JNDI Registry. Here we need a CamelContextLifecycle, it will define a lifecycle which could help to setup the registry. Create a Java Class that implements CamelContextLifecycle<JndiRegistry> and override the method needed.

You can now play do things in following event during the lifetime of the Camel context.
  • afterAddRoutes
  • afterStart
  • afterStop
  • beforeAddRoutes
  • beforeStart
  • beforeStop
We want register the bean before the Camel context starts, so int beforeStart method, bind the java bean into JNDI registry.

package com.redhat.demo02;

import org.apache.camel.component.servletlistener.CamelContextLifecycle;
import org.apache.camel.component.servletlistener.ServletCamelContext;
import org.apache.camel.impl.JndiRegistry;

public class MyCamelLifeCycle implements CamelContextLifecycle<JndiRegistry>{
  @Override
  public void afterAddRoutes
  (ServletCamelContext camelContext, JndiRegistry registry) throws Exception {}
  @Override
  public void afterStart
  (ServletCamelContext camelContext, JndiRegistry registry) throws Exception {}
  @Override
  public void afterStop
  (ServletCamelContext camelContext, JndiRegistry registry) throws Exception {}
  @Override
  public void beforeAddRoutes
  (ServletCamelContext camelContext, JndiRegistry registry) throws Exception {}
  @Override
  public void beforeStop
  (ServletCamelContext camelContext, JndiRegistry registry) throws Exception {}
  
  @Override
  public void beforeStart(ServletCamelContext camelContext, JndiRegistry registry) throws Exception {
     CurrencyConvertor currencyConvertor = new CurrencyConvertor();
     registry.bind("currencyconvertor",currencyConvertor);
  }

}

In web.xml add the Lifecycle class you just created.
  <context-param>
    <param-name>CamelContextLifecycle</param-name>
    <param-value>com.redhat.demo02.MyCamelLifeCycle</param-value>

  </context-param>

And then you will be able to call the bind bean using the Bean Component. 

  <route id="covertcurrency">
    <from uri="direct:getCurrency"/>
    <log message="Got currency: ${headers.amt} and amt${headers.currency}"/>
    <choice>
      <when>
        <header>currency</header>
        <to uri="sql:select * from currencyexchange where currencycode= :#currency ?dataSource=MyCamelDS"/>
        <log message="exchange rate ====&gt; ${body[0][rate]}"/>
        <bean ref="currencyconvertor" method="convertUSD(${headers.amt},${body})"/>
      </when>
      <otherwise>
        <log message="nothing to lookup"/>
        <transform>
          <constant>nothing to lookup</constant>
        </transform>
      </otherwise>
    </choice>
  </route>

  

Servlet
We need to setup the Servlet, under webapp, create the WEB-INF/web.xml file. Right click on Deployment Descriptor and choose Generate Deployment Descriptor Stub. It will create an empty web.xml file for you.

Add the servlet setting in the web.xml and publish it 

  <servlet>
    <servlet-name>camel</servlet-name>
    <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>camel</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>

Once it's done, we can then use the Servlet component in Camel, it will publish a servlet endpoint through the Servlet we set earlier.

  <route id="servletCurrencies">
    <from uri="servlet:/currencies?servletName=camel&amp;matchOnUriPrefix=true"/>
    <to uri="direct:getCurrencies"/>
  </route>

Restful Web Service
The Restful web services needs to have the CamelHttpTransportServlet setup too, since we have already done that in Servlet, all we have to do is to builds Rest endpoints as consumers in Rest DSL. And then configure it to servlet.

    <restConfiguration component="servlet" bindingMode="json" contextPath="/camel">
      <dataFormatProperty key="prettyPrint" value="true"/>
    </restConfiguration>
    <rest path="/currenciesrest">
      <get uri="/">
        <to uri="direct:getCurrencies"/>
      </get>
    </rest> 

That's all you have to do. You can find the entire project code here.

Comments

Rick said…
Thank you very much for this nice article, Christina!

The link leading to the source code seems to be inoperative. Could we please have that?
Unknown said…
This is great thank you. But for some reason in most of your articles where you write "...you can find the code here..." there's no link.

Christina Lin said…
https://github.com/jbossdemocentral/jboss-fuse-oneap
Eric Ramirez said…
Hi Christina,
Thank you for your work, it is a very clear introduction to Fuse. I was reading more about Karaf and saw that it is not a JEE container and therefore JTA is optional. To me this is a barrier because I want to be able to combine routes and handle/roll back transactions within my camel routes. Does this make sense, am I missing something?

Popular posts from this blog

Red Hat JBoss Fuse/A-MQ - Fuse and A-MQ Version 6.3 GA is released!

Fuse and A-MQ 6.3 GA has just went out. Maybe, you would think this is just only a minor version release why should I care? Hold your thoughts on that! Because they have done a lot of improvements and also added many new features into this release.

Besides various bug fixes and making sure Fuse Fabric is much more stable. There are two major change in this version update:

New Tooling in JBoss Developer Studio (JBDS) 9.1 GA. Newer Apache Camel version – Camel v2.17. I was really impressed by the work put in to make developing Camel application much simpler. First is the installation of tooling itself. Now it has a all-in-one installer so you don't need to worry about which plugins you need to check. See the videos below to see the new "Getting Started" of Fuse 6.3.



And If you notice from the above video, the presentation of camel route in JBDS has also updated. It fixed some of the miss representation of logic and making it easier to read.

Old Camel Route
New Camel Route
On …

Fuse Integration Service - Setup JBDS and create first quickstart application

Before we go and start creating our first application, I want to show you how to setup your JBoss Developer Studio, create a small application from the quickstart example and then running it on Fuse Integration Service.

I am using JBoss Developer Studio version 9, you can find it here.
After download the

jboss-devstudio-9.0.0.GA-installer-eap.jar
double-click it, and start installing with default values.

After successful installation, we will need install the plugins for Fuse, on JBoss Central view, select software update, select enable early access.


And select JBoss Fuse Development for the plugin,


Click on install, and we are all set to go!

First thing first, we want to create a Fuse project to deploy on the base of Fuse Integration Service, which is OpenShift. If you have not installed it, please go back to my previous post for instructions. So on your JBDS, right click and start creating the project. Select new, maven project, if you have installed the plugin correctly, you should …

Red Hat JBoss Fuse - Getting Started with Fuse Integration Service 2.0 Tech preview

I just realized that I did not do a getting started for Fuse Integration Service 2.0 Tech preview before I did the pipeline demo, thanks for those of you who reminded me! :)

To get started with FIS 2.0, for people who has just getting to know the technology, here is how I interpret it. Basically, it's divide into two aspect,

1. Integration development, FIS uses Apache Camel as the core technology that creates, orchestrate, compose microservices into a super lightweight thin integration layer, and become the API provider and service orchestrator through exposing RESTful or messaging service endpoints. And you can choose to either package and run it with Spring-Boot or Karaf.


2. Application Deployment and Management, FIS takes advantages of OpenShift platform, and allows you to separately deploy the micro-integration service among distributed environment, at the same time takes care of the failover, high availability, load balancing and service lookup problem for you.


So, now we know …