stringapache-cameljavabeansmessage-body

Apache Camel trims off apostrophes from String message body


import static java.lang.System.out;

import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

class RequestReplyMessageSample {

    class Replier {

        String reply( final String /*Message*/ /*Exchange*/ request ) {
            out.println( "\n[ERROR] Expected: 'Re'quest', Actual: " + request
                    + "  <-- Am I doing somethig wrong, is this a bug or a feature?\n" );
            return String.format( "**** Replying to %s ****%n", request/*.getMessage()*/ /*.getBody( String.class )*/ );
        }
    } // Replier

    private static final DefaultCamelContext cc = new DefaultCamelContext();

    public static void main( final String... args ) throws Exception {

        final Replier replier = new RequestReplyMessageSample().new Replier();

        cc.setName( "Request Reply Sample" );
        cc.addRoutes( new RouteBuilder() {

            @Override
            public void configure() {

                from( "timer:start?repeatCount=1" )
                        .setExchangePattern( ExchangePattern.InOut )
                        .process().message( m -> m.setBody( "'Re'quest'" ) ) // EIP Request
                        .process().message( m -> print( "Request", m ) )
                        .log( "Requesting..." )
                        .log( "Replying..." )
                        // How to get Message (or Exchange) as argument in here?
                        .bean( replier, "reply(${body})" ) // EIP Requestor/Replier
                        .process().message( m -> print( "Reply", m ) ) // EIP Reply (in the body of the Message)
                        .setId( "Request/Reply" );
            }
        } );
        cc.start();
        Thread.sleep( 2000 );
        cc.stop();
        cc.close();
    } // main()

    static void print( final String endpoint, final Message m ) {

        out.printf( "%s %s: %s%n", endpoint, m, m.getBody() );
    } // print()

} // RequestReplyMessageSample

Output

...
Request Message: 'Re'quest'
[ple) thread #1 - timer://start] Request/Reply                  INFO  Requesting...
[ple) thread #1 - timer://start] Request/Reply                  INFO  Replying...

[ERROR] Expected: 'Re'quest', Actual: Re'quest  <-- Am I doing somethig wrong, is this a bug or a feature?

Reply Message: **** Replying to Re'quest ****
...

Solution

  • It's a feature. In this case, the single quotes at the start/end of the expression are interpreted as a string literal start/end. You need to add another single quote to let the parser see it as character (i.e. m.setBody("''Re'quest''")).