Java Code Examples for org.apache.camel.builder.RouteBuilder

The following are top voted examples for showing how to use org.apache.camel.builder.RouteBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: syndesis   File: FunctionTest.java   View source code 7 votes vote down vote up
protected RouteBuilder createSyndesisRouteBuilder() {
    return new SyndesisRouteBuilder("") {
        @Override
        protected SyndesisModel loadModel() throws Exception {
            SyndesisModel syndesis = new SyndesisModel();
            syndesis.createFlow()
                .addStep(new Endpoint("direct:extension"))
                .addStep(new Function()
                    .name(MyExtension.class.getName())
                    .property("message", "hello"))
                .addStep(new Endpoint("direct:a/b"));

            return syndesis;
        }
    };
}
 
Example 2
Project: drinkwater-java   File: RouteBuilders.java   View source code 6 votes vote down vote up
public static RoutesBuilder mapBeanRoutes(ServiceRepository serviceRepository,
                                          Service service) {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            List<Method> methods = javaslang.collection.List.of(service.getConfiguration().getServiceClass().getDeclaredMethods());

            // create an instance of the bean
            Object beanToUse = service.getConfiguration().getTargetBean();

            for (Method m : methods) {
                if (Modifier.isPublic(m.getModifiers())) {
                    from("direct:" + formatBeanMethodRoute(m))
                            .bean(beanToUse, formatBeanEndpointRoute(m), true);
                }
            }
        }
    };
}
 
Example 3
Project: drinkwater-java   File: RouteBuilders.java   View source code 6 votes vote down vote up
public static RouteBuilder mapBeanClassRoutes(DrinkWaterApplication app, Service service) {

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                List<Method> methods = javaslang.collection.List.of(service.getConfiguration().getServiceClass().getDeclaredMethods());

                // create an instance of the bean
                Object beanToUse = BeanFactory.createBeanClass(app, service.getConfiguration(), service);

                for (Method m : methods) {
                    if (Modifier.isPublic(m.getModifiers())) {
                        RouteDefinition def = from("direct:" + formatBeanMethodRoute(m));
                        def = addMethodInvokedStartTrace(service, def, Operation.of(m));
                        def.bean(beanToUse, formatBeanEndpointRoute(m), true);
                        addMethodInvokedEndTrace(service, def);

                    }
                }
            }
        };
    }
 
Example 4
Project: syndesis   File: __extension-name__Extension.java   View source code 6 votes vote down vote up
@Bean
@SyndesisExtensionAction(
    id = "my-step",
    name = "My Step",
    description = "A simple step",
    entrypoint = "direct:my-step"
)
public RouteBuilder myAction() {
    return new RouteBuilder() {
        @Override
        public void configure() {
            from("direct:my-step")
                .log("Body is: ${body}");
        }
    };
}
 
Example 5
Project: syndesis   File: ExtensionTest.java   View source code 6 votes vote down vote up
protected RouteBuilder createSyndesisRouteBuilder() {
    return new SyndesisRouteBuilder("") {
        @Override
        protected SyndesisModel loadModel() throws Exception {
            SyndesisModel syndesis = new SyndesisModel();
            syndesis.createFlow()
                .addStep(new Endpoint("direct:extension"))
                .addStep(new Extension()
                    .name(MyExtension.class.getName())
                    .property("message", "hello"))
                .addStep(new Endpoint("direct:a/b"));

            return syndesis;
        }
    };
}
 
Example 6
Project: sponge   File: SpringConfiguration.java   View source code 6 votes vote down vote up
/**
 * Camel routes that use the engine as a consumer (directly or indirectly).
 *
 * @return route builder.
 */
@Bean
public RouteBuilder consumerRoute() {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            // @formatter:off
            from("sponge:camelRssEngine").routeId("spongeConsumer")
                    .log("Received Camel message: ${body}");

            from("direct:log").routeId("directLog")
                    .log("${body}");
            // @formatter:on
        }
    };
}
 
Example 7
Project: sponge   File: CamelProducerCustomUriActionTest.java   View source code 6 votes vote down vote up
@Bean
@Override
public RouteBuilder route() {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            // @formatter:off
            from("direct:start").routeId("spongeProducer")
                    .to("sponge:spongeEngine?action=CustomAction&managed=false")
                    .log("Action result as a body: ${body}")
                    .to("direct:log");

            from("direct:log").routeId("directLog")
                    .log("Action result as a body: ${body}");
            // @formatter:on
        }
    };
}
 
Example 8
Project: sponge   File: CamelManyConsumersTest.java   View source code 6 votes vote down vote up
@Bean
@Override
public RouteBuilder route() {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            // @formatter:off
            from("sponge:spongeEngine").routeId("spongeConsumer1")
                    .to("direct:log");

            from("sponge:spongeEngine").routeId("spongeConsumer2")
                    .to("direct:log");

            from("direct:log").routeId("directLog")
                    .log("${body}");
            // @formatter:on
        }
    };
}
 
Example 9
Project: sponge   File: SimpleCamelConsumerTest.java   View source code 6 votes vote down vote up
@Bean
public RouteBuilder exampleRoute() {
    return new RouteBuilder() {

        @Override
        public void configure() {
            // @formatter:off
            from("sponge:spongeEngine").routeId("spongeConsumer")
                .log("${body}")
                .process(exchange -> spongeEngine().getOperations().getVariable(AtomicBoolean.class, "receivedCamelMessage")
                        .set(true))
                .to("stream:out");
            // @formatter:on
        }
    };
}
 
Example 10
Project: sponge   File: CamelProducerCustomHeaderActionTest.java   View source code 6 votes vote down vote up
@Bean
@Override
public RouteBuilder route() {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            // @formatter:off
            from("direct:start").routeId("spongeProducer")
                    .setHeader("CamelSpongeAction", constant("CustomAction"))
                    .to("sponge:spongeEngine?managed=false")
                    .log("Action result as a body: ${body}")
                    .to("direct:log");

            from("direct:log").routeId("directLog")
                    .log("Action result as a body: ${body}");
            // @formatter:on
        }
    };
}
 
Example 11
Project: camel-springboot   File: SoapCallWithObjectTest.java   View source code 6 votes vote down vote up
@Bean
public RouteBuilder createSoapService() {
	return new RouteBuilder() {
		@Override
		public void configure() throws Exception {
			from("cxf:/GlobalWeather?serviceClass=" + GlobalWeatherSoap.class.getName())
					.routeId("test-GlobalWeatherSoap")
					.toD("direct:${header." + CxfConstants.OPERATION_NAME + "}");

			from("direct:GetCitiesByCountry")
				.setProperty("country",simple("${body[0]}",String.class)) //The method arguments are in a org.apache.cxf.message.MessageContentsList
				.process((e) -> {
					switch(e.getProperty("country",String.class)) {
					case "TEST":
						e.getIn().setBody("<NewDataSet><Table><Country>TEST</Country><City>AA</City></Table><Table><Country>TEST</Country><City>BB</City></Table></NewDataSet>");
						break;
					default:
						e.getIn().setBody("<NewDataSet/>");
					}
				});

		}

	};
}
 
Example 12
Project: camel-springboot   File: SoapCallWithFileTest.java   View source code 6 votes vote down vote up
@Bean
public RouteBuilder createSoapService() {
	return new RouteBuilder() {
		@Override
		public void configure() throws Exception {
			from("cxf:/GlobalWeather?dataFormat=MESSAGE")
					.routeId("test-GlobalWeatherSoap")
					.choice()
					.when(header(SoapBindingConstants.SOAP_ACTION).contains("GetCitiesByCountry"))
						.process((e) -> {
							e.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, getCitiesByCountryResponseCode);
							e.getIn().setBody(getClass().getClassLoader().getResourceAsStream(getCitiesByCountryResponseResource));
							
						})
					.end()
					;
		}
	};
}
 
Example 13
Project: syndesis-integration-runtime   File: FunctionTest.java   View source code 6 votes vote down vote up
protected RouteBuilder createSyndesisRouteBuilder() {
    return new SyndesisRouteBuilder("") {
        @Override
        protected SyndesisModel loadModel() throws Exception {
            SyndesisModel syndesis = new SyndesisModel();
            syndesis.createFlow()
                .addStep(new Endpoint("direct:extension"))
                .addStep(new Function()
                    .name(MyExtension.class.getName())
                    .property("message", "hello"))
                .addStep(new Endpoint("direct:a/b"));

            return syndesis;
        }
    };
}
 
Example 14
Project: syndesis-integration-runtime   File: ExtensionTest.java   View source code 6 votes vote down vote up
protected RouteBuilder createSyndesisRouteBuilder() {
    return new SyndesisRouteBuilder("") {
        @Override
        protected SyndesisModel loadModel() throws Exception {
            SyndesisModel syndesis = new SyndesisModel();
            syndesis.createFlow()
                .addStep(new Endpoint("direct:extension"))
                .addStep(new Extension()
                    .name(MyExtension.class.getName())
                    .property("message", "hello"))
                .addStep(new Endpoint("direct:a/b"));

            return syndesis;
        }
    };
}
 
Example 15
Project: fluid   File: CamelSinkTest.java   View source code 6 votes vote down vote up
@Test
public void shouldWrapIntegersIntoCamelBodies(TestContext context) throws Exception {
    Async async = context.async();
    CamelSink<Integer> sink = new CamelSink<>(
            new JsonObject().put("endpoint", "direct:test")
    );
    CamelContext camelContext = sink.camelContext();
    camelContext.addRoutes(new RouteBuilder() {

        @Override public void configure() throws Exception {
            from("direct:test").process(event -> {
                if (event.getIn().getBody(Integer.class) == 10) {
                    context.assertEquals(event.getIn().getBody(Integer.class), 10);
                    async.complete();
                }
            });
        }
    });

    Source.from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).to(sink);
}
 
Example 16
Project: camel-orientdb   File: OrientDBComponentTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() {
			Map<String, String> properties = context.getProperties();
			properties.put(OrientDBComponent.DB_URL, DB_URL);
			properties.put(OrientDBComponent.DB_USERNAME, DB_USERNAME);
			properties.put(OrientDBComponent.DB_PASSWORD, DB_PASSWORD);
			context.setProperties(properties);

			from("orientdb:INSERT INTO "+TEST_LINKED_CLASS+" SET "+TEST_PROPERTY+"=\""+TEST_PROPERTY_VALUE+"\"?outputType=map&preload=false")
			.to("orientdb:INSERT INTO "+TEST_CLASS+" SET "+TEST_PROPERTY+"=\""+TEST_PROPERTY_VALUE+"\", "+TEST_LINK_PROPERTY+"=:rid")
			.to("orientdb:?preload=true&makeNew=true")
           	.to("mock:result");
        }
    };
}
 
Example 17
Project: Camel   File: EhcacheAggregationRepositoryRoutesTest.java   View source code 6 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from(ENDPOINT_DIRECT)
                .routeId("AggregatingRouteOne")
                .aggregate(header(CORRELATOR))
                .aggregationRepository(createAggregateRepository())
                .aggregationStrategy(EhcacheAggregationRepositoryRoutesTest.this::aggregate)
                .completionSize(VALUES.length)
                    .to("log:org.apache.camel.component.ehcache.processor.aggregate?level=INFO&showAll=true&multiline=true")
                    .to(ENDPOINT_MOCK);
        }
    };
}
 
Example 18
Project: Camel   File: OnCompletionGlobalTraceTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            Tracer tracer = new Tracer();
            tracer.setDestinationUri("mock:trace");
            context.addInterceptStrategy(tracer);

            // START SNIPPET: e1
            // define a global on completion that is invoked when the exchange is complete
            onCompletion().to("log:global").to("mock:sync");

            from("direct:start")
                .process("myProcessor")
                .to("mock:result");
            // END SNIPPET: e1
        }
    };
}
 
Example 19
Project: Camel   File: InOutConsumerQueueTest.java   View source code 6 votes vote down vote up
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() throws Exception {
            from("sjms:queue:start").to("log:request")
                .to("sjms:queue:in.out.queue?exchangePattern=InOut&namedReplyTo=in.out.queue.response")
                .to("log:response").to("mock:result");

            from("sjms:queue:in.out.queue?exchangePattern=InOut").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    String body = (String)exchange.getIn().getBody();
                    if (body.contains("Camel")) {
                        Thread.sleep(2000);
                    }
                }
            });
        }
    };
}
 
Example 20
Project: Camel   File: SedaNoConsumerTest.java   View source code 6 votes vote down vote up
@Test
public void testFailIfNoConsumesrAfterConsumersLeave() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:foo?failIfNoConsumers=true").routeId("stopThisRoute").to("mock:foo");
        }
    });

    context.start();

    getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");

    template.sendBody("seda:foo?failIfNoConsumers=true", "Hello World");

    assertMockEndpointsSatisfied();

    context.stopRoute("stopThisRoute");
    TimeUnit.MILLISECONDS.sleep(100);
    try {
        template.sendBody("seda:foo?failIfNoConsumers=true", "Hello World");
        fail("Should throw an exception");
    } catch (CamelExecutionException e) {
        assertIsInstanceOf(SedaConsumerNotAvailableException.class, e.getCause());
    }
}
 
Example 21
Project: Camel   File: XMLEncryption11Test.java   View source code 6 votes vote down vote up
@Test
public void testFullPayloadAsymmetricKeyDecryptionSHA256() throws Exception {
                  
    final KeyStoreParameters tsParameters = new KeyStoreParameters();
    tsParameters.setPassword("password");
    tsParameters.setResource("sender.ts");
    
    final KeyStoreParameters ksParameters = new KeyStoreParameters();
    ksParameters.setPassword("password");
    ksParameters.setResource("recipient.ks");

    context.addRoutes(new RouteBuilder() {
        public void configure() {
            from("direct:start")
                .marshal().secureXML("", new HashMap<String, String>(), true, "recipient", XMLCipher.AES_128, 
                                     XMLCipher.RSA_OAEP, tsParameters, null, XMLCipher.SHA256).to("mock:encrypted")
                .unmarshal().secureXML("", new HashMap<String, String>(), true, "recipient", XMLCipher.AES_128, 
                                     XMLCipher.RSA_OAEP, ksParameters, null, XMLCipher.SHA256).to("mock:decrypted");
        }
    });
    xmlsecTestHelper.testDecryption(context);
}
 
Example 22
Project: Camel   File: CronScheduledRoutePolicyTest.java   View source code 6 votes vote down vote up
@Test
public void testScheduledStopRoutePolicy() throws Exception {
    context.getComponent("quartz2", QuartzComponent.class).setPropertiesFile("org/apache/camel/routepolicy/quartz2/myquartz.properties");
    context.addRoutes(new RouteBuilder() {
        public void configure() {
            CronScheduledRoutePolicy policy = new CronScheduledRoutePolicy();
            policy.setRouteStopTime("*/3 * * * * ?");
            policy.setRouteStopGracePeriod(0);
            policy.setTimeUnit(TimeUnit.MILLISECONDS);
            
            from("direct:start")
                .routeId("test")
                .routePolicy(policy)
                .to("mock:unreachable");
        }
    });
    context.start();
    
    Thread.sleep(5000);
    assertTrue(context.getRouteStatus("test") == ServiceStatus.Stopped);
}
 
Example 23
Project: Camel   File: RubyScriptTextTest.java   View source code 6 votes vote down vote up
@Test
@Ignore
public void parallelExecutionWithoutCachedScriptAndNewScriptEngineForEachExchange() throws Exception {
    context.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            //getContext().getProperties().put(Exchange.COMPILE_SCRIPT, "true");

            from("seda:jruby?concurrentConsumers=5")
                .to("language:ruby:puts $request.body;result = $request.body")
                .to(resultEndpoint);
        }
    });

    resultEndpoint.setExpectedMessageCount(messageCount);
    resultEndpoint.assertNoDuplicates(body());

    for (int i = 1; i < messageCount + 1; i++) {
        template.sendBody("seda:jruby", "BODY" + i);
    }

    assertMockEndpointsSatisfied(10, TimeUnit.SECONDS);
}
 
Example 24
Project: Camel   File: Mina2SendToProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void testConnectionOnSendMessage() throws Exception {
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").to(String.format("mina2:tcp://localhost:%1$s?sync=false", getPort()));
        }
    });

    try {
        context.start();
    } catch (Exception e) {
        fail("Should not have thrown an exception");
    }

}
 
Example 25
Project: Camel   File: ServiceNowTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() {
            from("direct:servicenow")
                .to("servicenow:{{env:SERVICENOW_INSTANCE}}"
                    + "?userName={{env:SERVICENOW_USERNAME}}"
                    + "&password={{env:SERVICENOW_PASSWORD}}"
                    //+ "&oauthClientId={{env:SERVICENOW_OAUTH2_CLIENT_ID}}"
                    //+ "&oauthClientSecret={{env:SERVICENOW_OAUTH2_CLIENT_SECRET}}"
                    + "&model.incident=org.apache.camel.component.servicenow.model.Incident")
                .to("log:org.apache.camel.component.servicenow?level=INFO&showAll=true")
                .to("mock:servicenow");
        }
    };
}
 
Example 26
Project: Camel   File: ChannelTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(2).redeliveryDelay(0).logStackTrace(false));

            from("direct:start")
                .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        if (counter++ < 1) {
                            throw new IllegalArgumentException("Damn");
                        }
                    }
                }).delay(10).to("mock:result");
        }
    };
}
 
Example 27
Project: Camel   File: MulticastNoStopOnExceptionTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .multicast()
                    .to("direct:foo", "direct:bar", "direct:baz")
                .end()
                .to("mock:result");

            from("direct:foo").to("mock:foo");

            from("direct:bar").process(new MyProcessor()).to("mock:bar");

            from("direct:baz").to("mock:baz");
        }
    };
}
 
Example 28
Project: Camel   File: IntercepFromAndStrategyTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            // add a dummy strategy
            // removing this line the test works
            context.addInterceptStrategy(new DummyInterceptor());
            // intercet from
            interceptFrom("direct:start").log("Intercepted").to("mock:intercepted");

            from("direct:start").to("mock:result");
        }
    };
}
 
Example 29
Project: incubator-tamaya-sandbox   File: TamayaPropertyResolverTest.java   View source code 6 votes vote down vote up
@Test
public void testJavaDSLWithTamayaResolution() throws Exception {
    CamelContext camelContext = new DefaultCamelContext();
    camelContext.addComponent("properties", new TamayaPropertiesComponent());
    RouteBuilder builder = new RouteBuilder() {
        public void configure() {
            from("direct:hello").transform().simple("{{tamaya:message}}");
        }
    };
    camelContext.addRoutes(builder);
    camelContext.start();
    // test configuration is injected right...
    Greeter proxy = new ProxyBuilder(camelContext).endpoint("direct:hello").build(Greeter.class);
    String greetMessage = proxy.greet();
    assertEquals("Good Bye from Apache Tamaya!", greetMessage);
}
 
Example 30
Project: Camel   File: SaxonXPathSplitTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .split().xpath("/persons/person")
                .choice()
                    .when().xpath("person/city = 'London'")
                        .to("mock:london")
                    .when().xpath("person/city = 'Paris'")
                        .to("mock:paris")
                    .otherwise()
                        .to("mock:other");
        }
    };
}
 
Example 31
Project: Camel   File: OnExceptionProcessorInspectCausedExceptionTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(deadLetterChannel("mock:error").maximumRedeliveries(3));

            // START SNIPPET: e1
            // here we register exception cause for MyFunctionException
            // when this exception occur we want it to be processed by our processor
            onException(MyFunctionalException.class).process(new MyFunctionFailureHandler()).stop();
            // END SNIPPET: e1

            from("direct:start").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    throw new MyFunctionalException("Sorry you cannot do this");
                }
            });
        }
    };
}
 
Example 32
Project: Camel   File: RestUndertowHttpPostJsonPojoTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            // configure to use undertow on localhost with the given port
            // and enable auto binding mode
            restConfiguration().component("undertow").host("localhost").port(getPort()).bindingMode(RestBindingMode.auto);

            // use the rest DSL to define the rest services
            rest("/users/")
                .post("new").type(UserPojo.class)
                    .to("mock:input");
        }
    };
}
 
Example 33
Project: Camel   File: SplitterThrowExceptionInExpressionTwoTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .errorHandler(deadLetterChannel("mock:error").disableRedelivery())
                .multicast().stopOnException().streaming()
                    .to("mock:cast1")
                    .split(new MyExpression()).stopOnException().streaming()
                        .to("mock:cast2")
                    .end()
                    .to("mock:cast3")
                .end()
                .to("mock:result");
        }
    };
}
 
Example 34
Project: Camel   File: PropertiesComponentEndpointTest.java   View source code 6 votes vote down vote up
public void testPropertiesComponentEndpoints() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("{{cool.start}}")
                .to("log:{{cool.start}}?showBodyType=false&showExchangeId={{cool.showid}}")
                .to("mock:{{cool.result}}");
        }
    });
    context.start();

    getMockEndpoint("mock:{{cool.result}}").expectedMessageCount(1);

    template.sendBody("{{cool.start}}", "Hello World");

    assertMockEndpointsSatisfied();
}
 
Example 35
Project: Camel   File: RoutingSlipThrowExceptionFromExpressionTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            onException(ExpressionEvaluationException.class)
                .handled(true)
                .to("mock://error");

            from("direct://start")
                .to("log:foo")
                .routingSlip().method(RoutingSlipThrowExceptionFromExpressionTest.class, "slipTo")
                    .to("mock://result")
                .end();
        }
    };
}
 
Example 36
Project: Camel   File: Mina2EncodingTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidEncoding() throws Exception {
    final String uri = String.format("mina2:tcp://localhost:%1$s?textline=true&encoding=XXX&sync=false", getPort());

    try {
        context.addRoutes(new RouteBuilder() {

            public void configure() {
                from(uri).to("mock:result");
            }
        });
        fail("Should have thrown a ResolveEndpointFailedException due invalid encoding parameter");
    } catch (FailedToCreateRouteException e) {
        IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
        assertEquals("The encoding: XXX is not supported", iae.getMessage());
    }
}
 
Example 37
Project: Camel   File: JettyConstantSetHeaderTest.java   View source code 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    port = AvailablePortFinder.getNextAvailable(8000);

    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("jetty:http://localhost:" + port + "/beer")
                    .convertBodyTo(String.class)
                    .to("mock:before")
                    .setHeader("beer", constant("Carlsberg"))
                    .to("mock:result")
                    .transform(constant("Bye World"));
        }
    };
}
 
Example 38
Project: Camel   File: DirectNoMultipleConsumersTest.java   View source code 6 votes vote down vote up
public void testNoMultipleConsumersTest() throws Exception {
    CamelContext container = new DefaultCamelContext();
    container.disableJMX();

    container.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            from("direct:in").to("mock:result");

            from("direct:in").to("mock:result");
        }
    });

    try {
        container.start();
        fail("Should have thrown an FailedToStartRouteException");
    } catch (FailedToStartRouteException e) {
        // expected
    } finally {
        container.stop();
    }
}
 
Example 39
Project: Camel   File: HL7MLLPNettyRouteToTest.java   View source code 6 votes vote down vote up
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() throws Exception {
            from("direct:start")
                .to("netty4:tcp://127.0.0.1:" + getPort() + "?sync=true&decoder=#hl7decoder&encoder=#hl7encoder")
                // because HL7 message contains a bunch of control chars then the logger do not log all of the data
                .log("HL7 message: ${body}")
                .to("mock:result");

            from("netty4:tcp://127.0.0.1:" + getPort() + "?sync=true&decoder=#hl7decoder&encoder=#hl7encoder")
                .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        Message input = exchange.getIn().getBody(Message.class);

                        assertEquals("2.4", input.getVersion());
                        QRD qrd = (QRD)input.get("QRD");
                        assertEquals("0101701234", qrd.getWhoSubjectFilter(0).getIDNumber().getValue());

                        Message response = createHL7AsMessage();
                        exchange.getOut().setBody(response);
                    }
                });
        }
    };
}
 
Example 40
Project: Camel   File: SearchByExchangeDirectTest.java   View source code 6 votes vote down vote up
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("direct:start")
                    .toF("twitter://search?%s&keywords=java", getUriTokens())
                    .split().body()
                    .to("mock:result");

            from("direct:header")
                    .toF("twitter://search?%s", getUriTokens())
                    .split().body()
                    .to("mock:result");

            from("direct:double")
                    .toF("twitter://search?filterOld=false&%s", getUriTokens())
                    .split().body()
                    .to("mock:result");
        }
    };
}