You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

Sort

Available as of Camel 2.0

Sort can be used to sort a message. Imagine you consume text files and before processing each file you want to be sure the content is sorted.

Sort will by default sort the body using a default comparator that handles numeric values or uses the string representation. You can provide your own comparator, and even an expression to return the value to be sorted. Sort requires the value returned from the expression evaluation is convertible to java.util.List as this is required by the JDK sort operation.

Using from Java DSL

In the route below it will read the file content and tokenize by line breaks so each line can be sorted.

from("file://inbox").sort(body().tokenize("\n")).to("bean:MyServiceBean.processLine");

You can pass in your own comparator as a 2nd argument:

from("file://inbox").sort(body().tokenize("\n"), new MyReverseComparator()).to("bean:MyServiceBean.processLine");

Using from Spring DSL

In the route below it will read the file content and tokenize by line breaks so each line can be sorted.

<route>
  <from uri="file://inbox"/>
  <sort>
    <expression>
      <tokenize token="\n"/>
    </expression>
  </sort>
  <beanRef ref="myServiceBean" method="processLine"/>
</route>

And to use our own comparator we can refer to it as a spring bean:

<route>
  <from uri="file://inbox"/>
  <sort comparatorRef="myReverseComparator">
    <expression>
      <tokenize token="\n"/>
    </expression>
  </sort>
  <beanRef ref="MyServiceBean" method="processLine"/>
</route>

<bean id="myReverseComparator" class="com.mycompany.MyReverseComparator"/>

If you omit the <expression> element, then the body of the message must already be in the form of a list. Besides <tokenize>, you can supply an expression using any language you like, so long as it returns a list.

Using This Pattern

If you would like to use this EIP Pattern then please read the Getting Started, you may also find the Architecture useful particularly the description of Endpoint and URIs. Then you could try out some of the Examples first before trying this pattern out.

  • No labels