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   Source Code and License 8 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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");
        }
    };
}
 
Example 41
Project: Camel   File: FileConsumeAlterFileNameHeaderIssueTest.java   Source Code and License 6 votes vote down vote up
public void testConsumeAndMoveChangeFileHeader() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("file://target/files")
                // change file header
                .setHeader(Exchange.FILE_NAME, constant("bye.txt"))
                .to("mock:result");
        }
    });
    context.start();

    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived("Hello World");
    mock.expectedHeaderReceived(Exchange.FILE_NAME, "bye.txt");

    template.sendBodyAndHeader("file://target/files", "Hello World", Exchange.FILE_NAME, "hello.txt");

    assertMockEndpointsSatisfied();
    oneExchangeDone.matchesMockWaitTime();

    // the original file should have been moved, as the file consumer should be resilient against
    // end users changing headers
    assertTrue("File should been moved", new File("target/files/.camel/hello.txt").exists());
}
 
Example 42
Project: Camel   File: NettyTcpWithInOutUsingPlainSocketTest.java   Source Code and License 6 votes vote down vote up
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("netty4:tcp://localhost:{{port}}?textline=true&sync=true").process(new Processor() {
                public void process(Exchange e) {
                    String in = e.getIn().getBody(String.class);
                    if ("force-null-out-body".equals(in)) {
                        // forcing a null out body
                        e.getOut().setBody(null);
                    } else if ("force-exception".equals(in)) {
                        // clear out before throwing exception
                        e.getOut().setBody(null);
                        throw new IllegalArgumentException("Forced exception");
                    } else {
                        e.getOut().setBody("Hello " + in);
                    }
                }
            });
        }
    };
}
 
Example 43
Project: Camel   File: DefaultErrorHandlerTest.java   Source Code and License 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            // if no error handler is configured it should
            // use the default error handler

            from("direct:start").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    String body = exchange.getIn().getBody(String.class);
                    if ("Kabom".equals(body)) {
                        throw new IllegalArgumentException("Boom");
                    }
                    exchange.getIn().setBody("Bye World");
                }
            }).to("mock:result");
        }
    };
}
 
Example 44
Project: Camel   File: WeightedRandomLoadBalanceTest.java   Source Code and License 6 votes vote down vote up
public void testRandom2() throws Exception {
    x.expectedMessageCount(2);
    y.expectedMessageCount(1);
    z.expectedMessageCount(3);

    context.addRoutes(new RouteBuilder() {
        public void configure() {
            // START SNIPPET: example
            from("direct:start")
                .loadBalance().weighted(false, "2, 1, 3", ",")
                    .to("mock:x", "mock:y", "mock:z");
            // END SNIPPET: example
        }
    });
    context.start();
    
    sendMessages(1, 2, 3, 4, 5, 6);
    
    assertMockEndpointsSatisfied();
}
 
Example 45
Project: Camel   File: ValidatorSchemaImportTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test for the valid schema location relative to a path other than the validating schema
 * @throws Exception
 */
@Test
public void testChildParentUncleSchemaImport() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .doTry()
                    .to("validator:org/apache/camel/component/validator/childparentuncle/child/child.xsd")
                    .to("mock:valid")
                .doCatch(ValidationException.class)
                    .to("mock:invalid")
                .doFinally()
                    .to("mock:finally")
                .end();
        }
    });
    validEndpoint.expectedMessageCount(1);
    finallyEndpoint.expectedMessageCount(1);

    template.sendBody("direct:start",
            "<childuser xmlns='http://foo.com/bar'><user><id>1</id><username>Test User</username></user></childuser>");

    MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint);
}
 
Example 46
Project: eds   File: GearmanTest.java   Source Code and License 5 votes vote down vote up
@Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder()   {
            @Override
            public void configure() throws Exception {
                from(uri).to(to).tracing().log("接收消息 ${body}");
//                .process(new Processor() {
//                    @Override
//                    public void process(Exchange exchange) throws Exception {
//                        System.err.println("=====process : "+exchange);
//                    }
//                });
            }
        };
    }
 
Example 47
Project: eds   File: ActiveMQWithCamelTest.java   Source Code and License 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
  // 收
  return new RouteBuilder() {
    @Override
    public void configure() throws Exception {
      from(activemqEndPoint).process(processor);
    }
  };
}
 
Example 48
Project: drinkwater-java   File: TraceRouteBuilder.java   Source Code and License 5 votes vote down vote up
public static void addExceptionTracing(IDrinkWaterService service,
                                       Class ExceptionClazz,
                                       RouteBuilder routeBuilder) {
    if (service.getConfiguration().getIsTraceEnabled()) {
        routeBuilder.onException(ExceptionClazz).to(ROUTE_exceptionEvent);
    }
}
 
Example 49
Project: drinkwater-java   File: RestHelper.java   Source Code and License 5 votes vote down vote up
public static void buildRestRoutes(RouteBuilder builder, Object bean,
                                   IDrinkWaterService drinkWaterService) {

    //check this for cors problems
    //http://camel.465427.n5.nabble.com/Workaround-with-REST-DSL-to-avoid-HTTP-method-not-allowed-405-td5771508.html
    try {

        String serviceHost = endpointFrom(drinkWaterService);
        drinkWaterService.getConfiguration().setServiceHost(serviceHost);

        RestPropertyDefinition corsAllowedHeaders = new RestPropertyDefinition();
        corsAllowedHeaders.setKey("Access-Control-Allow-Headers");
        corsAllowedHeaders.setValue(getAllowedCorsheaders(drinkWaterService));

        // builder.getContext().getDataFormats();
        RestConfigurationDefinition restConfig =
                builder.restConfiguration()
                        .component("jetty")
                        .enableCORS(true)
                        .scheme("http")
                        .host(host(drinkWaterService))
                        .port(port(drinkWaterService))
                        .contextPath(context(drinkWaterService, drinkWaterService.getConfiguration()))
                        .bindingMode(RestBindingMode.json)
                        .jsonDataFormat("json-drinkwater");

        restConfig.setCorsHeaders(singletonList(corsAllowedHeaders));

    } catch (Exception ex) {
        throw new RuntimeException("could not configure the rest service correctly", ex);
    }

    javaslang.collection
            .List.of(ReflectHelper.getPublicDeclaredMethods(bean.getClass()))
            .map(method -> buildRestRoute(builder, method, drinkWaterService.getTracer()))
            .map(tuple -> routeToBeanMethod(tuple._1, bean, tuple._2, drinkWaterService));
}
 
Example 50
Project: drinkwater-java   File: RestHelper.java   Source Code and License 5 votes vote down vote up
private static RestDefinition toRestdefinition(RouteBuilder builder,
                                               Method method,
                                               HttpMethod httpMethod,
                                               String restPath) {
    RestDefinition answer = builder.rest();

    String fromPath = restPath;

    if (httpMethod == HttpMethod.GET) {
        answer = answer.get(fromPath);
    } else if (httpMethod == HttpMethod.POST) {
        answer = answer.post(fromPath);
    } else if (httpMethod == HttpMethod.PUT) {
        answer = answer.put(fromPath);
    } else if (httpMethod == HttpMethod.DELETE) {
        answer = answer.delete(fromPath);
    } else if (httpMethod == HttpMethod.PATCH) {
        answer = answer.patch(fromPath);
    } else {
        throw new RuntimeException("method currently not supported in Rest Paths : " + httpMethod);
    }

    answer = setBodyType(answer, method);

    return answer;
}
 
Example 51
Project: drinkwater-java   File: RouteBuilders.java   Source Code and License 5 votes vote down vote up
public static RoutesBuilder mapCronRoutes(String groupName, DrinkWaterApplication app, Service service) {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {

            boolean jobActive = service.safeLookupProperty(Boolean.class, "job.activated", true);

            if (jobActive) {

                Object bean = BeanFactory.createBean(app, service.getConfiguration(), service);

                String cronExpression = service.getConfiguration().getCronExpression();
                long interval = service.getConfiguration().getRepeatInterval();

                cronExpression =
                        service.lookupProperty(service.getConfiguration().getCronExpression() + ":" + cronExpression);

                interval = service.safeLookupProperty(Long.class, "job.interval", interval);

                String enpoint = "quartz2://" + groupName + "/" +
                        service.getConfiguration().getServiceName() + "?fireNow=true";

                if (cronExpression == null) {
                    cronExpression = cronExpression.replaceAll(" ", "+");
                    enpoint += "&cron=" + cronExpression;

                } else {
                    enpoint += "&trigger.repeatInterval=" + interval;
                }

                //camel needs + instead of white space

                //TODO : check correctness of expression see camel doc here the job must have only one method !!!!
                from(enpoint).bean(bean);
            }

        }
    };
}
 
Example 52
Project: drinkwater-java   File: RouteBuilders.java   Source Code and License 5 votes vote down vote up
public static RouteBuilder mapHttpProxyRoutes(DrinkWaterApplication app, Service service) {

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                boolean useSessionManager = service.safeLookupProperty(Boolean.class, "useSessionManager:false", false);
                String sessionManagerOption = useSessionManager? "&sessionSupport=true":"";

                String frontEndpoint = service.lookupProperty("proxy.endpoint");

                String destinationEndpoint = service.lookupProperty("destination.endpoint");

                if (frontEndpoint == null || destinationEndpoint == null) {
                    throw new RuntimeException("could not find proxy and destination endpoint from config");
                }

                String handlers = getHandlersForJetty(service);
                String handlersConfig = handlers == null ? "":"&handlers="+handlers;

                addExceptionTracing(service, Exception.class, this);

                RouteDefinition choice =
                        from("jetty:" + frontEndpoint + "?matchOnUriPrefix=true&enableMultipartFilter=false"
                                + handlersConfig + sessionManagerOption);

                choice = addServerReceivedTracing(service, choice);
                choice = choice.to("jetty:" + destinationEndpoint + "?bridgeEndpoint=true&amp;throwExceptionOnFailure=true");
                addServerSentTracing(service, choice);
            }
        };
    }
 
Example 53
Project: drinkwater-java   File: DrinkWaterApplication.java   Source Code and License 5 votes vote down vote up
private static void addWWWIfEnabled(DrinkWaterApplication app) throws Exception {
    Boolean serveStaticWWW = Boolean.parseBoolean(app.lookupProperty(WWW_Enabled));

    if (serveStaticWWW) {
        RouteBuilder WWWRouteBuilder = new RouteBuilder() {

            @Override
            public void configure() throws Exception {


                CamelContextFactory.registerBean(app.applicationLevelContext, DW_STATIC_WWW_HANDLER, getWWWResourceHandler());

                String wwwHost = app.lookupProperty(WWW_Host);
                String wwwPort = app.lookupProperty(WWW_Port);
                String wwwRoot = app.lookupProperty(WWW_Root);
                String wwwHostAndPort = wwwHost + ":" + wwwPort + "/" + wwwRoot;

                from(String.format(
                        "jetty:http://%s?handlers=%s", wwwHostAndPort, DW_STATIC_WWW_HANDLER))
                        .to("mock:empty?retainFirst=1");

                logger.info("static files served from : http://" + wwwHostAndPort);


            }
        };
        app.applicationLevelContext.addRoutes(WWWRouteBuilder);
    }
}
 
Example 54
Project: drinkwater-java   File: DrinkWaterApplication.java   Source Code and License 5 votes vote down vote up
private RouteBuilder createTracingRoute(IBaseEventLogger logger) {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {

            from("vm:trace").bean(logger, "logEvent(${body})");

        }
    };
}
 
Example 55
Project: syndesis   File: FunctionTest.java   Source Code and License 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("direct:a/b")
                .to("mock:result");
        }
    };
}
 
Example 56
Project: syndesis   File: ExtensionTest.java   Source Code and License 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("direct:a/b")
                .to("mock:result");
        }
    };
}
 
Example 57
Project: syndesis   File: JsonEndpointTest.java   Source Code and License 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from("direct:start").to("json:marshal").convertBodyTo(String.class).to("mock:result");
        }
    };
}
 
Example 58
Project: syndesis   File: S3PollingBucketConnectorTest.java   Source Code and License 5 votes vote down vote up
@Bean
public RouteBuilder routeBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("aws-s3-polling-bucket-connector:test?amazonS3Client=#amazonS3Client")
                .to("mock:result");
        }
    };
}
 
Example 59
Project: syndesis   File: S3GetObjectConnectorTest.java   Source Code and License 5 votes vote down vote up
@Bean
public RouteBuilder routeBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("aws-s3-get-object-connector:test?amazonS3Client=#amazonS3Client")
                .to("mock:result");
        }
    };
}
 
Example 60
Project: syndesis   File: S3CopyObjectConnectorTest.java   Source Code and License 5 votes vote down vote up
@Bean
public RouteBuilder routeBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .to("aws-s3-copy-object-connector:test?deleteAfterWrite=false&amazonS3Client=#amazonS3Client");
        }
    };
}