Camel: How to increment the value of an Integer header by a set amount

I don't see where you are increasing your integer header by 50 in your code [NOTE: Question was edited afterwards]. You just seem to be parsing a String into an Integer. You can simplify it by leveraging type conversions:

Message in = ex.getIn();
in.setHeader("offset", in.getHeader("offset", Integer.class));

If you want to increment the offset header by 50, you can do it inside your route with the help of OGNL (no need to resort to a Processor, like the other answer suggested), and by converting the header first to an Integer:

from("direct:hello")
    .setHeader("offset", header("offset").convertTo(Integer.class))
    .setHeader("offset").ognl("request.headers.offset + 50");

I am using such processor for this:

public class IncrementIntProcessor implements Processor {
    private String headerName;
    private int delta = 1;

    public IncrementIntProcessor(String headerName){
        this.headerName = headerName;
    }

    public IncrementIntProcessor(String headerName, int delta){
        this.headerName = headerName;
        this.delta = delta;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        int num = (exchange.getIn().getHeader(headerName)==null ? 0 : exchange.getIn().getHeader(headerName, Integer.class));
        exchange.getIn().setHeader(headerName, (num+delta));
    }
}

Example:

            ....
            .process(new IncrementIntProcessor("intHeader", 50))
            .log(LoggingLevel.INFO, "${header.intHeader}")
            ....

Interesting to see other, simple solutions.

Tags:

Apache Camel