Apache Camel - Spring

Though Apache Camel come with lot of examples , when I was totally new to Camel I found it a bit difficult to follow. I couldn't find a simple example to get me started in google as well. Here is a simple Camel-Spring example.


Before we start, 


What is Camel?
Apache Camel is an Open Source Integration Framework based on known Enterprise Integration Patterns


Need for Camel,


For Integrating Systems , you have few options like,


Option 1, Develop a custom solution. This Works & Fastest for small use cases
Option 2, Use Integration framework.


Cons,

  • Framework do the heavy lifting
  • Focus on business problem
  • Not "reinventing the wheel“

Option 3, Enterprise Service Bus. But ESB's are more than a integration framework, many uses may not need that complexity.


Since you are here, I assume , you have decided to go with Option 2. Camel won't disaapoint you. Now Let's get our hands dirty,


What all you need?


1. apache-activemq , Download here
2. apache-camel


What are we trying to do?


Very simple scenario, I need to read from a message queue and save the message to file. [You may never face such a use case but, good enough to explain the concepts]




(Step 1) Set Java Home and the Java path
(Step 2) Set Up Your Queue



  • Unzip apache-activemq
  • For windows, go to apache-activemq-5.5.1\bin\win32
  • Run activemq.bat
  • Once the mq is started, go to http://localhost:8161/
  • On the home page, click on Manage ActiveMQ broker
  • One the page opened you will find a link "Queues", Clictk on "Queues"
  • Give a name, say IN_QUEUE, for your queue in the text box. Click "Create"

Now you test message queue is ready.


Before we go further, there are few things in Camel, you should know,


Camel consists of a CamelContext which contains a collection of Component instances.


Components are the extension point in Camel to add connectivity to other systems. Endpoint where the message comes in or leaves the integration layer. Acts rather like a URI or URL in a web application or a Destination in a JMS system; you can communicate with an endpoint "c:/tmp", you could use URIs like "jms:aQueue" and "file:c:\tmp .


Processors are used to manipulate and mediate messages in between Endpoints. The Processor interface is used to implement consumers of message exchanges or to implement a Message Translator.


To wire Processors and Endpoints together, Camel defines a DSL Camel provides Java DSL, Spring XML, Scala etc.


We trying implement this use case with Camle Spring support.


So we leave few things to Spring like create the Camel Context, Define your Compoent.Now in this use case we have two Component, a JMS component and File Component.


Step 3 [As precondition, you need to create the Java Project in you IDE and add required the jar files to the build path]




(a) Create spring-demo.xml






(b) Create a class which extends RouteBuilder, This is where you configure your 'Route'. Route connects Components through the Endpoints. Routes are defined using DSL. Here we use Java DSL


@Override
public void configure() throws Exception {
from("jms:queue:IN_QUEUE").
to("file://D:/Work/My Workspace/Camel/springout");
}




The code says get message 'from' IN_QUEUE and transfer 'to' a file. Now how do you test this code ?


For that you need some one to put messages to your IN_QUEUE. Let's write one the Camel way. I created another xml , to create a new Camel Context. Basically I wanted the client to be used else where.


Here is my client-spring.xml






This is my Client code,






Now for the test,


First run the server or the class which extends RoutBuilder


java -duration 60s -fa /META-INF/spring/spring-demo.xml


This will keep the server live and keep looking for messages.Now just run the Client code to put the message.You should see the file created in the out put folder.

Evolving Architecture ...

Recently I heard some one using the term 'Evolving Architecture'...

I'm wondering how much an architecture can 'evolve'. If architecture can evolve, then how much 'architecture' should be there in the beginning ?

During the days of water fall projects , we had the fully signed off (no really though ;o) ) architecture before we start anything. But now in the days of iterative development , this may not the be case.

So should we allow the architecture to 'evolve' or create a full blown architecture before we start ?

I think it should be some where in between !!!

There are some decisions we should not defer, till we run into problems..

Identify the architecturally significant pieces and create structure and strong foundation for those in the beginning..

If you are deferring something for later..be sure you are aware of the consequences..

Any thoughts ?

Huh!! ..I'm not needed anymore

Yes I'm talking about the role of a 'architect'.

Most of the projects after few iterations/releases I start to feel I’m unnecessary in that project. I used to get frustrated and always been in ‘confused’ state.

But now a days I start thinking like, maybe there is nothing wrong to be in that state of being ‘unnecessary’ in a project.

Doesn’t that indicate I had done might have done my job well ? Had laid out the foundation for the development team to build the structure. Has defined the process/standards/check lists for them.

Project managers are at ease now. I had developed healthy relationship with the team members and communicated the concepts well enough and they don’t need me anymore.

So being ‘unnecessary’ in a team can be a good thing at times.

Any thoughts ? :o)

Video Preview Portlet-Liferay Alfresco Integration

Video Preview Portlet can be implemented in couple of ways.

In my scenario, I had to pull the video content from Alfresco and show the preview inside a portlet.

Kept it simple using
JQueryMedia Plug-in.

Steps

1. Copy the JQuery Media Plugin scripts to your web application or if you have a theme, then to the theme folder.

2. Include scripts in the jsp page or the velocity template (in case of Portlet theme)

3. Add the below code in jsp

<script type="text/javascript">
$(function() {

$('a.media').media();

});

</script>

4. To show the video preview add

<a class="media {width:480, height:280}" href=" <YOUR URL HERE >" >VIDEO </a >

Inside href, you need to give the URL for the video. To get the URL need to use the Alfresco API.

Based on the file tye (the JQuery checks for extension) the library will embed the plug-in for the player in the web page.

Ex, if its wmv it will embed Windows Media Player, for flv , flash player, mov ,Qucik time (if available on your browser, else it will ask to download)

Spring SimpleMappingExceptionResolver to log stack trace

SimpleMappingExceptionResolver is generally used to redirect to an error page. It can be extended to log the trace to a log file.

public class LoggingExceptionResolver extends SimpleMappingExceptionResolver {

private static Log log = LogFactory.getLog(LoggingExceptionResolver.class);

public LoggingExceptionResolver() {
super();
}

@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
log.debug(getStackTrace(ex));
return super.resolveException(request, response, handler, ex);
}

/**
* @param t , Throwable
* @return String of the exception
*/
public String getStackTrace(Throwable t) {
StringWriter stringWritter = new StringWriter();
PrintWriter printWritter = new PrintWriter(stringWritter, true);
t.printStackTrace(printWritter);
printWritter.flush();
stringWritter.flush();
return stringWritter.toString();
}
}

Configure this bean,
< bean id="exceptionResolver" class="com.common.service.LoggingExceptionResolver"
>
</bean >

Binary Data Over REST Web Service

There was requiremnet to retrieve images from a Content Management System and render the content to a portlet deployed in Liferay.

The application was built on top of Spring MVC portlet and the Service calls from Portlet was REST API calls. So the REST WS API was made to return a byte[] of the content

To sent binary data in REST call [senting binary over REST WS may be questioned], you should encode using sun.misc.BASE64Encoder and on the receiving end you can use sun.misc.BASE64Decoder to decode the data.

The code looks like this

Service API

@RequestMapping(value = "/cms/image", method = RequestMethod.GET)
public void (ModelMap modelMap){
byte[] buff= getBytes(); // Return the byte[] of the image
String
imgaeArray= new sun.misc.BASE64Encoder().encode(buff);
modelMap.addAttribute("result", imgaeArray);
}

At Portlet end;

@Autowired
RESTRepository repository;

@RequestMapping(params = "action=preview")
public String preview(Model model, RenderRequest renderRequest,RenderResponse renderResponse) {
Map <String, Object> paramMap = new HashMap
<String, Object>();
Map
<String, String> map = repository.get("/cms/image", Map.class,paramMap);
byte []
imgaeArray= new sun.misc.BASE64Decoder().decodeBuffer(map.get("result"));

}

If you don't know the content type, then you may need to return a DTO in the REST API instead of just encoded
byte[] . DTO can have the properties to hold the byte[] and the content type.

Performance Tuning

During what stage of the development cycle we start performance tuning? How much time are we spending to tune application that’s in Production or in UAT?

One comment I heard from even from a Enterprise Architect was, “I know those are important, but my boss says get me the functionality first, other “lities” can come later”. The “lities” include scalability, maintainability etc and performance as well.

I like to politely disagree to him. But this is what most the project goes through. Due to business compulsions or time lines we build the system and later spend sleepless nights in fixing the performance bottle necks.

In most of the Enterprise Java application development performance tuning starts late in the development cycle. We start worrying about performance in the UAT phase or even after production when performance becomes critical.

Performance is as important as any functionality we build. Why are we not investing time on the early stages of development?

Tuning an application; most people sees it only as SQL Query tuning. I agree that is important, but that is not all. Tuning is required in design, presentation layer, and UI components as well. Even some incorrect business requirement could lead to performance bottle necks.

In one of the project the database returned result is 1 minute but the screen rendering took 10 minutes for huge record sets. The issue was with a JSF UI component which displayed the result in table format and due to a wrong Java script implementation in that page. When component rendering was changed from the conventional <table>,<tr>,<td> to <div><span> the results were still encouraging.

What I suggest is performance tuning or performance; engineering track should cut across all stages of development life cycle from Functional Specification, Design, and Coding. As we progress in building system we should go back often tune where ever required. Make sure the application is tested with quality and quantity data.

Early Alarm makes life easy. Performance tuning; “Start Early, Do it regularly!!!”