Simple Camel REST Example – Temperature Converter

Screen Shot 2013-07-24 at 11.53.52 PM

In the Freenode java channel ##java someone mentioned their next goal was to learn REST by writing a service to convert between Celsius and Fahrenheit. I mentioned how simple that’d be with the right tool (Camel of course) and wrote the example.

First step was so generate a project using one of the Maven Camel archetypes. In this case I chose the Java DSL archetype camel-archetype-java.

(Note, you can just type mvn archetype:generate  and the plugin will let you interactively build the above. No need to remember all that!)

For this example I decided to use the Restlet component as well as the Groovy component to do the actual calculation embedded in the route. So I had to add both of those dependencies to my pom.xml.

I deleted the example data directory since we won’t be needing it or the sample data the archetype includes.

Then I edited replacing the sample route with two simple routes one for F and one for C. Using the Restlet component I specified the address the service would use including {degree} as the input. I then told Restlet to only respond to HTTP GET requests. Then it was just a matter of grabbing the input and running the calculation putting the result in the body of the message.

I chose Groovy but I could’ve used any of the scripting languages integrated into the Camel  DSLs.  EL, Groovy, JavaScript, JoSQL, JXPath, MVEL, OGNL, PHP, Python, Ruby and XPath. Additionally, any JSR -223 scripting language could have been used using the generic DSL methods.

To run the example just use mvn exec:java . Test using your browser or curl.

Completely over simplified example but it shows the power of Camel and it’s ability to hide the plumbing details from a large number of protocols and applications, allowing you to focus on your business logic instead. Full working example is on GitHub.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Comments on this entry are closed.