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); } } } }; }
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); } } } }; }
@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}"); } }; }
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; } }; }
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; } }; }
/** * 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 } }; }
@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 } }; }
@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 } }; }
@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 } }; }
@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 } }; }
@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/>"); } }); } }; }
@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() ; } }; }
@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); }
@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"); } }; }
@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); } }; }
@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 } }; }
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); } } }); } }; }
@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()); } }
@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); }
@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); }
@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); }
@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"); } }
@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"); } }; }
@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"); } }; }
@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"); } }; }
@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"); } }; }
@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); }
@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"); } }; }
@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"); } }); } }; }
@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"); } }; }
@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"); } }; }
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(); }
@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(); } }; }
@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()); } }
@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")); } }; }
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(); } }
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); } }); } }; }
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"); } }; }