יום שישי, 24 במאי 2013

Camel by Code

Very simple camel code :
package org.apache.camel.example.console;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class TestCodeForBlog {

    public static void main(String[] args) {
       try {
            CamelContext context = new DefaultCamelContext();
           
            context.addRoutes(new RouteBuilder() {
                    public void configure() {
                        from("stream:in?promptMessage=Enter something please :").to("stream:out");
                    }            
            });
            context.start();
            Thread.sleep(334000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
The code creates a Camel context object add a simple route that  transfer data from stdin to stdout .
Routes action is starting by calling the start  action of  the camel context.
Sleep command is used to block the main thread termination and allow the camel route to take its actions.

Add filter :
package org.apache.camel.example.console;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

class MyPredicate implements Predicate
{
    @Override
    public boolean matches(Exchange pExchange) {
        String theBodyText = (String) pExchange.getIn().getBody();
       
        if ( theBodyText.contains("Zvika"))
        {
            return true;
        }   
        return false;
    }   
}

public class TestCodeForBlog {
    public static void main(String[] args) {
          try {
            CamelContext context = new DefaultCamelContext();
           
            context.addRoutes(new RouteBuilder() {
       
            public void configure() {
   
                from("stream:in?promptMessage=Enter something please :").
                filter(new MyPredicate()).
                    to("stream:out");
            }
            
            });
            context.start();
           Thread.sleep(334000);
           System.out.print("I'm out");
            
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
}

The result:
Enter something please :moshe
Enter something please :Zvika
Zvika
Enter something please :Test4

The example add to the route a filter in order to filter out all the messages that are not confirm to its predicate.
The predicate is a class that's implements the Predicate interface.it overrides the match method that examine the exchange and return Boolean value indicates if the filter pass  

אין תגובות:

הוסף רשומת תגובה