org.apache.camel.RoutesBuilder Java Examples

The following examples show how to use org.apache.camel.RoutesBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactedJMSIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private RoutesBuilder configureJmsRoutes() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(deadLetterChannel(JmsQueue.DEAD_LETTER_QUEUE.getCamelEndpointUri())
            .useOriginalMessage()
            .maximumRedeliveries(0)
            .redeliveryDelay(1000));

            from(JmsQueue.QUEUE_ONE.getCamelEndpointUri())
            .transacted("PROPAGATION_REQUIRED")
            .to(JmsQueue.QUEUE_TWO.getCamelEndpointUri());

            from(JmsQueue.QUEUE_TWO.getCamelEndpointUri())
            .choice()
                .when(body().contains("Bob"))
                    .throwException(new IllegalArgumentException("Invalid name"))
                .otherwise()
                    .to("seda:success");

            from(JmsQueue.DEAD_LETTER_QUEUE.getCamelEndpointUri())
            .to("seda:dlq");
        }
    };
}
 
Example #2
Source File: SendDynamicResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@javax.enterprise.inject.Produces
RoutesBuilder myRoute() {
    return new EndpointRouteBuilder() {
        @Override
        public void configure() throws Exception {
            final EndpointConsumerBuilder trigger = direct(
                    "send-dynamic");
            final EndpointProducerBuilder service = http(
                    "localhost:${header.SendDynamicHttpEndpointPort}/test/service?q=*&fq=publication_date:%5B${date:now-72h:yyyy-MM-dd}T00:00:00Z%20TO%20${date:now-24h:yyyy-MM-dd}T23:59:59Z%5D&wt=xml&indent=false&start=0&rows=100");

            from(trigger)
                    .setHeader(Exchange.HTTP_METHOD).constant("GET")
                    .toD(service)
                    .convertBodyTo(String.class);
        }
    };
}
 
Example #3
Source File: IntegrationRouteLoaderTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void integrationRouteLoaderTest() throws Exception {
    IntegrationRouteLoader irl = new IntegrationRouteLoader();
    TestRuntime runtime = new TestRuntime();

    irl.load(runtime,
        Sources.fromURI("classpath:/syndesis/integration/integration.syndesis?language=syndesis"));

    assertThat(runtime.builders).hasSize(1);
    final RoutesBuilder routeBuilder = runtime.builders.get(0);
    assertThat(routeBuilder).isInstanceOf(RouteBuilder.class);

    RouteBuilder rb = (RouteBuilder) routeBuilder;
    // initialize routes
    rb.configure();
    final RoutesDefinition routeCollection = rb.getRouteCollection();
    final List<RouteDefinition> routes = routeCollection.getRoutes();
    assertThat(routes).hasSize(1);
    final RouteDefinition route = routes.get(0);
    final FromDefinition input = route.getInput();
    assertThat(input).isNotNull();
    assertThat(input.getEndpointUri()).isEqualTo("direct:expression");
}
 
Example #4
Source File: RibbonLoadBalancerTest.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
@Bean
public RoutesBuilder routeBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .routeId("scall")
                .serviceCall()
                    .name("myService")
                    .uri("jetty:http://myService")
                    .end();
            fromF("jetty:http://localhost:%d", PORT1)
                .routeId("" + PORT1)
                .transform()
                .constant("" + PORT1);
            fromF("jetty:http://localhost:%d", PORT2)
                .routeId("" + PORT2)
                .transform()
                .constant("" + PORT2);
        }
    };
}
 
Example #5
Source File: SourceLoader.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an instance of {@link Result} for the given {@link RoutesBuilder}.
 */
static Result on(RoutesBuilder target) {
    ObjectHelper.notNull(target, "target");

    return new Result() {
        @Override
        public Optional<RoutesBuilder> builder() {
            return Optional.of(target);
        }

        @Override
        public Optional<Object> configuration() {
            return Optional.empty();
        }
    };
}
 
Example #6
Source File: SourceLoader.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an instance of {@link Result} by determining the type of hte given target object..
 */
static Result on(Object target) {
    ObjectHelper.notNull(target, "target");

    return new Result() {
        @Override
        public Optional<RoutesBuilder> builder() {
            return target instanceof RoutesBuilder
                ? Optional.of((RoutesBuilder)target)
                : Optional.empty();
        }

        @Override
        public Optional<Object> configuration() {
            return target instanceof RoutesBuilder
                ? Optional.empty()
                : Optional.of(target);
        }
    };
}
 
Example #7
Source File: FunktionTestSupport.java    From funktion-connectors with Apache License 2.0 6 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    final Funktion funktion = createFunktion();
    if (isDumpFlowYAML()) {
        String fileNamePrefix = "target/funktion-tests/" + getClassNameAsPath() + "-" + getTestMethodName();
        File file = new File(getBaseDir(), fileNamePrefix + ".yml");
        file.getParentFile().mkdirs();
        Funktions.saveConfig(funktion, file);
        Funktions.saveConfigJSON(funktion, new File(getBaseDir(), fileNamePrefix + ".json"));
    }
    return new FunktionRouteBuilder() {
        @Override
        protected Funktion loadFunktion() throws IOException {
            return funktion;
        }
    };

}
 
Example #8
Source File: BookRouteConfiguration.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Bean
RoutesBuilder myRouter(final BookService bookService, final BookDeleter bookDeleter) {
	return new RouteBuilder() {

		@Override
		public void configure() throws Exception {
			// scenario 1 - from bean to output
			from("direct:start").unmarshal()
					.json(JsonLibrary.Jackson, BookReturned.class).bean(bookService)
					.to("jms:output");
			// scenario 2 - from input to output
			from("jms:input").unmarshal()
					.json(JsonLibrary.Jackson, BookReturned.class).bean(bookService)
					.to("jms:output");
			// scenario 3 - from input to no output
			from("jms:delete").unmarshal()
					.json(JsonLibrary.Jackson, BookDeleted.class).bean(bookDeleter);
		}

	};
}
 
Example #9
Source File: CamelInflightBackPressureTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            // use in flight route policy to throttle how many messages to take in by Camel
            // to control the back-pressure to only allow at most 20 in-flight messages
            ThrottlingInflightRoutePolicy inflight = new ThrottlingInflightRoutePolicy();
            inflight.setMaxInflightExchanges(20);
            // start Camel consumer again when we are down or below 25% of max
            inflight.setResumePercentOfMax(25);

            from("seda:inbox").routePolicy(inflight)
                // use a little delay as otherwise Camel is to fast and the inflight throttler cannot react so precisely
                // and it also spread the incoming messages more evenly than a big burst
                .delay(100)
                .log("Camel routing to Reactive Streams: ${body}")
                .to("reactive-streams:inbox");
        }
    };
}
 
Example #10
Source File: CamelLatestBackPressureTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            // just ignore discarded streams by marking them as handled
            onException(ReactiveStreamsDiscardedException.class).handled(true);

            from("seda:inbox")
                // use a little delay as otherwise Camel is to fast and the inflight throttler cannot react so precisely
                // and it also spread the incoming messages more evenly than a big burst
                .delay(100)
                .log("Camel routing to Reactive Streams: ${body}")
                .to("reactive-streams:inbox?backpressureStrategy=LATEST");
        }
    };
}
 
Example #11
Source File: ManageTracerMain.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {

            // enable tracing
            context.setTracing(true);

            // slow things down a bit
            context.setDelayer(2000L);

            from("file://target/rider/orders")
                .wireTap("seda:audit")
                .bean(OrderCsvToXmlBean.class)
                .to("jms:queue:orders");

            from("seda:audit")
                .bean(AuditService.class, "auditFile");
        }
    };
}
 
Example #12
Source File: WeaveByToUriTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:quotes").routeId("quotes")
                .split(body(), flexible().accumulateInCollection(ArrayList.class))
                    .transform(simple("${body.toLowerCase()}"))
                    .to("seda:line")
                .end()
                .to("mock:combined");
        }
    };
}
 
Example #13
Source File: AdviceWithMockEndpointsTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:quotes").routeId("quotes")
                .choice()
                    .when(simple("${body} contains 'Camel'"))
                        .to("seda:camel")
                    .otherwise()
                        .to("seda:other");
        }
    };
}
 
Example #14
Source File: WeaveByTypeSelectFirstTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:quotes").routeId("quotes")
                .split(body(), flexible().accumulateInCollection(ArrayList.class))
                    .transform(simple("${body.toLowerCase()}"))
                    .to("seda:line")
                .end()
                .to("mock:combined");
        }
    };
}
 
Example #15
Source File: WeaveByIdTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:quotes").routeId("quotes")
                .bean("transformer").id("transform")
                    .to("seda:lower");
        }
    };
}
 
Example #16
Source File: WeaveByTypeTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:quotes").routeId("quotes")
                .split(body(), flexible().accumulateInCollection(ArrayList.class))
                    .transform(simple("${body.toLowerCase()}"))
                    .to("mock:line")
                .end()
                .to("mock:combined");
        }
    };
}
 
Example #17
Source File: ReplaceFromTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("aws-sqs:quotes").routeId("quotes")
                .choice()
                    .when(simple("${body} contains 'Camel'"))
                        .to("seda:camel")
                    .otherwise()
                        .to("seda:other");
        }
    };
}
 
Example #18
Source File: CamelNoBackPressureTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:inbox")
                // use a little delay as otherwise Camel is to fast and the inflight throttler cannot react so precisely
                // and it also spread the incoming messages more evenly than a big burst
                .delay(100)
                .log("Camel routing to Reactive Streams: ${body}")
                .to("reactive-streams:inbox");
        }
    };
}
 
Example #19
Source File: CamelConsumerBackPressureTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            // allow at most 5 inflight messages and use 5 concurrent consumers
            from("reactive-streams:inbox?maxInflightExchanges=5&concurrentConsumers=5")
                // use a little delay so us humans can follow what happens
                .delay(constant(10))
                .log("Processing message ${body}");
        }
    };
}
 
Example #20
Source File: CamelHystrixTimeoutAndFallbackTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .hystrix()
                    // use 2 second timeout
                    .hystrixConfiguration().executionTimeoutInMilliseconds(2000).end()
                    .log("Hystrix processing start: ${threadName}")
                    .toD("direct:${body}")
                    .log("Hystrix processing end: ${threadName}")
                .onFallback()
                    // use fallback if there was an exception or timeout
                    .log("Hystrix fallback start: ${threadName}")
                    .transform().constant("Fallback response")
                    .log("Hystrix fallback end: ${threadName}")
                .end()
                .log("After Hystrix ${body}");

            from("direct:fast")
                // this is a fast route and takes 1 second to respond
                .log("Fast processing start: ${threadName}")
                .delay(1000)
                .transform().constant("Fast response")
                .log("Fast processing end: ${threadName}");

            from("direct:slow")
                // this is a slow route and takes 3 second to respond
                .log("Slow processing start: ${threadName}")
                .delay(3000)
                .transform().constant("Slow response")
                .log("Slow processing end: ${threadName}");
        }
    };
}
 
Example #21
Source File: CamelHystrixTimeoutTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .hystrix()
                    // use 2 second timeout
                    .hystrixConfiguration().executionTimeoutInMilliseconds(2000).end()
                    .log("Hystrix processing start: ${threadName}")
                    .toD("direct:${body}")
                    .log("Hystrix processing end: ${threadName}")
                .end()
                .log("After Hystrix ${body}");

            from("direct:fast")
                // this is a fast route and takes 1 second to respond
                .log("Fast processing start: ${threadName}")
                .delay(1000)
                .transform().constant("Fast response")
                .log("Fast processing end: ${threadName}");

            from("direct:slow")
                // this is a slow route and takes 3 second to respond
                .log("Slow processing start: ${threadName}")
                .delay(3000)
                .transform().constant("Slow response")
                .log("Slow processing end: ${threadName}");
        }
    };
}
 
Example #22
Source File: CamelMain.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadRouteBuilders(CamelContext camelContext) throws Exception {
    // routes are discovered and pre-instantiated which allow to post process them to support Camel's DI
    CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor();
    for (RoutesBuilder builder : mainConfigurationProperties.getRoutesBuilders()) {
        postProcessor.postProcessBeforeInitialization(builder, builder.getClass().getName());
        postProcessor.postProcessAfterInitialization(builder, builder.getClass().getName());
    }
}
 
Example #23
Source File: StubRunnerCamelConfiguration.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Bean
public RoutesBuilder myRouter(final BatchStubRunner batchStubRunner) {
	return new SpringRouteBuilder() {
		@Override
		public void configure() throws Exception {
			Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner
					.getContracts();
			for (Map.Entry<StubConfiguration, Collection<Contract>> entry : contracts
					.entrySet()) {
				Collection<Contract> value = entry.getValue();
				MultiValueMap<String, Contract> map = new LinkedMultiValueMap<>();
				for (Contract dsl : value) {
					if (dsl == null) {
						continue;
					}
					if (dsl.getInput() != null
							&& dsl.getInput().getMessageFrom() != null
							&& StringUtils.hasText(dsl.getInput().getMessageFrom()
									.getClientValue())) {
						String from = dsl.getInput().getMessageFrom()
								.getClientValue();
						map.add(from, dsl);
					}
				}
				for (Map.Entry<String, List<Contract>> entries : map.entrySet()) {
					from(entries.getKey())
							.filter(new StubRunnerCamelPredicate(entries.getValue()))
							.process(new StubRunnerCamelProcessor())
							.dynamicRouter(header(
									StubRunnerCamelConfiguration.STUBRUNNER_DESTINATION_URL_HEADER_NAME));
				}
			}
		}
	};
}
 
Example #24
Source File: CamelMainRoutesCollector.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public List<RoutesBuilder> collectRoutesFromRegistry(
        CamelContext camelContext,
        String excludePattern,
        String includePattern) {

    return registryRoutesLoader.collectRoutesFromRegistry(camelContext, excludePattern, includePattern);
}
 
Example #25
Source File: CamelContextRecorder.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public void addRoutes(RuntimeValue<CamelContext> context, String typeName) {
    try {
        addRoutes(
                context,
                context.getValue().getClassResolver().resolveClass(typeName, RoutesBuilder.class));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: ActivityLoggingTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createTestRoutes() {
    return new RouteBuilder() {
        @Override
        public void configure() {
            from("direct:start")
                .id("start")
                .routePolicy(new IntegrationActivityTrackingPolicy(activityTracker))
                .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                .pipeline()
                    .id("step:log")
                    .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                    .log(LoggingLevel.INFO, "log", "log", "hi")
                    .process(OutMessageCaptureProcessor.INSTANCE)
                .end()
                .pipeline()
                    .id("step:rnderr")
                    .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                    .process().body(String.class, body -> {
                        if ("Hello Error".equals(body)) {
                            throw new RuntimeException("Bean Error");
                        }
                    })
                    .process(OutMessageCaptureProcessor.INSTANCE)
                .end()
                .pipeline()
                    .id("step:end")
                    .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                    .to("mock:end")
                    .process(OutMessageCaptureProcessor.INSTANCE)
                .end();
        }
    };
}
 
Example #27
Source File: ActivityLoggingWithSplitTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createTestRoutes() {
    return new RouteBuilder() {
        @Override
        public void configure() {
            from("direct:start")
                .id("start")
                .routePolicy(new IntegrationActivityTrackingPolicy(activityTracker))
                .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                .process(OutMessageCaptureProcessor.INSTANCE)
                .split()
                    .body()
                    .pipeline()
                        .id("step:log")
                        .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                        .log(LoggingLevel.INFO, "log", "log", "hi")
                        .process(OutMessageCaptureProcessor.INSTANCE)
                    .end()
                    .pipeline()
                        .id("step:rnderr")
                        .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                        .process().body(String.class, body -> {
                            if ("error".equals(body)) {
                                throw new RuntimeException("Bean Error");
                            }
                        })
                        .process(OutMessageCaptureProcessor.INSTANCE)
                    .end()
                    .pipeline()
                        .id("step:end")
                        .setHeader(IntegrationLoggingConstants.STEP_ID, KeyGenerator::createKey)
                        .to("mock:end")
                        .process(OutMessageCaptureProcessor.INSTANCE)
                    .end()
                .end();
        }
    };
}
 
Example #28
Source File: CamelRouteProducer.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Produces
RoutesBuilder producedRoute() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:produced")
                    .id("produced")
                    .to("log:produced");
        }
    };
}
 
Example #29
Source File: ComponentProxyComponentTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() {
            from("direct:start")
                .to("my-bean-proxy")
                .to("mock:result");
        }
    };
}
 
Example #30
Source File: CamelConsumeNumbersTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("reactive-streams:numbers")
                .log("Got number ${body}");
        }
    };
}