Java Code Examples for org.apache.camel.impl.DefaultCamelContext#addRoutes()

The following examples show how to use org.apache.camel.impl.DefaultCamelContext#addRoutes() . 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: SimpleRegistryTest.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    // create the registry to be the SimpleRegistry which is just a Map based implementation
    SimpleRegistry registry = new SimpleRegistry();
    // register our HelloBean under the name helloBean
    registry.put("helloBean", new HelloBean());

    // tell Camel to use our SimpleRegistry
    context = new DefaultCamelContext(registry);

    // create a producer template to use for testing
    template = context.createProducerTemplate();

    // add the route using an inlined RouteBuilder
    context.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            from("direct:hello").beanRef("helloBean");
        }
    });
    // star Camel
    context.start();
}
 
Example 2
Source File: DecanterTraceEventHandlerTest.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private DefaultCamelContext createCamelContext(TraceEventHandler handler) throws Exception {
    RouteBuilder builder = new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").routeId("test-route").to("log:foo");
        }
    };
    DefaultCamelContext camelContext = new DefaultCamelContext();
    camelContext.setName("test-context");
    camelContext.addRoutes(builder);
    Tracer tracer = new Tracer();
    tracer.setEnabled(true);
    tracer.setTraceOutExchanges(true);
    tracer.setLogLevel(LoggingLevel.OFF);
    tracer.addTraceHandler(handler);
    camelContext.setTracing(true);
    camelContext.setDefaultTracer(tracer);
    camelContext.start();
    return camelContext;
}
 
Example 3
Source File: DecanterEventNotifierTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private DefaultCamelContext createCamelContext(DecanterEventNotifier notifier) throws Exception {
    RouteBuilder builder = new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").routeId("test-route").to("log:foo");
        }
    };

    DefaultCamelContext camelContext = new DefaultCamelContext();
    camelContext.setName("test-context");
    camelContext.addRoutes(builder);
    camelContext.getManagementStrategy().addEventNotifier(notifier);
    camelContext.start();
    return camelContext;
}
 
Example 4
Source File: CamelAppenderTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    camelContext = new DefaultCamelContext();
    camelContext.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct-vm:decanter")
                    .id("decanter-test")
                    .log("Received ${body}")
                    .to("mock:assert");
        }
    });
    camelContext.start();
}
 
Example 5
Source File: RouteXmlTestSupport.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected XmlModel assertRoutes(File file, int expected, String ns) throws Exception {
    if (ns == null || ns.trim().length() == 0) {
        ns = CamelNamespaces.springNS;
    }
    XmlModel x = assertLoadModel(file, expected);

    // now lets add a route and write it back again...
    DefaultCamelContext tmpContext = new DefaultCamelContext();
    tmpContext.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:newFrom").to("seda:newTo");
        }
    });
    x.getContextElement().getRoutes().addAll(tmpContext.getRouteDefinitions());

    List<RouteDefinition> routes = x.getRouteDefinitionList();
    assertEquals("routes: " + routes, expected + 1, routes.size());

    // now lets write to XML      model
    outDir.mkdirs();
    File outFile = new File(outDir, file.getName());
    System.out.println("Generating file: " + outFile);
    tool.marshal(outFile, x);

    assertFileExists(outFile);

    // lets check the file has the correct namespace inside it
    String text = FileCopyUtils.copyToString(new FileReader(outFile));
    assertTrue("Namespace " + ns + " not present in output file\n" + text, text.contains(ns));

    return x;
}
 
Example 6
Source File: GRPCIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testGRPCSynchronousProducer() throws Exception {

    Future<String> future = AvailablePortFinder.readServerDataAsync("grpc-port");
    int port = Integer.parseInt(future.get(10, TimeUnit.SECONDS));

    DefaultCamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .toF("grpc://localhost:%d/%s?method=pingSyncSync&synchronous=true", port, "org.wildfly.camel.test.grpc.subA.PingPong");
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        PingRequest pingRequest = PingRequest.newBuilder()
            .setPingName(GRPC_TEST_PING_VALUE)
            .setPingId(GRPC_TEST_PING_ID_1)
            .build();

        PongResponse response = template.requestBody("direct:start", pingRequest, PongResponse.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(response.getPongId(), GRPC_TEST_PING_ID_1);
        Assert.assertEquals(response.getPongName(), GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE);
    } finally {
        camelctx.close();
    }
}
 
Example 7
Source File: Nd4jKafkaRouteTest.java    From nd4j with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
    zk = new EmbeddedZookeeper(TestUtils.getAvailablePort());
    zk.startup();
    kafka = new EmbeddedKafkaCluster(zk.getConnection());
    kafka.startup();
    kafka.createTopics(TOPIC);
    camelContext = new DefaultCamelContext();
    camelContext.start();
    connectionInformation = KafkaConnectionInformation.builder().groupId(GROUP_ID).topicName(TOPIC)
                    .zookeeperHost("localhost").zookeeperPort(zk.getPort()).kafkaBrokerList(kafka.getBrokerList())
                    .build();
    camelContext.addRoutes(Nd4jKafkaRoute.builder().kafkaConnectionInformation(connectionInformation).build());
}
 
Example 8
Source File: SwaggerIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwagger() throws Exception {
    DefaultCamelContext camelctx = new DefaultCamelContext();
    camelctx.setName("swagger-test");
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            restConfiguration().component("undertow")
                .contextPath("swagger-tests")
                .host("localhost")
                .port(8080)
                .apiContextPath("/api-doc")
                .apiProperty("api.title", "User API")
                .apiProperty("api.version", "1.2.3")
                .apiProperty("cors", "true");
            rest("/hello")
                .get("/{name}").description("A user object").outType(User.class).to("direct:hello")
                .produces(MediaType.APPLICATION_JSON)
                .consumes(MediaType.APPLICATION_JSON);
            from("direct:hello").transform(simple("Hello ${header.name}"));
        }
    });

    camelctx.start();
    try {
        HttpRequest.HttpResponse result = HttpRequest.get("http://localhost:8080/swagger-tests/hello/Kermit").getResponse();
        Assert.assertEquals("Hello Kermit", result.getBody());

        result = HttpRequest.get("http://localhost:8080/swagger-tests/api-doc").getResponse();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getStatusCode());
        Assert.assertTrue("Contains substr: " + result.getBody(), result.getBody().contains("\"name\" : \"hello\""));
    } finally {
        camelctx.close();
    }
}
 
Example 9
Source File: SplitStepHandlerJsonTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Test chains of split/aggregate where a 2nd split directly follows on the 1st aggregate.
 * direct -> split -> log -> aggregate -> split -> log -> aggregate -> mock
 */
@Test
public void testSplitAggregateChain() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder routes = new IntegrationRouteBuilder(
                "classpath:/syndesis/integration/split-chain.json",
                Resources.loadServices(IntegrationStepHandler.class)
        );

        // Set up the camel context
        context.addRoutes(routes);
        addBodyLogger(context);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:expression", MockEndpoint.class);
        final List<String> body = Arrays.asList("a,b,c", "de", "f,g");

        result.expectedBodiesReceived(body);

        template.sendBody("direct:expression", body);

        result.assertIsSatisfied();
    } finally {
        context.stop();
    }
}
 
Example 10
Source File: ComponentOptionsTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegistryOption() throws Exception{
    Map<String, Object> properties = new HashMap<>();
    properties.put("dataSource", "#ds");
    properties.put("query", "select from dual");


    ComponentProxyComponent component = new ComponentProxyComponent("my-sql-proxy", "sql");
    component.setOptions(properties);

    SimpleRegistry registry = new SimpleRegistry();
    registry.bind("ds", this.ds);
    registry.bind(component.getComponentId() + "-component", component);

    DefaultCamelContext context = new DefaultCamelContext(registry);
    try {
        context.setAutoStartup(false);
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .to("my-sql-proxy")
                    .to("mock:result");
            }
        });

        validateRegistryOption(context);
        validateRegistryOption(context);
    } finally {
        context.stop();
    }
}
 
Example 11
Source File: SimpleEndpointStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleEndpointStep() throws Exception {
    final DefaultCamelContext context = getDefaultCamelContextWithMyBeanInRegistry();

    try {
        final RouteBuilder routes = newIntegrationRouteBuilder(activityTracker,
            new Step.Builder()
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("direct")
                        .putConfiguredProperty("name", "start")
                        .build())
                    .build())
                .build(),
            new Step.Builder()
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("bean")
                        .putConfiguredProperty("beanName", "myBean")
                        .putConfiguredProperty("method", "myProcessor")
                        .build())
                    .build())
                .build(),
            new Step.Builder()
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("mock")
                        .putConfiguredProperty("name", "result")
                        .build())
                    .build())
                .build()
        );

        // Set up the camel context
        context.setUuidGenerator(KeyGenerator::createKey);
        context.addLogListener(new IntegrationLoggingListener(activityTracker));
        context.addInterceptStrategy(new ActivityTrackingInterceptStrategy(activityTracker));
        context.addRoutes(routes);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:result", MockEndpoint.class);
        final String body = "testSimpleEndpointStep";

        result.expectedBodiesReceived(body.toUpperCase());
        template.sendBody("direct:start", body);

        result.assertIsSatisfied();

        verify(activityTracker).startTracking(any(Exchange.class));
        verify(activityTracker, times(3)).track(eq("exchange"), anyString(), eq("step"), anyString(), eq("id"), anyString(), eq("duration"), anyLong(), eq("failure"), isNull());
        verify(activityTracker).finishTracking(any(Exchange.class));
    } finally {
        context.stop();
    }
}
 
Example 12
Source File: CamelCollectorTest.java    From karaf-decanter with Apache License 2.0 4 votes vote down vote up
@Test
public void testTracer() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-collector-camel", new RolePrincipal("admin")));

    // add a event handler
    List<Event> received = new ArrayList();
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            received.add(event);
        }
    };
    Hashtable serviceProperties = new Hashtable();
    serviceProperties.put(EventConstants.EVENT_TOPIC, "decanter/collect/*");
    bundleContext.registerService(EventHandler.class, eventHandler, serviceProperties);

    // create route with tracer
    EventAdmin eventAdmin = getOsgiService(EventAdmin.class);
    DecanterTraceEventHandler handler = new DecanterTraceEventHandler();
    handler.setEventAdmin(eventAdmin);

    RouteBuilder routeBuilder = new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:test").routeId("route-test").to("log:foo");
        }
    };
    DefaultCamelContext camelContext = new DefaultCamelContext();
    camelContext.setName("context-test");
    camelContext.addRoutes(routeBuilder);
    Tracer tracer = new Tracer();
    tracer.setEnabled(true);
    tracer.setTraceOutExchanges(true);
    tracer.setLogLevel(LoggingLevel.OFF);
    tracer.addTraceHandler(handler);
    camelContext.setTracing(true);
    camelContext.setDefaultTracer(tracer);
    camelContext.start();

    // send a exchange into the route
    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.sendBodyAndHeader("direct:test", "This is a test", "testHeader", "testValue");

    // TODO two events ?
    Assert.assertEquals(2, received.size());

    Assert.assertEquals("decanter/collect/camel/tracer", received.get(0).getTopic());
    Assert.assertEquals("context-test", received.get(0).getProperty("camelContextName"));
    Assert.assertEquals("InOnly", received.get(0).getProperty("exchangePattern"));
    Assert.assertEquals("camelTracer", received.get(0).getProperty("type"));
    Assert.assertEquals("log://foo", received.get(0).getProperty("toNode"));
    Assert.assertEquals("route-test", received.get(0).getProperty("routeId"));
    Assert.assertEquals("direct://test", received.get(0).getProperty("fromEndpointUri"));
    Assert.assertEquals("root", received.get(0).getProperty("karafName"));
    Assert.assertEquals("This is a test", received.get(0).getProperty("inBody"));
    Assert.assertEquals("String", received.get(0).getProperty("inBodyType"));
}
 
Example 13
Source File: LiveScoreVerticle.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {

    // create a CamelContext
    camelContext = new DefaultCamelContext();
    // add the Camel routes which streams live scores
    camelContext.addRoutes(new LiveScoreRouteBuilder(vertx));
    // create a producer template which is used below when a new client connects
    template = camelContext.createFluentProducerTemplate();
    // start Camel
    camelContext.start();

    // create a vertx router to setup websocket and http server
    Router router = Router.router(vertx);

    // configure allowed inbound and outbound traffics
    BridgeOptions options = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("control"))
            .addOutboundPermitted(new PermittedOptions().setAddress("clock"))
            .addOutboundPermitted(new PermittedOptions().setAddress("games"))
            .addOutboundPermitted(new PermittedOptions().setAddress("goals"));

    // route websocket to vertx
    router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options, event -> {
        if (event.type() == BridgeEventType.SOCKET_CREATED) {
            System.out.println("Websocket connection created");

            // a new client connected so setup its screen with the list of games
            vertx.setTimer(100, h -> template.to("direct:init-games").send());

        } else if (event.type() == BridgeEventType.SOCKET_CLOSED) {
            System.out.println("Websocket connection closed");
        }

        event.complete(true);
    }));

    // serve the static resources (src/main/resources/webroot)
    router.route().handler(StaticHandler.create());

    // let router accept on port 8080
    System.out.println("Listening on http://localhost:8080");
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
 
Example 14
Source File: ExtensionStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testBeanExtensionStepHandler() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder routeBuilder = newIntegrationRouteBuilder(
            new io.syndesis.common.model.integration.Step.Builder()
                .id("step-1")
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("direct")
                        .putConfiguredProperty("name", "start")
                        .build())
                    .build())
                .build(),
            new io.syndesis.common.model.integration.Step.Builder()
                .id("step-2")
                .stepKind(StepKind.extension)
                .action(new StepAction.Builder()
                    .descriptor(new StepDescriptor.Builder()
                        .kind(StepAction.Kind.BEAN)
                        .entrypoint("io.syndesis.integration.runtime.handlers.ExtensionStepHandlerTest$MyExtension::action")
                        .build())
                    .build())
                .putConfiguredProperty("param1", "Val-1")
                .putConfiguredProperty("param2", "Val-2")
                .build(),
            new io.syndesis.common.model.integration.Step.Builder()
                .id("step-3")
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("mock")
                        .putConfiguredProperty("name", "result")
                        .build())
                    .build())
                .build()
        );

        // Set up the camel context
        context.addRoutes(routeBuilder);
        context.setAutoStartup(false);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        List<RouteDefinition> routes = context.getRouteDefinitions();
        assertThat(routes).hasSize(1);

        RouteDefinition route = context.getRouteDefinitions().get(0);
        assertThat(route).isNotNull();
        assertThat(route.getInput()).isNotNull();
        assertThat(route.getInput()).hasFieldOrPropertyWithValue("uri", "direct:start");
        assertThat(route.getOutputs()).hasSize(5);
        assertThat(route.getOutputs().get(0)).isInstanceOf(PipelineDefinition.class);
        assertThat(route.getOutputs().get(0).getOutputs()).hasSize(2);
        assertThat(route.getOutputs().get(0).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(0).getOutputs().get(1)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(1)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(2)).isInstanceOf(ProcessDefinition.class);
        assertThat(route.getOutputs().get(3)).isInstanceOf(PipelineDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs()).hasSize(3);
        assertThat(route.getOutputs().get(3).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs().get(1)).isInstanceOf(ToDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs().get(1)).hasFieldOrPropertyWithValue(
            "uri",
            "class:io.syndesis.integration.runtime.handlers.ExtensionStepHandlerTest$MyExtension?method=action&bean.param1=Val-1&bean.param2=Val-2"
        );
        assertThat(route.getOutputs().get(3).getOutputs().get(2)).isInstanceOf(ProcessDefinition.class);
        assertThat(route.getOutputs().get(4)).isInstanceOf(PipelineDefinition.class);
        assertThat(route.getOutputs().get(4).getOutputs()).hasSize(3);
        assertThat(route.getOutputs().get(4).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(4).getOutputs().get(1)).isInstanceOf(ToDefinition.class);
        assertThat(route.getOutputs().get(4).getOutputs().get(1)).hasFieldOrPropertyWithValue("uri", "mock:result");
        assertThat(route.getOutputs().get(4).getOutputs().get(2)).isInstanceOf(ProcessDefinition.class);
    } finally {
        context.stop();
    }
}
 
Example 15
Source File: DataMapperStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testJsonTypeProcessors() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder routeBuilder = newIntegrationRouteBuilder(getTestSteps("{" +
                                "\"AtlasMapping\":{" +
                                    "\"dataSource\":[" +
                                        "{\"jsonType\":\"" + DataMapperStepHandler.ATLASMAP_JSON_DATA_SOURCE + "\",\"id\":\"source\",\"uri\":\"atlas:json:source\",\"dataSourceType\":\"SOURCE\"}," +
                                        "{\"jsonType\":\"" + DataMapperStepHandler.ATLASMAP_JSON_DATA_SOURCE + "\",\"id\":\"target\",\"uri\":\"atlas:json:target\",\"dataSourceType\":\"TARGET\",\"template\":null}" +
                                    "]," +
                                    "\"mappings\":{}" +
                                    "}" +
                                "}"));

        // Set up the camel context
        context.addRoutes(routeBuilder);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        List<RouteDefinition> routes = context.getRouteDefinitions();
        assertThat(routes).hasSize(1);

        RouteDefinition route = context.getRouteDefinitions().get(0);
        assertThat(route).isNotNull();
        assertThat(route.getInput()).isNotNull();
        assertThat(route.getInput()).hasFieldOrPropertyWithValue("uri", "direct:start");
        assertThat(route.getOutputs()).hasSize(5);
        assertThat(route.getOutputs().get(0)).isInstanceOf(PipelineDefinition.class);
        assertThat(route.getOutputs().get(0).getOutputs()).hasSize(2);
        assertThat(route.getOutputs().get(0).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(0).getOutputs().get(1)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(1)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(2)).isInstanceOf(ProcessDefinition.class);

        // Atlas
        assertThat(route.getOutputs().get(3)).isInstanceOf(PipelineDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs()).hasSize(5);
        assertThat(route.getOutputs().get(3).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs().get(1)).isInstanceOf(ProcessDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs().get(2)).isInstanceOf(ToDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs().get(2)).hasFieldOrPropertyWithValue(
                "uri",
                "atlas:mapping-flow-0-step-1.json?encoding=UTF-8&sourceMapName=" + OutMessageCaptureProcessor.CAPTURED_OUT_MESSAGES_MAP
        );
        assertThat(route.getOutputs().get(3).getOutputs().get(3)).isInstanceOf(ProcessDefinition.class);
        assertThat(route.getOutputs().get(3).getOutputs().get(4)).isInstanceOf(ProcessDefinition.class);
        assertThat(route.getOutputs().get(4)).isInstanceOf(PipelineDefinition.class);
        assertThat(route.getOutputs().get(4).getOutputs()).hasSize(3);
        assertThat(route.getOutputs().get(4).getOutputs().get(0)).isInstanceOf(SetHeaderDefinition.class);
        assertThat(route.getOutputs().get(4).getOutputs().get(1)).isInstanceOf(ToDefinition.class);
        assertThat(route.getOutputs().get(4).getOutputs().get(1)).hasFieldOrPropertyWithValue("uri", "mock:result");
        assertThat(route.getOutputs().get(4).getOutputs().get(2)).isInstanceOf(ProcessDefinition.class);
    } finally {
        context.stop();
    }
}
 
Example 16
Source File: SplitStepHandlerJsonTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
/**
 * Test subsequent split/aggregate where a 1st split operates on a initial collection of elements and a
 * 2nd split operates on a completely new collection provided by some mock endpoint.
 * direct -> split -> log -> aggregate -> bean:myMock -> split -> log -> aggregate -> mock
 */
@Test
public void testSubsequentSplitAggregate() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder routes = new IntegrationRouteBuilder(
                "classpath:/syndesis/integration/subsequent-split.json",
                Resources.loadServices(IntegrationStepHandler.class)
        );

        // Set up the camel context
        context.addRoutes(routes);

        SimpleRegistry beanRegistry = new SimpleRegistry();
        beanRegistry.bind("bodyLogger", new BodyLogger.Default());
        beanRegistry.bind("myMock", (Processor) exchange -> exchange.getIn().setBody(Arrays.asList("d", "e", "f")));
        context.setRegistry(beanRegistry);

        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:expression", MockEndpoint.class);
        final List<String> body = Arrays.asList("a", "b", "c");

        result.expectedMessageCount(1);

        template.sendBody("direct:expression", body);

        result.assertIsSatisfied();
        List<?> bodyReceived = result.getExchanges().get(0).getIn().getBody(List.class);
        assertThat(bodyReceived).hasSize(3);
        assertThat(bodyReceived.get(0)).isEqualTo("d");
        assertThat(bodyReceived.get(1)).isEqualTo("e");
        assertThat(bodyReceived.get(2)).isEqualTo("f");
    } finally {
        context.stop();
    }
}
 
Example 17
Source File: ChoiceStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testChoiceStepNoConfiguredFlows() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder integrationRoute = newIntegrationRouteBuilder(activityTracker,
                new Step.Builder()
                        .id(START_STEP)
                        .stepKind(StepKind.endpoint)
                        .action(new ConnectorAction.Builder()
                                .descriptor(new ConnectorDescriptor.Builder()
                                        .componentScheme("direct")
                                        .putConfiguredProperty("name", "flow")
                                        .build())
                                .build())
                        .build(),
                new Step.Builder()
                        .id(CHOICE_STEP)
                        .stepKind(StepKind.choice)
                        .build(),
                new Step.Builder()
                        .id(MOCK_STEP)
                        .stepKind(StepKind.endpoint)
                        .action(new ConnectorAction.Builder()
                                .descriptor(new ConnectorDescriptor.Builder()
                                        .componentScheme("mock")
                                        .putConfiguredProperty("name", "result")
                                        .build())
                                .build())
                        .build()
        );

        // Set up the camel context
        context.setUuidGenerator(KeyGenerator::createKey);
        context.addLogListener(new IntegrationLoggingListener(activityTracker));
        context.addInterceptStrategy(new ActivityTrackingInterceptStrategy(activityTracker));
        context.addRoutes(integrationRoute);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:result", MockEndpoint.class);

        final List<String> messages = Arrays.asList("Hello Camel!", "Bye Camel!", "And Now for Something Completely Different");

        result.expectedBodiesReceived(messages);

        for (String message : messages) {
            template.sendBody("direct:flow", message);
        }

        result.assertIsSatisfied();

        verify(activityTracker, times(3)).startTracking(any(Exchange.class));
        verifyActivityStepTracking(CHOICE_STEP, 3);
        verifyActivityStepTracking(MOCK_STEP, 3);
        verify(activityTracker, times(3)).finishTracking(any(Exchange.class));

    } finally {
        context.stop();
    }
}
 
Example 18
Source File: GRPCIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testGRPCAsynchronousProducer() throws Exception {

    Future<String> future = AvailablePortFinder.readServerDataAsync("grpc-port");
    int port = Integer.parseInt(future.get(10, TimeUnit.SECONDS));

    DefaultCamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .toF("grpc://localhost:%d/%s?method=pingAsyncSync", port, "org.wildfly.camel.test.grpc.subA.PingPong");
        }
    });

    camelctx.start();
    try {
        final CountDownLatch latch = new CountDownLatch(1);

        PingRequest pingRequest = PingRequest.newBuilder()
            .setPingName(GRPC_TEST_PING_VALUE)
            .setPingId(GRPC_TEST_PING_ID_1)
            .build();

        ProducerTemplate template = camelctx.createProducerTemplate();
        template.asyncCallbackSendBody("direct:start", pingRequest, new SynchronizationAdapter() {
            @Override
            public void onComplete(Exchange exchange) {
                latch.countDown();

                @SuppressWarnings("unchecked")
                List<PongResponse> response = exchange.getOut().getBody(List.class);

                Assert.assertEquals(2, response.size());
                Assert.assertEquals(response.get(0).getPongId(), GRPC_TEST_PONG_ID_1);
                Assert.assertEquals(response.get(0).getPongName(), GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE);
                Assert.assertEquals(response.get(1).getPongId(), GRPC_TEST_PONG_ID_2);
            }
        });

        Assert.assertTrue("Gave up waiting for latch", latch.await(5, TimeUnit.SECONDS));
    } finally {
        camelctx.close();
    }
}
 
Example 19
Source File: SplitAggregateStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSplitAggregateScriptAggregationStrategy() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder routes = newIntegrationRouteBuilder(activityTracker,
            new Step.Builder()
                .id(START_STEP)
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("direct")
                        .putConfiguredProperty("name", "expression")
                        .build())
                    .build())
                .build(),
            new Step.Builder()
                .id(SPLIT_STEP)
                .stepKind(StepKind.split)
                .putConfiguredProperty("language", "tokenize")
                .putConfiguredProperty("expression", "|")
                .putConfiguredProperty("aggregationStrategy", "script")
                .putConfiguredProperty("aggregationScriptLanguage", "nashorn")
                .putConfiguredProperty("aggregationScript", "newExchange.in.body += oldExchange ? oldExchange.in.body : '';\n" +
                        "newExchange;")
                .build(),
            new Step.Builder()
                .id(MOCK_STEP)
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("mock")
                        .putConfiguredProperty("name", "split")
                        .build())
                    .build())
                .build(),
            new Step.Builder()
                .id(AGGREGATE_STEP)
                .stepKind(StepKind.aggregate)
                .build()
        );

        // Set up the camel context
        context.setUuidGenerator(KeyGenerator::createKey);
        context.addLogListener(new IntegrationLoggingListener(activityTracker));
        context.addInterceptStrategy(new ActivityTrackingInterceptStrategy(activityTracker));
        context.addRoutes(routes);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:split", MockEndpoint.class);
        final String body = "a|b|c";

        result.expectedBodiesReceived((Object[])body.split("|"));

        String response = template.requestBody("direct:expression", body, String.class);

        result.assertIsSatisfied();
        Assert.assertEquals("c|b|a", response);

        verify(activityTracker).startTracking(any(Exchange.class));
        verifyActivityStepTracking(START_STEP, 1);
        verifyActivityStepTracking(SPLIT_STEP, 0);
        verifyActivityStepTracking(MOCK_STEP, 5);
        verifyActivityStepTracking(AGGREGATE_STEP, 0);
        verify(activityTracker, times(6)).track(eq("exchange"), anyString(), eq("step"), anyString(), eq("id"), anyString(), eq("duration"), anyLong(), eq("failure"), isNull());
        verify(activityTracker).finishTracking(any(Exchange.class));
    } finally {
        context.stop();
    }
}
 
Example 20
Source File: ChoiceStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testChoiceStep() throws Exception {
    final DefaultCamelContext context = new DefaultCamelContext();

    try {
        final RouteBuilder integrationRoute = newIntegrationRouteBuilder(activityTracker,
            new Step.Builder()
                .id(START_STEP)
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("direct")
                        .putConfiguredProperty("name", "flow")
                        .build())
                    .build())
                .build(),
            new Step.Builder()
                .id(CHOICE_STEP)
                .stepKind(StepKind.choice)
                .putConfiguredProperty("flows", "[" +
                                    "{\"condition\": \"${body} contains 'Hello'\", \"flow\": \"hello-flow\"}," +
                                    "{\"condition\": \"${body} contains 'Bye'\", \"flow\": \"bye-flow\"}" +
                                "]")
                .build(),
            new Step.Builder()
                .id(MOCK_STEP)
                .stepKind(StepKind.endpoint)
                .action(new ConnectorAction.Builder()
                    .descriptor(new ConnectorDescriptor.Builder()
                        .componentScheme("mock")
                        .putConfiguredProperty("name", "result")
                        .build())
                    .build())
                .build()
        );

        final RouteBuilder helloRoute = new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:hello-flow")
                        .to("mock:hello");
            }
        };

        final RouteBuilder byeRoute = new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:bye-flow")
                        .to("mock:bye");
            }
        };

        // Set up the camel context
        context.setUuidGenerator(KeyGenerator::createKey);
        context.addLogListener(new IntegrationLoggingListener(activityTracker));
        context.addInterceptStrategy(new ActivityTrackingInterceptStrategy(activityTracker));
        context.addRoutes(helloRoute);
        context.addRoutes(byeRoute);
        context.addRoutes(integrationRoute);

        SimpleRegistry beanRegistry = new SimpleRegistry();
        beanRegistry.bind("bodyLogger", new BodyLogger.Default());
        context.setRegistry(beanRegistry);
        context.start();

        // Dump routes as XML for troubleshooting
        dumpRoutes(context);

        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:result", MockEndpoint.class);
        final MockEndpoint helloResult = context.getEndpoint("mock:hello", MockEndpoint.class);
        final MockEndpoint byeResult = context.getEndpoint("mock:bye", MockEndpoint.class);

        final List<String> messages = Arrays.asList("Hello Camel!", "Bye Camel!", "And Now for Something Completely Different");

        result.expectedBodiesReceived(messages);
        helloResult.expectedBodiesReceived("Hello Camel!");
        byeResult.expectedBodiesReceived("Bye Camel!");

        for (String message : messages) {
            template.sendBody("direct:flow", message);
        }

        result.assertIsSatisfied();
        helloResult.assertIsSatisfied();
        byeResult.assertIsSatisfied();

        verify(activityTracker, times(3)).startTracking(any(Exchange.class));
        verifyActivityStepTracking(CHOICE_STEP, 3);
        verifyActivityStepTracking(MOCK_STEP, 3);
        verify(activityTracker, times(3)).finishTracking(any(Exchange.class));
    } finally {
        context.stop();
    }
}