Java Code Examples for org.apache.camel.component.mock.MockEndpoint#expectedBodiesReceived()

The following examples show how to use org.apache.camel.component.mock.MockEndpoint#expectedBodiesReceived() . 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: SplitExceptionHandlingSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemainderElementsProcessedOnException() throws Exception {
    String[] array = new String[]{"one", "two", "three"};

    MockEndpoint mockSplit = getMockEndpoint("mock:split");
    mockSplit.expectedMessageCount(2);
    mockSplit.expectedBodiesReceived("two", "three");

    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.expectedMessageCount(0);

    try {
        template.sendBody("direct:in", array);
        fail("Exception not thrown");
    } catch (CamelExecutionException ex) {
        assertTrue(ex.getCause() instanceof IllegalStateException);
        assertMockEndpointsSatisfied();
    }
}
 
Example 2
Source File: AggregateABCEagerTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testABCEND() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    // we expect ABC in the published message
    // notice: Only 1 message is expected
    mock.expectedBodiesReceived("ABC");

    // send the first message
    template.sendBodyAndHeader("direct:start", "A", "myId", 1);
    // send the 2nd message with the same correlation key
    template.sendBodyAndHeader("direct:start", "B", "myId", 1);
    // the F message has another correlation key
    template.sendBodyAndHeader("direct:start", "F", "myId", 2);
    // now we have 3 messages with the same correlation key
    // and the Aggregator should publish the message
    template.sendBodyAndHeader("direct:start", "C", "myId", 1);
    // and now the END message to trigger completion
    template.sendBodyAndHeader("direct:start", "END", "myId", 1);

    assertMockEndpointsSatisfied();
}
 
Example 3
Source File: MicrometerTimerIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testOverrideMetricsName() throws Exception {
    CamelContext camelctx = createCamelContext();
    camelctx.start();
    try {
        Object body = new Object();

        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:out", MockEndpoint.class);
        mockEndpoint.expectedBodiesReceived(body);

        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:in-1", body);

        Timer timer = metricsRegistry.find("B").timer();
        Assert.assertEquals(1L, timer.count());
        Assert.assertTrue(timer.max(TimeUnit.MILLISECONDS) > 0.0D);
        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 4
Source File: DirectVMSpringIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpringDirectVMComponent() throws Exception {
    CamelContext camelctxA = contextRegistry.getCamelContext("direct-vm-context-a");
    Assert.assertEquals(ServiceStatus.Started, camelctxA.getStatus());

    CamelContext camelctxB = contextRegistry.getCamelContext("direct-vm-context-b");
    Assert.assertEquals(ServiceStatus.Started, camelctxB.getStatus());

    MockEndpoint mockEndpoint = camelctxB.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedBodiesReceived("Hello Kermit");

    ProducerTemplate template = camelctxA.createProducerTemplate();
    template.sendBody("direct:start", "Kermit");

    mockEndpoint.assertIsSatisfied();
}
 
Example 5
Source File: OutboundEndpointTest.java    From vertx-camel-bridge with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithSeveralEndpoints() throws Exception {
  MockEndpoint endpoint = (MockEndpoint) camel.getComponent("mock").createEndpoint("mock:foo");
  MockEndpoint endpoint2 = (MockEndpoint) camel.getEndpoint("mock:foo2");

  camel.addEndpoint("output", endpoint);
  camel.addEndpoint("output2", endpoint2);

  bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel)
      .addOutboundMapping(fromVertx("test").toCamel("output"))
      .addOutboundMapping(fromVertx("test").setEndpoint(endpoint2))
  );

  camel.start();
  BridgeHelper.startBlocking(bridge);

  vertx.eventBus().publish("test", "hello");
  vertx.eventBus().publish("test", "hello2");

  await().atMost(DEFAULT_TIMEOUT).until(() -> endpoint.getExchanges().size() == 2);
  await().atMost(DEFAULT_TIMEOUT).until(() -> endpoint2.getExchanges().size() == 2);

  endpoint.expectedBodiesReceived("hello", "hello2");
  endpoint2.expectedBodiesReceived("hello", "hello2");
}
 
Example 6
Source File: XTokenizeLanguageIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testXTokenize() throws Exception {
    Namespaces ns = new Namespaces("C", "urn:c");

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .split().xtokenize("//C:child", ns)
            .to("mock:result");
        }
    });

    camelctx.start();
    try {
        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        mockEndpoint.expectedBodiesReceived("<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\"></c:child>", "<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\"></c:child>");

        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", XML);

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 7
Source File: UndertowWsIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void wsClientSingleText() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            final int port = getPort();
            from("undertow:ws://localhost:" + port + "/app1")
                    .log(">>> Message received from WebSocket Client : ${body}").to("mock:result1");
        }

    });

    camelctx.start();
    try {
        TestClient websocket = new TestClient("ws://localhost:" + getPort() + "/app1").connect();

        MockEndpoint result = camelctx.getEndpoint("mock:result1", MockEndpoint.class);
        result.expectedBodiesReceived("Test");

        websocket.sendTextMessage("Test");

        result.await(60, TimeUnit.SECONDS);
        result.assertIsSatisfied();

        websocket.close();
    } finally {
        camelctx.close();
    }

}
 
Example 8
Source File: AggregateABCCloseTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Test
public void testABCClose() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    // we expect ABC in the published message
    // notice: Only 1 message is expected
    mock.expectedBodiesReceived("ABC");

    // send the first message
    template.sendBodyAndHeader("direct:start", "A", "myId", 1);
    // send the 2nd message with the same correlation key
    template.sendBodyAndHeader("direct:start", "B", "myId", 1);
    // the F message has another correlation key
    template.sendBodyAndHeader("direct:start", "F", "myId", 2);
    // now we have 3 messages with the same correlation key
    // and the Aggregator should publish the message
    template.sendBodyAndHeader("direct:start", "C", "myId", 1);

    // sending with correlation id 1 should fail as its closed
    try {
        template.sendBodyAndHeader("direct:start", "A2", "myId", 1);
    } catch (CamelExecutionException e) {
        ClosedCorrelationKeyException cause = assertIsInstanceOf(ClosedCorrelationKeyException.class, e.getCause());
        assertEquals("1", cause.getCorrelationKey());
    }

    assertMockEndpointsSatisfied();
}
 
Example 9
Source File: SpringAggregateABCTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testABC() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived("ABC");

    template.sendBodyAndHeader("direct:start", "A", "myId", 1);
    template.sendBodyAndHeader("direct:start", "B", "myId", 1);
    template.sendBodyAndHeader("direct:start", "F", "myId", 2);
    template.sendBodyAndHeader("direct:start", "C", "myId", 1);

    assertMockEndpointsSatisfied();
}
 
Example 10
Source File: SpringFailoverInheritErrorHandlerLoadBalancerTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadBalancer() throws Exception {
    // simulate error when sending to service A
    context.getRouteDefinition("start").adviceWith(context, new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("direct:a")
                .choice()
                    .when(body().contains("Kaboom"))
                        .throwException(new IllegalArgumentException("Damn"))
                    .end()
                .end();
        }
    });
    context.start();

    // A should get the 1st
    MockEndpoint a = getMockEndpoint("mock:a");
    a.expectedBodiesReceived("Hello");

    // B should get the 2nd
    MockEndpoint b = getMockEndpoint("mock:b");
    b.expectedBodiesReceived("Kaboom");

    // send in 2 messages
    template.sendBody("direct:start", "Hello");
    template.sendBody("direct:start", "Kaboom");

    assertMockEndpointsSatisfied();
}
 
Example 11
Source File: SpringTransformScriptTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransform() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived("Hello Camel how are you?");

    template.sendBody("direct:start", "Camel");

    assertMockEndpointsSatisfied();
}
 
Example 12
Source File: SplitTokenizeTest.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public void testSplitTokenizerD() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:split");
    mock.expectedBodiesReceived("[Claus]", "[James]", "[Willem]");

    template.sendBody("direct:d", "[Claus][James][Willem]");

    assertMockEndpointsSatisfied();
}
 
Example 13
Source File: SpringSecurityHeadersSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecuredServiceAccess() throws InterruptedException {
    MockEndpoint mockSecure = getMockEndpoint("mock:secure");
    mockSecure.setExpectedMessageCount(1);
    mockSecure.expectedBodiesReceived("foo");

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("username", "jakub");
    headers.put("password", "supersecretpassword1");
    template.sendBodyAndHeaders("direct:in", "foo", headers);

    assertMockEndpointsSatisfied();
}
 
Example 14
Source File: DefaultErrorHandlerTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderOk() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:queue.order");
    mock.expectedBodiesReceived("amount=1,name=Camel in Action,id=123,status=OK");

    template.sendBody("seda:queue.inbox","amount=1,name=Camel in Action");

    assertMockEndpointsSatisfied();
}
 
Example 15
Source File: SplitXmlTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitArray() throws Exception {
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.expectedMessageCount(2);
    mockOut.expectedBodiesReceived("Scott Cranton", "Jakub Korab");

    String filename = "target/classes/xml/books.xml";
    assertFileExists(filename);
    InputStream booksStream = new FileInputStream(filename);

    template.sendBody("direct:in", booksStream);

    assertMockEndpointsSatisfied();
}
 
Example 16
Source File: SimulateErrorUsingProcessorJava8Test.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimulateErrorUsingProcessor() throws Exception {
    getMockEndpoint("mock:http").expectedMessageCount(0);

    MockEndpoint ftp = getMockEndpoint("mock:ftp");
    ftp.expectedBodiesReceived("Camel rocks");

    template.sendBody("direct:file", "Camel rocks");

    assertMockEndpointsSatisfied();
}
 
Example 17
Source File: HelloWorldEmbeddedSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostBye() throws Exception {
    final String json = "{ \"name\": \"Scott\" }";

    MockEndpoint update = getMockEndpoint("mock:update");
    update.expectedBodiesReceived(json);

    fluentTemplate().to("undertow:http://localhost:" + port1 + "/say/bye")
            .withHeader(Exchange.HTTP_METHOD, "POST")
            .withHeader(Exchange.CONTENT_ENCODING, "application/json")
            .withBody(json)
            .send();

    assertMockEndpointsSatisfied();
}
 
Example 18
Source File: FilterStepHandlerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testExpressionFilterStepOnArray() 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", "start")
                                        .build())
                                .build())
                        .build(),
                new Step.Builder()
                        .id(FILTER_STEP)
                        .stepKind(StepKind.expressionFilter)
                        .putConfiguredProperty("filter", "${body.size()} > 0 && ${body[0].name} == 'James'")
                        .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(routes);
        context.start();

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

        final List<String> matchingMessages = Collections.singletonList(buildPersonJsonArray("James"));
        final List<String> notMatchingMessages = Arrays.asList(buildPersonJsonArray(),
                                                               buildPersonJsonArray("Jimmi"));
        final ProducerTemplate template = context.createProducerTemplate();
        final MockEndpoint result = context.getEndpoint("mock:result", MockEndpoint.class);

        List<String> allMessages = new ArrayList<>();
        allMessages.addAll(matchingMessages);
        allMessages.addAll(notMatchingMessages);

        result.expectedBodiesReceived(matchingMessages);

        for (Object body : allMessages) {
            template.sendBody("direct:start", body);
        }

        result.assertIsSatisfied();

        verify(activityTracker, times(allMessages.size())).startTracking(any(Exchange.class));
        verifyActivityStepTracking(MOCK_STEP, matchingMessages.size());
        verifyActivityStepTracking(FILTER_STEP, allMessages.size());
        verify(activityTracker, times(allMessages.size())).finishTracking(any(Exchange.class));
    } finally {
        context.stop();
    }
}
 
Example 19
Source File: AzureIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testAppendBlob() throws Exception {

    StorageCredentials creds = getStorageCredentials("camelblob", System.getenv(AZURE_STORAGE_BLOB));
    Assume.assumeNotNull("Credentials not null", creds);

    CamelContext camelctx = createCamelContext(creds);
    camelctx.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            from("direct:start")
            .to("azure-blob://camelblob/container1/blobAppend?credentials=#creds&operation=updateAppendBlob");

            from("azure-blob://camelblob/container1/blobAppend?credentials=#creds&blobType=appendblob")
            .to("mock:read");

            from("direct:list")
            .to("azure-blob://camelblob/container1?credentials=#creds&operation=listBlobs");
        }
    });

    camelctx.start();
    try {
        MockEndpoint mockRead = camelctx.getEndpoint("mock:read", MockEndpoint.class);
        mockRead.expectedBodiesReceived("Append Blob");
        mockRead.expectedMessageCount(1);

        ProducerTemplate producer = camelctx.createProducerTemplate();

        Iterator<?> it = producer.requestBody("direct:list", null, Iterable.class).iterator();
        Assert.assertFalse("No Blob exists", it.hasNext());

        // append to blob
        producer.sendBody("direct:start", "Append Blob");
        mockRead.assertIsSatisfied();

        it = producer.requestBody("direct:list", null, Iterable.class).iterator();
        Assert.assertTrue("Blob exists", it.hasNext());
        CloudBlob blob = (CloudAppendBlob) it.next();
        blob.delete();

        it = producer.requestBody("direct:list", null, Iterable.class).iterator();
        Assert.assertFalse("No Blob exists", it.hasNext());

    } finally {
        camelctx.close();
    }
}
 
Example 20
Source File: CryptoCmsIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testCryptoCmsSignEncryptDecryptVerify() throws Exception {
    Assume.assumeFalse("[#2241] CryptoCmsIntegrationTest fails on IBM JDK", EnvironmentUtils.isIbmJDK() || EnvironmentUtils.isOpenJDK());

    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("crypto-cms:sign://testsign?signer=#signer1,signer=#signer2&includeContent=true")
            .to("crypto-cms:encrypt://testencrpyt?toBase64=true&recipient=#recipient1&contentEncryptionAlgorithm=DESede/CBC/PKCS5Padding&secretKeyLength=128")
            .to("crypto-cms:decrypt://testdecrypt?fromBase64=true&keyStoreParameters=#keyStoreParameters")
            .to("crypto-cms:verify://testverify?keyStoreParameters=#keyStoreParameters")
            .to("mock:result");
        }
    });

    KeyStoreParameters keyStoreParameters = new KeyStoreParameters();
    keyStoreParameters.setType("JCEKS");
    keyStoreParameters.setResource("/crypto.keystore");
    keyStoreParameters.setPassword("Abcd1234");

    DefaultKeyTransRecipientInfo recipient = new DefaultKeyTransRecipientInfo();
    recipient.setCertificateAlias("rsa");
    recipient.setKeyStoreParameters(keyStoreParameters);

    DefaultSignerInfo signerInfo = new DefaultSignerInfo();
    signerInfo.setIncludeCertificates(true);
    signerInfo.setSignatureAlgorithm("SHA256withRSA");
    signerInfo.setPrivateKeyAlias("rsa");
    signerInfo.setKeyStoreParameters(keyStoreParameters);

    DefaultSignerInfo signerInfo2 = new DefaultSignerInfo();
    signerInfo2.setSignatureAlgorithm("SHA256withDSA");
    signerInfo2.setPrivateKeyAlias("dsa");
    signerInfo2.setKeyStoreParameters(keyStoreParameters);

    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedBodiesReceived("Testmessage");

    context.bind("keyStoreParameters", keyStoreParameters);
    context.bind("signer1", signerInfo);
    context.bind("signer2", signerInfo2);
    context.bind("recipient1", recipient);

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", "Testmessage");

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
        context.unbind("keyStoreParameters");
        context.unbind("signer1");
        context.unbind("signer2");
        context.unbind("recipient1");
    }
}