Over a million developers have joined DZone.

Integrating Databases and Building RESTful Services in EAP with Fuse and CDI

Developing an app in EAP with a Java DSL? Here's a guide to integrating your database and make RESTful services with CDI and Fuse.

· Integration Zone

Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and dPaaS could cost you down the road. Brought to you in partnership with Liaison Technologies.

We have talked about how to start developing an application in EAP with a Java DSL, and most interestingly how to utilize the CDI framework in JavaEE. And in this post we are going to take that example a bit more further, show you how to integrate with Databases and Java beans in the application, create a servlet, and lastly setup a RESTful webservice.

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.

And there we are, datasource ready!

We can then use the CDI framework to lookup datasource in JNDI. So create a CDI Producer, in CDI, the producer produce an object that can be injected which we are going later inject the datasource into our camel context.

public class DatasourceProducer {
  @Resource(lookup= "java:jboss/datasources/MyCamelDS")
  DataSource dataSource;

  @Produces
  @Named("MyCamelDS")
  public DataSource getDataSource() {
    return dataSource;  
  }
}

You will be surprised on how easy it really is to use it in Camel, because it's done. Now in our RouteBuilder class, we are going select every single exchange rate in the database. We are going to use the SQL component in Camel, provide the SQL, and then provide the datasource name we named in the producer we created. 

Lastly we are going to transform the resultset in JSON format, using the built-in transformation components in Camel.  

  from("direct:getCurrencies").routeId("allcurrencies")
  .to("sql:select * from currencyexchange?dataSource=MyCamelDS")
  .marshal()
  .json(JsonLibrary.Jackson);

That's it!

Java Bean

First thing, create a Java class that has a method takes in amount of money and currency to exchange. And on top of the class, place the @Name annotation, this will allow the bean we created to accessible through the EL. And we can lookup the bean from Camel.

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

To use it in the Camel route, just use the bean components in Camel. 

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

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.

    from("servlet:///currency?servletName=camel&matchOnUriPrefix=true")
  .routeId("servletCurrency")
  .to("direct:getCurrency");

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")
      .contextPath("/camel").port(8080).bindingMode(RestBindingMode.json);

  rest("/currenciesrest")
      .get()
      .produces(MediaType.APPLICATION_JSON)
      .to("direct:getCurrencies"); 

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

Discover the unprecedented possibilities and challenges, created by today’s fast paced data climate and why your current integration solution is not enough, brought to you in partnership with Liaison Technologies.

Topics:
jboss fuse ,integration ,ei ,enterprise integration

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}