Camel development series 14

Hello and welcome to yet another Camel development series. In this post I will describe how to use some basic Camel concepts together with Telegram chat bot and accessing a REST API to receive chat messages. You can customize this for many use causes for push/pull type of apps. Finally I will show how you can deploy this non-web app to Heroku and see the result.

Basic flow

The basic flow of the app is as follows:

  1. On startup it calls a REST API found at which is the swedish government’s lottery site. They have a REST API where you can access various lotteries, draws and results.
  2. The app first calls an endpoint to get the draws for this week.
  3. It then retrieves the draw number for Saturday and Wednesday draw.
  4. It calls another endpoint and receives the actual lottery numbers for the draws for those days.
  5. It then pushes out a friendly message to a Telegram chat bot.

Now off course, you can add additional features such as sending commands and getting more data and even returning random numbers to suggest for playing the lottery.

First the code

You can find all the code here . I will not got through code in detail such most Camel users should be familiar with it since it is pretty standard Camel functionality.

Maven setup

To get our app to deploy to Heroku we need to be able to run our pom file with the package command. To to do that we need to assemble our app and this can be done using the appassembler-maven-plugin. Simply add the plugin below and change the parts to your project. Pay attention to the CamelWorker which is specified under target. This will be used by Heroku when starting our worker process.


Heroku setup

Now we come to the Heroku setup. Let’s follow these setups.

1. Create an account at Heroku.

2. Download the Heroku cli and install it.

3. Before proceeding ensure that your folder structure is allows:


That is, don’t have a long folder structure leading to your pom file. This is because Heroku looks at the root folder for the pom.xml, and the Procfile. If your repo is not structured like this rearrange it before proceeding.

4. Verify by opening a cmd and type ”heroku” in the command prompt. You should receive a prompt to login. Enter your credentials to login.  Afterwards next time just typing heroku should display the following:


5. Then it is time to create your heroku app. In the command prompt heroku apps:create :

heroku apps:create svenskalotto
Creating svenskalotto… done |

The link above should the remote git repo that you need to add to your remote link in your local git repository. I called mine heroku. Ensure that if you type git remote -v, the ”heroku” remote is shown with the link to your app repo.

5. Now in order for our app to work in Heroku a couple things are needed. Heroku by default works with webapps where you have some website to show. Our Camel app is java standalone app. We instead need to use a Heroku worker process rather than a webapp process. This is so that Heroku understands that our app is a ”backend” app. For more on this look into Heroku processes. We also need to specify the jdk to use, add jvm arguments to ignore ssl certification validations and create an environment variable to store our API access key.

6. Heroku requires two files, a file and a Procfile. Create both of them and put them in the root folder of your repo. You can look at my repo to see what values I used. Essentially the file tells Heroku how to run our app and parameters to use when running it. Procfile contains the type of worker to use on the Dyno.

7. Once you have added the two files remember to push to your repo.

8. Now it is time to push to your heroku repo. In your cmd  at your project folder type:

git push heroku master

You should now see heroku push your code and building the app as can been here:

Finally the build process finishes as seen here:

If the app did not start immediately you can view the logs using:

heroku logs


heroku logs:tail

9. Now, our app will start but will crash. Why? Because we have not created an environment variable four access key. Login to our app dashboard. Go to settings. There is a option to show configVars. Click and then a key value input form will appear. Write the name of your environment variable and its value. Ensure you have referred to it in your Camel code. Once you save it the app will restart.

10. If everything works your Telegram bot should show some nice lotto text 😉 For example:


If you have any questions on the code or the setup let me know. Eventually I hope to expand and do a more push based chat.


Camel development series 13

Hello, and welcome to another post regarding development with Camel and all things related to Camel.

Its been far too long since my previous post and although any excuse is a bad excuse but since my previous post I have switched back to consulting and ventured back in the commercial world. The big thing noticeable is off course how far ahead Camel is even of the commercial vendors. Already in 2015 you could dockerize Camel. These days these are either alpha features or just about production ready. More importantly, you can’t just auto-scale as you like as there are complicated licensing agreements to take into consideration. Another different is that commercial vendors have a huge obstacle and that is, it is practically impossible right now to develop true micro-services with them unless you pay loads of cash. With Camel, you just write your app, dockerize it and go. I think if the commercial vendors want to catch up they need to break apart their architecture and make things more modular. If I am writing and REST-API I don’t want  a gazillion other parts connected to the runtime that clogs resources. I think they are moving in this direction but it will be at least some before they are there.

Anyway here I thought I’d show a couple of new features in Camel 2.20 which looks quit cool.

JSON Schema validation

In order to use this component add camel-json-validator to your pom file.
Here is an example RouteBuilder class for you

public class JsonSchemaValidation extends RouteBuilder {
public void configure() throws Exception {


As you can see we grap the json data, we send it to the validator component and specify the schema, and catch any validation error. Pretty easy right?

Health check API

I don’t have any code to show here but it is pretty cool that Camel has started to introduce a health check API. I think that was one of the issues that was missing previously. Once it becomes to easy to check if a CamelContext is available or which routes are up from API then this will do wonders for monitoring.

JSONPath writeasstring

One annoying thing which isn’t Camel related per say was that when you used jsonpath and wanted to get the value of json field it would write it as [”myvalue”] rather than ”myvalue”. Finally there is a writeAsString method to do this for you.

Support for AWS Lambda

In Camel 2.20 there is now direct support for AWS lambda function calls. See more info and examples here

This is pretty cool which means you can use Camel to call your AWS Lambda environment and have mixture of both type of functionality. You could have Camel running in docker on AWS calling your lamda functions!

Camel development series 12

Hello and welcome to another Camel development series. From now on I will paste less code to the blog and instead refer to the github repo where the code is stored. It makes writing the blog easier and that helps to motivate me to write more often.

In this serie I will touch upon a frequent scenario. Our problem is that we want to expose a HTTP endpoint in order to allow the client to perform a HTTP GET operation. We then want to call the backend HTTP(s) and retrieve say a picture and allow this to be displayed via the browser. How can we accomplish this?

Well if you want to jump straight to the code go here:

As you can see we accomplish this in four lines of code. We first expose our undertow endpoint and ensure only HTTP GET operations can be performed.  Then we set the Exchange.HTTP_QUERY header to our query parameter. Finally we call the backend https service using the http4 component. The key here is to enable the parameter bridgeEndpoint=true so that Camel understands it is acting as a proxy and doesn’t mix up the endpoints. Finally we convert the payload to byte and return it to the original client. That’s all!

Camel development series 11

Hello and welcome to another Camel development series.

In this series I thought we’d go through some more hints and some tricks I learned after one year of working with Camel.

Avoid unnecessary object creation

Do not create unnecessary object models of your data. As a java developer you tend to think everything in terms of object. But should you always create objects? The whole point of integration is to remain stateless and act as an interface to transfer data. So I would say, where possible don’t create objects. This has nothing to do with performance since object creation is cheap but more to do with not having to write unnecessary code for an behaviour related functionality. Let us work with an example.

So you receive a json message, you need to do some content-based routing and then generate a SOAP message and send to some web service.

Now you could off course create an object model for the json message or write a bean and the same goes for the SOAP xml. But unless you are dealing with completed message structure or attachments you don’t need to write code that way when it comes to integration. Here is an approach to solve it in another way.


.when(PredicateBuilder.isEqualTo(ExpressionBuilder.languageExpression("jsonpath", "$.data.request"), constant("valueToMatch1")))
        .when(PredicateBuilder.isEqualTo(ExpressionBuilder.languageExpression("jsonpath", "$.data.request"), constant("valueToMatch2")))
  .throwException(IllegalArgumentException.class, "Unknown request command received!")

In the above you can see that I don’t create any objects. I simply use the excellent library of json path or the camel version of it camel-jsonpath and simply perform a lookup in the data and based on that I route to my individual routes. This allows for writing less code, simpler code and I stay within the Camel dsl. It makes it also easy to understand what the integration is doing. I avoid going from one class to another.

Now about creating a SOAP message. Again you could write jaxb code, or use some other xml processing or use CXF or some other framework. But if your SOAP messages are relatively simple and does not contain attachments then you skip all that and use freemarker to inject data into your SOAP message. Here is an example:


Here is my freemarker template file:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soapenv="" xmlns:lan="http://test">

As you can see I extract the data again using json path and insert it in a header. Then I route to a freemarker endpoint. In my freemarker template I have written a simple expression to where the data should be injected. That’s all! I don’t write any xml code or worry about name space creation and stuff like that. Exactly same thing goes for the opposite. You can see xpath to extract data from xml messages and use a template json freemarker template to insert a simple expression.

Creating environment variables in your tests

A lot of the times you need to access environment variables but you don’t want to use real values in your tests but simple some fake value but you don’t want to change your code. You still want to access that same environment variable but just change the value.

I use the excellent library called system-rules by Stefan Birkner. It works really well and is really use to use. If you work with maven add this to your pom


How do you use it?

In your JUNIT test class add the following:

  public final EnvironmentVariables environmentVariables = new EnvironmentVariables();

  public void setUp() throws Exception {
    environmentVariables.set("VAR1", "1");
    environmentVariables.set("VAR2", "2");
    environmentVariables.set("VAR3", "3");

As you can see we add the rule and create a variable of type EnvironmentVariables. Then in your setUp method you simply create the variables and add values. As easy as that!

Testing JSON messages in your route tests

So quit often when you write route tests you will need to check if the json you produce needs to match some expected json. To do complicated JSON matches or even simple ones I simply the excellent library alled jsonassert. Add this to your pom:


To use it:
In your @test method add this:

JSONAssert.assertEquals(expectedResponse, response, false);

There are way more complicated things you can do with JSONAssert but if you want a simple way of comparing json messages this is great.

Camel development series 10

Hello everyone,

Well as usual it has been a long time since I wrote here but I thought a new year has started so a nice and simple update would be good.

This time I will keep it simple and instead show how you can verify json messages against a given schema in your Camel route.

The aim is thus:

Given a json message and a predefined json schema, we want to validate the message against the schema and return the result of the validation.

Camel route

Assuming you have create a Camel route here is how my (very) basic code looks like:

package org.souciance.integration.validate;

import org.apache.camel.builder.RouteBuilder;

import java.nio.charset.Charset;

public class CamelValidateJson extends RouteBuilder {

public void configure() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
String schema = IOUtils.toString(classLoader.getResourceAsStream("jsonvalidate/schema.json"), Charset.defaultCharset());
String json = IOUtils.toString(classLoader.getResourceAsStream("jsonvalidate/data.json"), Charset.defaultCharset());
.setProperty("Schema", constant(schema))
.bean(ValidateJson.class, "isValidJson")
.log("Valid json!")
.log("Invalid json!")

I have kept the steps very simple. The idea is to focus on the schema validation and nothing else so I am manually loading the data and the schema file. You could off course inject the schema path via some variable or some other way.

I then start the route via  timer, again this is to keep it simple.

I then create an exchange property called ”Schema” and insert the schema in it.

Then I call a bean using .bean and as parameters give the bean class and bean method.

The bean will return the result of the validation inside a header.

I use the choice() and when() to log the result.

The bean code looks like this:

package org.souciance.integration.validate;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;
import org.apache.camel.Exchange;


* Created by moeed on 2017-01-15.
public class ValidateJson {
* Method to jsonvalidate some json data based on a json schema
* @throws IOException
* @throws ProcessingException
public static void isValidJson(Exchange exchange) throws IOException, ProcessingException {
final JsonNode data = JsonLoader.fromString(exchange.getIn().getBody().toString());
final JsonNode schema = JsonLoader.fromString(exchange.getProperty("Schema").toString());

final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
JsonValidator validator = factory.getValidator();

ProcessingReport report = validator.validate(schema, data);
if (!report.toString().contains("success")) {
exchange.getIn().setHeader("isValid", false);
else {
exchange.getIn().setHeader("isValid", true);


The method isValidJson is very simple. It receives the exchange. It extracts the json data from the body and the json schema from the exchange property.

Now to the main part. I use the json schema library to do the actually schema validation. If the validation is false I update the exchange header and if it is successful I also update the exchange header.

If you log the output after running it with intentionally bad data for a given a schema you will see something like this: failure
error: object has missing required properties (["age"])
level: "error"
schema: {"loadingURI":"#","pointer":"/items"}
instance: {"pointer":"/7"}
domain: "validation"
keyword: "required"
required: ["_id","about","address","age","balance","company","email","eyeColor","favoriteFruit","friends","greeting","guid","index","isActive","latitude","longitude","name","phone","picture","range","registered","tags"]
missing: ["age"]

As you can see I did not have the property ”age” so the validation failed. With the age property put back in the data the output will simply be ”success”.

This is just simple way of doing json validation in your Camel routes. You can use it whilst doing rest calls or simple file based data manipulation. For more info here is the source code on my github:

Camel development series 9

Welcome again to another post regarding development with the Apache Camel framework. In this series I will cover a couple of different things that I have encountered or developed which may be of benefit to you.

Camel demo project on Github

I have updated my github page at and removed some old projects and added two new ones.


The CamelDemo project contains a larger maven project based on camel-blueprint-archetype version 2.17.0. It consists of a series of routes that aim to show in a very simple manner the basics of some of the most common Camel functionalities. This includes features such as:

  1. Content-based routing
  2. Splitting csv, xml and json data
  3. Rest-dsl
  4. File handling
  5. Timer based routes
  6. Camel unit tests

More features will be added in the near future. But I think it is a pretty good place to start if you are a complete newbie to Camel to just get a feel for the framework and what you can do with very little code. It is indeed a very powerful framework.


This is also a maven project based on Karaf 4.0.2. This is a really cool and powerful feature that I discovered a month or so ago and is extremely powerful when developing micro-services in isolation.

In short what this does is to allow you to build and distribute a Karaf distribution customized to your needs and include all the bundles  you desire on boot level. In practical terms, this means that you tell the maven karaf plugin which bundles/features you are interested in and add them to boot level.

Then you run maven:clean install and the plugin creates a zip and a tar.gz file in the target directory. Choose whichever format you desire. Then all you do is move that distribution to your server or docker image and unzip and run /bin/karaf. Then when Karaf boots up the bundles, including Camel and your Camel routes will already be started.

Take a look at the project for an overview. You should be able to build it and have Camel installed at boot level.

Running Camel for OSGI in Intellij

Normally when I develop a project with Camel I always know I will run it in Karaf. Therefore I start with template based on camel-blueprint-archetype. Before version 2.17.0 I didn’t have to change anything with logging. Just let maven do its magic and add the components I want and develop.

However since version 2.17.0 it seems new features to the archetype have been added. Now when you create a new project based on that archetype and then run the generated project you get this error:

[INFO] --- camel-maven-plugin:2.17.0:run (default-cli) @ email-bibsent ---
[INFO] camel-blueprint detected on classpath
[INFO] OSGi Blueprint XML files detected in directory C:\Work\repo\LSP\integration-platform\integrations\PollEmailFromBibsent\src\main\resources\OSGI-INF\blueprint
[INFO] Using org.apache.camel.test.blueprint.Main to initiate a CamelContext
[INFO] Starting Camel ...
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See for further details.

Essentially Camel won’t start since the sl4j logger is not found. I then found that you can solve this by adding the following dependencies:


But then I thought this can’t be quit right so I posted this question on the Camel nabble forum. The answer I got from Claus Ibsen was that the logger dependency from Camel is not present in that archetype because Karaf or any other OSGI container has its own logger.

What this means is, add those dependencies when you want to run the route in Intellij for testing, but then change the scope to


when you want to deploy them to Karaf or to your maven repository.

Camel development series part 8

In this series I will simply touch upon a few issues I encountered during coding that you might find useful. For reference this is on Camel version 2.17.0.

PollEnrich will not move file after completion

So I had a route where in the middle of the route I had to enrich it with a file, and after consuming the file, and the route finished it should move it to the a specific folder with a timestamp. The route looked like this:


 .pollEnrich().simple("file:" + location + "?fileName=${header.File}&charset=iso-8859-1&" +

We are using simple because we want pollEnrich to evaulate dynamic endpoints from headers. This can be found in the documentation. However, what actually happened was that the pollEnrich created the archive folder and the completely ignore the file expression language and just created a folder with the timestamp. No matter how hard I tried to change it still produced an output similar to this. My intention was to create a folder called archive and in there save the files with a timestamp attached to their name.

The problem was that the ”?move=” part doesn’t evaluate to anything meaningful at the point it’s evaluated. The ”move=” expressions need to be evaluated after the file has been picked up, but they are being evaluated before the file is read.

So my workaround was to replace the pollEnrich with the following:

 ConsumerTemplate consumer = exchange.getContext().createConsumerTemplate();
    String fileName = exchange.getIn().getHeader("File", String.class);
    String fileUri = "file://" + location + "?fileName=" + fileName + "&charset=iso-8859-1&move=archive/${file:name.noext}-${date:now:yyyyMMddHHmmssSSS}.${file:ext}&moveFailed=failed/${file:name.noext}-${date:now:yyyyMMddHHmmssSSS}.${file:ext}";
byte[] fileBody = consumer.receiveBody(fileUri,5000, byte[].class);

The above code resides in a processor. Basically I had to revert to a ConsumerTemplate instead. This works fine, it was just confusing that the pollEnrich didn’t work with dynamic properties.

Building predicates from exchange properties

Exchange properties are very useful when you want to pass properties from one exchange to another. Predicates are very powerful to build rich expressions in order to make to complex statements. These two can then be combined into something as simple as:

    Predicate success = exchangeProperty("Status").isEqualTo("true");
Predicate failure = exchangeProperty("Status").isEqualTo("false");

The code statement is easier to read and you have replaced a complex statement with a simpler one that can be used in the dsl. This is something really cool about Camel.

Splitting large files

Suppose you have a big file that you want to read. Maybe you have millions of rows of CSV data and you want to split them by a certain number or simply one by one.Since each row should be handled the same, you also want things to be done in parallel.

The most performance optimal way can be expressed like this:

.split().tokenize(System.lineSeparator(), 1000).streaming()
//use threading to handle the different split chunks in parallel
.threads(20, 50)

So, what we have done is to split based on a token. In this case it is by the operating system new line token e.g. in windows and in linux world. We also group them such that each split shall contain 1000 rows. Then we do streaming so that lazy parsing is done to save memory and finally we add threads so things can be done in parallel.

Specify exchange pattern and delay

The last two simple tips are for when you want to specify the exchange pattern directly as an endpoint and for introducing a simple delay in ms.

//specify the exhange pattern
//introduce a delay of 100 ms

As you can see we can write .inOnly or .inOut and then provide the endpoint. This can be good if you want to do some processing but don’t want to wait for a response, instead want to send an immediate reply to caller.

The delay is simple, simply add the value and you have your delay!