Tuesday, October 6, 2009

Enabling BPEL into JBoss : Welcome to the Riftsaw Project

The objective of Riftsaw Project is to bring BPEL capabilities for JBoss Application Server. This project is build on top of Apache ODE, basically adding some features for JBoss App Severs as which will allow either JBoss ESB (Community based) and in the future JBoss SOA Platform(Enterprise SLA) to support BPEL out-of-the-box.


Another "Opensource" BPEL alternative


If anybody tell you that BPEL is an easy language to create the processes manually and if you believe, you are ready to believe in any tale! I tell you it because this is a kind of technology that you really need a graphical tool/designer.


The JBoss Community has adopted for many years the Eclipse to deliver JBoss Tools and now this set of plugins made by JBoss Team is already integrated with Eclipse BPEL Designer. This is a cool plugin and you will really need this feature into your Eclipse, otherwise create any simple BPEL process will be a really boring task.

Nevertheless we support BPEL Designer in JBoss Tools. You are able to use the NetBeans BPEL Desginer which is another really cool opensource alternative. I did some personal researching over BPEL support in NetBeans and it was a real good experience. For certain moments I thought that Eclipse could incorporate some ideas from NetBeans designer as well.

I recommend you install the JBoss Tool's 3.1.0.M3 plugins into your Eclipse 3.5 (Galileo). It will add the BPEL support into your Eclipse as well as the capacity to deploy the process besides editing the WSDLs visually. For more information about this see this link: https://www.jboss.org/tools/download/dev.html

Once you are aware that you really need a designer tool, let's try share with you some good information before you dive into BPEL Development; first of all there are certain resources and concepts that would make BPEL easier for every human. These are the following:
  • WSDL
  • XPath
  • XSLT
  • XML Schema
If you have a good background over those items above, BPEL will be incredibly easier for you, otherwise, I recommend you attend the "Webservices online training", this is one of the training offered in JavaPassion Website. In this training, you will have some good brief introductions about everything you need to be a BPEL Rock Star.

I've been listen many many times companies complaining about SOA Adoption independently of the technology vendor a very common problem is what I call: "The gap between processes and the bussiness components". This is the moment where your company spent thousands of US$ to discovery the company's processes. So many Six Sigma guys came to you company and told you everything that your company is doing wrong and **designed some proposals using BPMN** or any other notation of "How the company could/must work". At this moment you can see a huge interrogation in front of you while you are trying to figure out which glue you will use to put your processes working with your legacy COBOL, Java, .Net and a bunch of WebServices representations of these legacy components, have you think about that before?

BPEL could help you in 30% to 40% to solve these kind of problems. Once BPEL aims you think in "Composite Applications" which in general are many compositions of different services (keep in mind that it can be not only WebServices).


This technology is perfect when you must execute several services according some conditions or even some rules. BPEL allows you think in "Services Orchestration" at the same way you think when you are creating Swing UI using some graphical designer.

The RiftSaw/Apache ODE is an implementation of WS-BPEL 2.0 which is the newest specification definied by OASIS of the standard BPEL4WS (Business Process Execution Language for Web Services) 1.0 and 1.1. Red Hat counts with one contributor for this spec: Alejandro GuĂ­zar (JBoss, by Red Hat).

Thinking about Processes

I married about 1 year and I can still remember my wedding process. Several people were involved. A lot of parallel tasks, a lot of dependent tasks, timeouts, authorizations, rules etc! Now try imagining everything into a flow keeping in mind how you would organize your plans to get married and keep in mind that you have a lot of expecations, and everything must be perfect on time, saving costs and allowing everybody to be happy... Well, this is exactly what processes are trying to solve and provide to the companies globally speaking!


A Process is composed by a Sequence of many activities and those different activities can to perform particular actions, but always promoting a collaborating among them. Let's see some examples of this:

Getting Married Process -> Propose the Lady -> Request Parent's Authorization -> Organize the Party -> Invite People -> Organize Honey Moon -> Organize Bachelor Party -> Say Yes!


If everything in the sequence flow is true, congratulations, you will have a good chance to celebrate a nice wedding! Although a process must handle when something that you are not expecting to happen, for instance: "Bachelor Party denied", and than you might try several different actions, flows or even new sequences for it. :)

WS-BPEL 2.0 spec describes a process, the sequence, the activities that are part of , the faults, the exceptions, the alternative paths and everything you need to create a process.

Using JBoss technologies for BPEL

When we are working with BPEL, basically the majority of Tools generates a .bpel file, this is a XML File that describes the process itself. A BPEL Process represents several interations with a bunch of Webservices, then if the BPEL can invoke several WebServices, makes sense if the way to invoke a BPEL process execution would a WebService as well, for this reason each .bpel file, or process, will have a WSDL that will represent the Client invocation, as well as the response that will send after the process flow.

A BPEL Process is a sequence of activities inside some sequence, exactly as I said before, you may represent it graphically(IDEs) or programatically (XML), the following table will show the 2 action's categories :












Basic
Activities

Structured
Activities



  • invoke

  • receive

  • reply

  • assign

  • compensate

  • compensateScope

  • empty

  • exit

  • throw

  • rethrow

  • validate

  • wait





  • flow

  • forEach

  • if

  • pick

  • repeatUntil

  • scope

  • while






These activities are represented in the BPEL Palette, as you can see in the following image:

This is a simple blog entry, so it would be impossible describe BPEL in depth here. So I recommend you read some books and deeper BPEL Articles if you need more background on this technology. it will make you understand this entry much better.

Creating your first BPEL Project using JBoss Tools, RiftSaw and JBoss App Server 5.1

First of all you must have in your machine the following software:

* Eclipse 3.5 + JBoss Tools 3.1.0M3
* JBoss 5.1.0 GA
* JBoss Riftsaw M1

Installing Riftsaw

This came from README.txt:

The build.xml script in this directory is responsible for deploying the BPEL runtime and deployer to the JBoss AS,and the BPEL/ESB examples to the JBossESB environment.

1) Install JBoss5.1.0.GA and JBossESB4.6.GA, and follow the JBossESB instructions for installing it into JBossAS

2) Update the deployment.properties file to set the path to each of this installations

3) Run "ant deploy" to install the BPEL deployer and engine into the JBossAS

4) Start the JBossAS server

At this point, you can try out the examples in the RiftSaw/samples folder.

Alternatively, if you want to try out the BPEL/ESB examples, then:

6) Run "ant deploy-esb-examples" to copy the ESB/BPEL examples into the JBossESB samples.

7) Follow the $JBossESB/samples/quickstarts/webservice_esb_bpel instructions to run the example

One thing that you may ask yourself:

a) Why the Riftsaw is installed both in AppServer and the ESB Server ?
- Hide quoted text -

A: In my point of view you may think into a "process repository" or something like other vendors loves to call : "A process server", so the BPEL processes will be running into an exclusiv (or clustered or load balanced) instance of a JBoss AppServer, which will host the Riftsaw Engine, as well as the WSDLs that represents the processes.

In another hand you have the other part of your SOA solution, in that case in particular I am talking about an ESB! At this moment, JBoss ESB can host services that may put several BPEL processes to work together, for each BPEL Process you will have an 1-1 relation with a WSDL, once you will access a BPEL process of the same way you acess a regular WebService: Through an WSDL.

Depending of what you wanna do in terms of Orchestration you may count just with BPEL, however keep in mind that you will be limited into WSDL boundary, so if you need different protocols collaborating with each other

Now I will save your time! it's time to watch this tutorial to get some basics of BPEL Development using JBoss Tools + Riftsaw, click here to watch!

If you prefer, you may watch it here:

JBoss Riftsaw - Getting Started Tutorial from Edgar Silva on Vimeo.



Why is it useful? It shows how you can edit the WSDL that acts as the endpoint for the BPEL process, and also shows how you can create the Service, Ports, Bind for this WebService.

Thursday, September 17, 2009

Screencast: Making JBoss ESB listen XMPP Protocol using Smack API

This simple screen-cast will show you how JBoss ESB can listen XMPP messages.

For this solution, I used Openfire+Smack API + JBoss ESB + Pidggin (could be any Gtalk client, Adium or so on):



I hope you enjoy, forgive my accent ( easl - English as Second Language) and see how you can add new capabilities into JBoss ESB

Any comment, doubt or questions, feel you free to reach me at edgar.silva (at) redhat.com

Wednesday, July 29, 2009

Would you like to hear about JON's success cases as well as a curious accent at JBossWorld 2009?

This September is very special for me, my wife and my dad will be celebrating their birthday this month, and the third motivation for happiness is the fact to be speaking at JBossWorld, and sharing some thoughts and our experiences with everybody there.



This JBossWorld 2009, you will have chance to watch a presentation of some success cases of JBoss Operations Network (JON) in Brazil, and also notice how some customers obtained very valuable benefits from this product.

The presentation title is: The "bossanova-way": JBoss management with JON in Brazil - Real case studies and applications of JBoss Operations Network , you may ask: "wth...does Bossanova mean in this context?".
Well, I'm gonna tell you the inspiration behind this title, Bossanova is a brazilian style of music very well known internationally speaking, I have seen many docus on TV saying that bossanova is a very appreciated and recognized as a sophisticated form of entertainment in the US. However, many of my american friends, have no idea that it comes from Brazil...
I am not sure if you like Frank Sinatra, but he is one of the persons that fell in love by this music style?



Perhaps you are very used to hearing good stuff about Brazil such as soccer, samba, beaches....and ok...Ladies.... but many people don't realize that Red Hat brought JBoss business to Brazil 3 years ago, and we could make JON a "defacto" solution for majority of the JBoss Enterprise's subscription buyers.


And our secret...our secret was somewhat based on bossanova, as far as we tried to be: "Simple, however sophisticated", helping people understand the value and benefits that JON can bring to the companies that are using JBoss in an enterprise environment.

In this presentation, we will show some testimonial of customers, as well as some technical demos and simulation of the key features that were mandatory for running and support JBoss in a very enterprise level. Yep...We will have deep demos, besides a rare accent.

Well, I hope to see you there, in the end I am sure that you will see the power of JON in very large interesting applications and scenarios in the country where Brazilian Portuguese is spoken :)

Wednesday, June 10, 2009

JBoss AOP in a Real World scenario

See the following statement:

" Tell me what is happening between your Application Server and your Database"


AOP is not something really new, besides you can use AOP for many real scenarios nowadays, like the proposed above, so, lets do it.
Installing JBoss AOP distro in your JBoss AppServer

Download the latest JBoss AOP binary, unzip this in your hard disk, in the jboss-aop folder, you have 2 options for updating, one for JBoss 4.x and other for 5.x.
  • /jboss-aop-2.1.1.GA/jboss-40-install/jboss-aop-jdk50.deployer or
  • /jboss-aop-2.1.1.GA/jboss-50-install/jboss-aop-jdk50.deployer
Both contains a build.properties, which you must edit it and inform the following properties:
  • jboss.home= put here your App Server directory home
  • jboss.config= put here the profile which you will update the AOP capabilities (eg: aop)
In your shell, in the appropriated deployer installer dir, you will call the "ant " command, it will update your JBoss Profile.
Enabling AOP in your JBoss Profile

In your profile, in the folder $jboss_home/$profile/deploy/jboss-aop-jdk50.deployer/META-INF, you will edit the file jboss-service.xml , will change the EnableLoadtimeWeaving attribute to true, according the following image:

After you change the AOP service, you must copy to the bin directory of your JBoss, the jar file called pluggable-instrumentor.jar that is in the lib folder of your JBoss AOP home directory.

The last step, you must add the following parameter in the JAVA_OPTS in the run.conf file:

-javaagent:pluggable-instrumentor.jar

Done, your AOP is updated in your JBoss AppServer.

Intecepting every JDBC Call made from your AppServer

JBoss AOP is an AOP Framework, which combined with AppServer make this kind of task really easy, where once you have a .aop file, it is a "deployable" file, that JBoss will deploy and make our aspects live in the App Server.

We will create a simple Interceptor, which is a simple class that implements org.jboss.aop.advice.Interceptor , that everything we need, is present , see the following source code:

public class JDBCMetricInterceptor implements Inteceptor {

public JDBCMetricInterceptor() {

}

public Object invoke(Invocation invocation) throws Throwable {

StringBuilder builder = new StringBuilder();
try {
builder.append("\n\t============== JDBC CALL ===============");


if (invocation instanceof MethodInvocation) {
MethodInvocation mi = (MethodInvocation) invocation;
builder.append("\n\ttype: Method Invocation");
builder.append("\n\tmethod: " + mi.getMethod().getName());

Object[] args = mi.getArguments();

if (null != args && args.length > 0) {

builder.append(String.format("\n\tHey, I saw %s parameter(s)",
args.length));
for (Object object : args) {
builder.append(String.format(
"\n\tParameters sent: %s of %s",   object,  (null==object)? "Null parameter": object.getClass().getName()));

}

}


}

return invocation.invokeNext();
} finally {
builder.append("\n\tJDBC Invocation end");
builder.append("\n\t========================================");
logger.info(builder.toString());
}
}

}



First of all, you might think: "We can intercept the java.sql.Statement class... and that's all", but JBoss AOP can't do that with "Java Standard Classes". So we will define a "definition" that our target will be: "Every class inside the package of the HSQLDB driver , which is org.hsqldb.jdbc, besides these classes must implement the class java.sql.Connection, which we assume that will execute the SQL to the database", right? See the code of the jboss-aop.xml file:



*(..))">




Once you deploy the generated aop file, when you boot the AppServer, you will see the AOP logging our messages:

Ofcourse, create anything with JBoss AOP is easier when we have in Brazilian office some help from Flavia Rainone, thanks Flavia.

Have fun with AOP, and keep in mind that you may use that in many real scenarios, is not necessary to be so geek for find out some opportunity to use it.

Thursday, April 2, 2009

Smooks+JBoss ESB applied : Getting Quotes from YahooFinance

I've been doing some researching for creating a cool sample using CEP into JBoss, while I am still working on it, I decided put a simple sample using Smooks for transforming CSVs from Yahoo Finance into XMLs, which is a format much easier for integrating with everything else.

Getting Stock Symbols and Quotes from Yahoo Finance in CSV Format


Yahoo offers an URL that gives you information about the quotes, it is not a WebServices, "REST Service" or nothing especial or too complex, it is basically an HTTP URL, that you may pass some additional info, and you can see the Quotes information by a glimpse into a CSV output. Look the following URL format:

http://finance.yahoo.com/d/quotes.csv?s= a BUNCH of STOCK SYMBOLS separated by "+" &f=a bunch of special tags

These special tags you can get more information here

I decided use this URL: http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT+ORCL+JAVA&f=snb3pt1d1 , and what does these parameters means?

a) s= The symbols, in that case: Red Hat, Microsoft, Oracle and Sun Microsystems.

b) f= It means which information I wanna in my "report", I decided put:
  • s = symbol s - symbol
  • n- companyName
  • b- bid
  • 3p - last bid
  • t1 - time
  • d1 - TradeDate
The result will give me the following information:

[java] "RHT","RED HAT INC",17.90,17.68,"4:04pm","4/2/2009"
[java] "MSFT","Microsoft Corpora",19.33,19.31,"4:00pm","4/2/2009"
[java] "ORCL","Oracle Corporatio",18.83,18.58,"4:00pm","4/2/2009"
[java] "JAVA","Sun Microsystems,",8.38,8.00,"4:00pm","4/2/2009"

Time to make it available into my JBoss ESB.

Using Smooks

The only thing that I am doing for testing is send the data obtained from the Yahoo URL to my Service JMS Quee Gateway, you may use Commons Http Client if you want something more sophisticated, othewise you may create a simple code as you can see in the following code-listing:


public static void main(String args[]) throws Exception
{
SendJMSMessage sm = new SendJMSMessage();
sm.setupConnection();
StringBuilder quotesData = new StringBuilder();
try {
// Create a URL for the desired page
URL url = new URL("http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT+ORCL+JAVA&f=snb3pt1d1");

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {

quotesData.append(str + "\n");


}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

System.out.println("Sending:\n" + quotesData.toString());
sm.sendAMessage(quotesData.toString());
sm.stop();

}





This is a basic JMS client (use the quickstarts as a template).

Now, the only I thing I have to do is configure my smooks-res.xml file as well as my "Smooks Actions" in jboss-esb.xml, in the following image, you can see on the left side the jboss-esb.xml and smooks-res:


The only thing I had done was editing some XML, and everything is ready.

This is one more practical example of JBoss ESB and its transformation engine.

Download the solution

You can download the solution from here

Tuesday, February 24, 2009

A Simple RestEasy Maven Archetype

I've been looking for better and faster ways to develop some of my solutions, while Gradle is quite promising in my opinion, I still prefer Apache Maven for collaborative projects, even Ant sounds good when you can predict any scenario for your application/project.

I had searching a lot about a RestEasy Archetype, but I haven't found. RestEasy is a project which Maven is strongly used, although I am not sure if I did my search properly, but just in case I create a simple RestEasy Archetype, which you can download from here.

Once you have Maven installed and configured, you just will unzip this zip file, and will type mvn install. You will see the following results into your console:

[INFO] [jar:jar]
[INFO] [install:install]
[INFO] Installing /Users/edgarsilva/redhat/dev/NetBeansProjects/resteasy-archetype/target/resteasy-archetype-1.0-SNAPSHOT.jar to /Users/edgarsilva/.m2/repository/org/jboss/resteasy/resteasy-archetype/1.0-SNAPSHOT/resteasy-archetype-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Wed Feb 25 04:26:00 BRT 2009
[INFO] Final Memory: 9M/16M
[INFO] ------------------------------------------------------------------------
edgar-silvas-macbook:resteasy-archetype edgarsilva$


Now, you are ready to create RestEasy projects using Maven Archetypes, to do that, you can use your preferred IDE or just can type in the console for instance, the following command:

mvn archetype:create -DarchetypeVersion=1.0-SNAPSHOT -Darchetype.interactive=false -DgroupId=sample -DarchetypeArtifactId=resteasy-archetype -Dversion=1.0-SNAPSHOT -DarchetypeGroupId=org.jboss.resteasy -DartifactId=sample

This command, will create a project called "sample" which contains everything you need for developing and deploying RestEasy Applications into JBoss Application Server.

In the following image, you can see the project opened using NetBeans:


If you run mvn:install you will see Maven in action downloading everything required for building your project. In addition, this archetype includes JBoss AppServer tasks, which you can use for deploying, starting or stooping the server anytime you want. After typing mvn install, this goal will compile and generated a war file into target folder, however you may call the command mvn jboss:start that you will see the following output:

[jsilva@jsilva esresteasy]$ mvn jboss:start
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'jboss'.
[INFO] artifact org.codehaus.mojo:jboss-maven-plugin: checking for updates from central
[INFO] ------------------------------------------------------------------------
[INFO] Building esresteasy
[INFO] task-segment: [jboss:start]
[INFO] ------------------------------------------------------------------------
[INFO] [jboss:start]
[INFO] Starting JBoss...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Wed Feb 25 16:30:56 BRT 2009
[INFO] Final Memory: 3M/74M
[INFO] ------------------------------------------------------------------------
[jsilva@jsilva esresteasy]$


Not only starting JBoss AppServer, you are also able to deploy your application using the command: mvn jboss:deploy :

[jsilva@jsilva esresteasy]$ mvn jboss:deploy
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'jboss'.
[INFO] ------------------------------------------------------------------------
[INFO] Building esresteasy
[INFO] task-segment: [jboss:deploy]
[INFO] ------------------------------------------------------------------------
[INFO] [jboss:deploy]
[INFO] Deploying /opt/java/workspace/esresteasy/target/esresteasy.war to JBoss.
[INFO] No server specified for authentication - using defaults
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Wed Feb 25 16:39:41 BRT 2009
[INFO] Final Memory: 3M/74M
[INFO] ------------------------------------------------------------------------



If you look the JBossApp Server console you can see your project deployed into JBoss:

16:39:39,812 INFO [TomcatDeployment] deploy, ctxPath=/esresteasy, vfsUrl=
16:39:39,930 ERROR [STDERR] 52 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider DataSourceProvider
16:39:39,935 ERROR [STDERR] 57 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider DefaultTextPlain
16:39:39,936 ERROR [STDERR] 58 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.StringTextStar
16:39:39,937 ERROR [STDERR] 59 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.InputStreamProvider
16:39:39,939 ERROR [STDERR] 61 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.ByteArrayProvider
16:39:39,941 ERROR [STDERR] 63 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider
16:39:39,942 ERROR [STDERR] 64 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider
16:39:39,944 ERROR [STDERR] 66 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.StreamingOutputProvider
16:39:39,950 ERROR [STDERR] 72 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.providers - Adding built in provider org.jboss.resteasy.plugins.providers.IIOImageProvider
16:39:40,084 ERROR [STDERR] 206 [http-127.0.0.1-8080-1] INFO org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - Adding scanned resource: esresteasy.Hello
16:39:40,087 INFO [STDOUT] FOUND JAX-RS resource: esresteasy.Hello



I am looking for an easy way to pass information of some users inputs to fill some information into my pom.xml, the same strategy used in seam-gen for instance and also in esb-gen, but I am still looking for how to do that.

Seems that Maven Archetype is changing or moving for a next generation (http://docs.codehaus.org/display/MAVEN/ArchetypeNG) , hopefully the actual archetypes are still working fine.

Friday, February 13, 2009

Combining ApacheCamel+BSF to make JBoss ESB polyglot

Some time ago I published here one of the ways I built for integrating services such as Apache Camel into JBoss ESB.

Hopefully Tom Fennelly (JBoss ESB CoreDev) also published an awesome documentation in how create new Listeners into JBoss via Schedulers, as I had done, in addition showing how do that using Groovy, which in my opinion is much better, safer and easier, I will show you the new implementation here right now.

When do I need new Listener into JBoss ESB?


Many many times I faced situations where some customers have unpredictable scenarios related with integration, that's why I liked Apache Camel since the first moment I had contact with! You can find out a clear and easy programming model(using DSLs), and a very nice set of components for integrating even with some providers not available in JBoss, like JBI(ServiceMix), Esper(CEP/ESP) etc.


Groovy in Action into ESB

Once the events in Camel happens into an specific RouteBuilder object, I just want to make it available as a "Service", so once JBoss ESB is running, the Camel is ready to answer any event.

To make it possible, I just created a classes called ApacheCamelListener, where I must fill some life-cycle methods, in order to ensure that everything will be executed properly in runtime, see the class: ApacheCamelListener.java:



package org.jboss.soa.esb.integration.apache.camel;

import java.io.File;
import java.util.logging.Logger;

import org.apache.bsf.BSFEngine;
import org.apache.bsf.BSFManager;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.jboss.soa.esb.ConfigurationException;
import org.jboss.soa.esb.helpers.ConfigTree;
import org.jboss.soa.esb.listeners.message.ActionProcessingPipeline;
import org.jboss.soa.esb.util.FileUtil;

public class ApacheCamelListener {

private ActionProcessingPipeline pipeline;

protected CamelContext context = new DefaultCamelContext();

protected Logger log;

protected boolean started = false;

public ApacheCamelListener() {
log = Logger.getLogger(ApacheCamelListener.class.getName());
}

public void start(ConfigTree config) throws ConfigurationException {
// Create and initialize the pipeline..
pipeline = new ActionProcessingPipeline(config);
pipeline.initialise();
log.info("Initilizing ApacheCamel into JBoss Esb Server ....");
if (!started) {
CamelContext context = new DefaultCamelContext();

try {

log.info("...Adding Routes");

File scriptsDir = new File((config.getAttribute("scripts-folder")));

File[] scripts = scriptsDir.listFiles();

if (null != scripts && scripts.length>0) {

String theScript = null;

JBossEsbRoute router = null;

BSFManager manager = new BSFManager();

BSFEngine bsfEngine = manager.loadScriptingEngine(config.getAttribute("script-language"));

for (File file : scripts) {

theScript = FileUtil.readTextFile(file);

router = (JBossEsbRoute) bsfEngine.eval(config.getAttribute("script-language"), 0, 0, theScript);

log.info(router.toString());

context.addRoutes(new ScriptingRoute(router));

}

}

} catch (Exception e) {

e.printStackTrace();

}

try {
context.start();
started = true;
log.info("Camel is ready and waiting events");

} catch (Exception e) {

e.printStackTrace();
}
}

}

public void stop() {
try {

started = false;

try {
context.stop();

} catch (Exception e) {

log.info("Error trying close Camel Context: " + e.getMessage());
}

} finally {
if (pipeline != null) {
pipeline.destroy();
}
}
}

}

Time for Innovating : Putting Ruby, Groovy and other scripting language to dispatch messages to existing Services

You can use JBoss jBPM Actions to call deployed Services, based in the service name, service category and the variables, so what I did is basically is allow users via Camel listen many others components and call an existing Service, the following image can describe my idea:


Basically when I configure my ApacheCamelListener, I can configure the "scripts-folder" and "script-language" properties for my listener, these propertis basically works to tell where in the filesystem this listener will looking for "other dinamic listeners", and then you can tell the orign of the event, and when some message/even happens in the provider, it will be forwarded via ServiceInvoker converting a Camel Message to an ESB Message Aware. See the Listener configuration:




Or you can simply see the jboss-esb.xml configuration here:



Now, I can use a Ruby Script to invoke some service from my ESB Server, and using a IRC room to interact with JBoss ESB.


require 'java'
include_class 'org.jboss.soa.esb.integration.apache.camel.JBossEsbRoute'
route = JBossEsbRoute.new
route.from = 'irc:localhost:667#room1'
route.to = 'irc:localhost:667#room2'
route.serviceCategory= 'Transformadores'
route.serviceName = 'TransformaChamadaXMLparaISO'
return route




In Apache Camel, I must pass a org.apache.camel.builder.RouteBuilder, to say how interact with the message arrived in the configured protocol. To do that, I extended this class for a JBossEsbRoute, as you can see in the following code-listing:



package org.jboss.soa.esb.integration.apache.camel;

public class JBossEsbRoute {

private String serviceName;
private String serviceCategory;
private String from;
private String to;


public JBossEsbRoute() {
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return String.format("This ServiceInvoker will listen events from %s " +
"and will forward to Service %s from category %s and route to %s",
this.from,this.serviceName,this.serviceCategory, this.to);
}

public JBossEsbRoute(String serviceName, String category, String from, String to) {

this.serviceName = serviceName;
this.serviceCategory = category;
this.from = from;
this.to = to;
}


Here is my extension for Camel understands any script written in PHP, ruby or perl etc, and make it integrated with JBoss ESB:



package org.jboss.soa.esb.integration.apache.camel;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class ScriptingRoute extends org.apache.camel.builder.RouteBuilder {

protected JBossEsbRoute route;

public ScriptingRoute() {
// TODO Auto-generated constructor stub
}

public ScriptingRoute(JBossEsbRoute r) {

this.route = r;

}


@Override
public void configure() throws Exception {

from(route.getFrom()).process(
new Processor() {
public void process(Exchange e) {

Object message = e.getIn().getBody();

System.out.println("#########" +
e.getContext().getExchangeConverter().convertTo(String.class, e));


System.out.println("Received event: " + message);


}
}).to(route.getTo());


}



The Ruby Script, basically creates a new Instance of JBossEsbRoute, which I can use to register a new Event Listener as well as a Invoker for an existing Services hosted into JBoss ESB. The following code-listing will allow you figure out how it is done:




String theScript = null;

JBossEsbRoute router = null;

BSFManager manager = new BSFManager();

BSFEngine bsfEngine = manager.loadScriptingEngine(config.getAttribute("script-language"));

for (File file : scripts) {

theScript = FileUtil.readTextFile(file);

router = (JBossEsbRoute) bsfEngine.eval(config.getAttribute("script-language"), 0, 0, theScript);

log.info(router.toString());

context.addRoutes(new ScriptingRoute(router));

}

}


Now, any language supported by Bean Scripting Framework can be used to invoke services into JBoss ESB, using Apache Camel for Events notifying and even forwarding after get processed into JBoss ESB pipelines.

I will be updating the sources and publishing in GitHub, if you are interested in that idea, reach me via email into edgarsilva (using) gmail.com.

Hope you enjoy!

ps- JBoss Esb 4.5 with Embedded Console is really great!