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

The following examples show how to use org.apache.camel.component.mock.MockEndpoint#setExpectedMessageCount() . 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: OnCompletionMultipleTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnCompletionDefinedAtRouteLevel() throws InterruptedException {
    // this block is defined first, the definition of the failure only will be considered
    MockEndpoint mockCompleted = getMockEndpoint("mock:completed");
    mockCompleted.setExpectedMessageCount(0);

    MockEndpoint mockFailed = getMockEndpoint("mock:failed");
    mockFailed.setExpectedMessageCount(0);

    // neither of the global completion blocks should be triggered
    MockEndpoint mockGlobalCompleted = getMockEndpoint("mock:globalCompleted");
    mockGlobalCompleted.setExpectedMessageCount(0);

    MockEndpoint mockGlobalFailed = getMockEndpoint("mock:globalFailed");
    mockGlobalFailed.setExpectedMessageCount(0);

    template.asyncSendBody("direct:in", "this message should be fine");

    assertMockEndpointsSatisfied();
}
 
Example 2
Source File: TransactionPolicySpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess() throws InterruptedException {
    AuditLogDao auditLogDao = getMandatoryBean(AuditLogDao.class, "auditLogDao");
    MessageDao messageDao = getMandatoryBean(MessageDao.class, "messageDao");

    String message = "ping";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockOut1 = getMockEndpoint("mock:out1");
    mockOut1.setExpectedMessageCount(1);
    mockOut1.message(0).body().isEqualTo(message);

    MockEndpoint mockOut2 = getMockEndpoint("mock:out2");
    mockOut2.setExpectedMessageCount(1);
    mockOut2.message(0).body().isEqualTo(message);

    template.sendBody("direct:policies", message);

    assertMockEndpointsSatisfied();
    assertEquals(1, auditLogDao.getAuditCount(message));
    assertEquals(1, messageDao.getMessageCount(message));
}
 
Example 3
Source File: TransactionPolicyTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureMock2() throws InterruptedException {
    String message = "ping";
    assertEquals(0, auditLogDao.getAuditCount(message));

    MockEndpoint mockOut1 = getMockEndpoint("mock:out1");
    mockOut1.setExpectedMessageCount(1);
    mockOut1.message(0).body().isEqualTo(message);

    MockEndpoint mockOut2 = getMockEndpoint("mock:out2");
    mockOut2.whenAnyExchangeReceived(new ExceptionThrowingProcessor());

    try {
        template.sendBody("direct:policies", message);
        fail();
    } catch (Exception e) {
        assertEquals("boom!", ExceptionUtils.getRootCause(e).getMessage());
    }

    assertMockEndpointsSatisfied();
    assertEquals(1, auditLogDao.getAuditCount(message));
    assertEquals(0, messageDao.getMessageCount(message));
}
 
Example 4
Source File: UndertowIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testUndertowConsumerPrefixPath() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("undertow:http://localhost/foo/bar?matchOnUriPrefix=true")
            .to("mock:result");
        }
    });
    try {
        camelctx.start();

        MockEndpoint endpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        endpoint.setExpectedMessageCount(3);

        HttpRequest.get("http://localhost:8080/foo").throwExceptionOnFailure(false).getResponse();
        HttpRequest.get("http://localhost:8080/foo/bar").getResponse();
        HttpRequest.get("http://localhost:8080/foo/bar/hello").getResponse();
        HttpRequest.get("http://localhost:8080/foo/bar/hello/world").getResponse();

        endpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 5
Source File: MailIntegrationCDITest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testMailEndpointWithCDIContext() throws Exception {
    CamelContext camelctx = contextRegistry.getCamelContext("camel-mail-cdi-context");
    Assert.assertNotNull("Camel context not null", camelctx);

    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.setExpectedMessageCount(1);

    Map<String, Object> mailHeaders = new HashMap<>();
    mailHeaders.put("from", "user1@localhost");
    mailHeaders.put("to", "user2@localhost");
    mailHeaders.put("message", "Hello Kermit");

    ProducerTemplate template = camelctx.createProducerTemplate();
    template.requestBodyAndHeaders("direct:start", null, mailHeaders);

    mockEndpoint.assertIsSatisfied(5000);
}
 
Example 6
Source File: SplitParallelProcessingTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testSplittingInParallel() throws InterruptedException {
    List<String> messageFragments = new ArrayList<String>();
    int fragmentCount = 50;
    for (int i = 0; i < fragmentCount; i++) {
        messageFragments.add("fragment" + i);
    }
    MockEndpoint mockSplit = getMockEndpoint("mock:split");
    mockSplit.setExpectedMessageCount(fragmentCount);
    mockSplit.expectedBodiesReceivedInAnyOrder(messageFragments);

    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(1);
    mockOut.message(0).body().isEqualTo(messageFragments);

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

    assertMockEndpointsSatisfied();
}
 
Example 7
Source File: MailIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMailEndpoint() throws Exception {

    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("smtp://localhost:10025?session=#java:jboss/mail/greenmail");

            from("pop3://user2@localhost:10110?delay=1000&session=#java:jboss/mail/greenmail&delete=true")
            .to("mock:result");
        }
    });

    try {
        deployer.deploy(GREENMAIL_WAR);

        camelctx.start();

        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        mockEndpoint.setExpectedMessageCount(1);

        Map<String, Object> mailHeaders = new HashMap<>();
        mailHeaders.put("from", "user1@localhost");
        mailHeaders.put("to", "user2@localhost");
        mailHeaders.put("message", "Hello Kermit");

        ProducerTemplate template = camelctx.createProducerTemplate();
        template.requestBodyAndHeaders("direct:start", null, mailHeaders);

        mockEndpoint.assertIsSatisfied(5000);
    } finally {
        camelctx.close();
        deployer.undeploy(GREENMAIL_WAR);
    }
}
 
Example 8
Source File: SecurityAsymNamespacesSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testXmlEncryptionDecryption() throws Exception {
    final Namespaces namespaces = new Namespaces("c", "http://camelcookbook.org/schema/booksignings");
    final String cityExistsXPath = "/c:booksignings/c:store/c:address/c:city";

    context.getRouteDefinition("encrypt")
        .adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                interceptSendToEndpoint("direct:decrypt")
                    .when(namespaces.xpath(cityExistsXPath))
                        .to("mock:incorrectlyEncrypted");
            }
        });
    context.getRouteDefinition("decrypt")
        .adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                interceptSendToEndpoint("mock:out")
                    .when(namespaces.xpath(cityExistsXPath))
                        .to("mock:correctlyDecrypted");
            }
        });
    context.start();

    MockEndpoint mockIncorrectlyEncrypted = getMockEndpoint("mock:incorrectlyEncrypted");
    mockIncorrectlyEncrypted.setExpectedMessageCount(0);
    MockEndpoint mockCorrectlyDecrypted = getMockEndpoint("mock:correctlyDecrypted");
    mockCorrectlyDecrypted.setExpectedMessageCount(1);
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(1);

    final InputStream resource = getClass().getClassLoader().getResourceAsStream("booklocations-ns.xml");
    final String request = context().getTypeConverter().convertTo(String.class, resource);

    template.sendBody("direct:encrypt", request);
    assertMockEndpointsSatisfied();
}
 
Example 9
Source File: EndpointConsumersSedaSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelConsumption() throws InterruptedException {
    final int messageCount = 100;
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(messageCount);
    mockOut.setResultWaitTime(5000);

    for (int i = 0; i < messageCount; i++) {
        template.sendBody("seda:in", "Message[" + i + "]");
    }

    assertMockEndpointsSatisfied();
}
 
Example 10
Source File: RollbackMarkRollbackOnlyTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactedRollback() throws InterruptedException {
    String message = "this message will explode";
    assertEquals(0, auditLogDao.getAuditCount(message));

    // the message does not proceed further down the route after the rollback statement
    MockEndpoint mockCompleted = getMockEndpoint("mock:out");
    mockCompleted.setExpectedMessageCount(0);

    // no exception is thrown despite the transaction rolling back
    template.sendBody("direct:transacted", message);

    assertMockEndpointsSatisfied();
    assertEquals(0, auditLogDao.getAuditCount(message)); // the insert was rolled back
}
 
Example 11
Source File: SecuritySpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testXmlEncryptionDecryption() throws Exception {
    final String cityExistsXPath = "/booksignings/store/address/city";

    context.getRouteDefinition("encrypt")
        .adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                interceptSendToEndpoint("direct:decrypt")
                    .when(xpath(cityExistsXPath))
                        .to("mock:incorrectlyEncrypted");
            }
        });
    context.getRouteDefinition("decrypt")
        .adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                interceptSendToEndpoint("mock:out")
                    .when(xpath(cityExistsXPath))
                        .to("mock:correctlyDecrypted");
            }
        });
    context.start();

    MockEndpoint mockIncorrectlyEncrypted = getMockEndpoint("mock:incorrectlyEncrypted");
    mockIncorrectlyEncrypted.setExpectedMessageCount(0);
    MockEndpoint mockCorrectlyDecrypted = getMockEndpoint("mock:correctlyDecrypted");
    mockCorrectlyDecrypted.setExpectedMessageCount(1);
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(1);

    final InputStream resource = getClass().getClassLoader().getResourceAsStream("booklocations.xml");
    final String request = context().getTypeConverter().convertTo(String.class, resource);

    template.sendBody("direct:encrypt", request);
    assertMockEndpointsSatisfied();
}
 
Example 12
Source File: SometimesAsyncProcessorTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncProcessing() throws InterruptedException {
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(messageCount);
    mockOut.setResultWaitTime(5000);

    for (int i = 0; i < messageCount; i++) {
        template.sendBodyAndHeader("seda:in", "Message[" + i + "]", "processAsync", false);
    }

    assertMockEndpointsSatisfied();
    Message message = mockOut.getExchanges().get(0).getIn();
    assertEquals(message.getHeader("initiatingThread"), message.getHeader("completingThread"));
}
 
Example 13
Source File: TikaIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void parseDocWithEmptyRegistryConfig() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(createRegistryWithEmptyConfig());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("tika:parse?tikaConfig=#testConfig").to("mock:result");
        }
    });
    MockEndpoint resultEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);

    try {
        camelctx.start();
        ProducerTemplate template = camelctx.createProducerTemplate();

        File document = new File("src/test/resources/tika/test.doc");
        template.sendBody("direct:start", document);

        resultEndpoint.setExpectedMessageCount(1);

        resultEndpoint.expectedMessagesMatches(new Predicate() {
            @Override
            public boolean matches(Exchange exchange) {
                Object body = exchange.getIn().getBody(String.class);
                Map<String, Object> headerMap = exchange.getIn().getHeaders();
                Assert.assertThat(body, instanceOf(String.class));
                Assert.assertThat((String) body, containsString("<body"));
                Assert.assertThat(headerMap.get(Exchange.CONTENT_TYPE), equalTo("application/msword"));
                return true;
            }
        });
        resultEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 14
Source File: IdempotentConsumerSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplayOfSameMessageWillNotTriggerCall() throws InterruptedException {
    MockEndpoint mockWs = getMockEndpoint("mock:ws");
    mockWs.setExpectedMessageCount(1);

    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(2);

    template.sendBodyAndHeader("direct:in", "Insert", "messageId", 1);
    template.sendBodyAndHeader("direct:in", "Insert", "messageId", 1); // again

    assertMockEndpointsSatisfied();
}
 
Example 15
Source File: AsyncProcessorSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncProcessing() throws InterruptedException {
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(messageCount);
    mockOut.setResultWaitTime(5000);

    for (int i = 0; i < messageCount; i++) {
        template.sendBody("seda:in", ExchangePattern.InOnly, "Message[" + i + "]");
    }

    assertMockEndpointsSatisfied();
}
 
Example 16
Source File: EncryptionSpringTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageEncryption() throws InterruptedException {
    MockEndpoint mockDecrypted = getMockEndpoint("mock:decrypted");
    mockDecrypted.setExpectedMessageCount(1);
    mockDecrypted.message(0).body().isEqualTo("foo");

    template.sendBody("direct:encrypt", "foo");

    assertMockEndpointsSatisfied();
}
 
Example 17
Source File: AggregateCompletionTimeoutTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testAggregation() throws InterruptedException {
    MockEndpoint mockOut = getMockEndpoint("mock:out");
    mockOut.setExpectedMessageCount(2);

    template.sendBodyAndHeader("direct:in", "One", "group", "odd");
    template.sendBodyAndHeader("direct:in", "Two", "group", "even");
    template.sendBodyAndHeader("direct:in", "Three", "group", "odd");
    template.sendBodyAndHeader("direct:in", "Four", "group", "even");
    template.sendBodyAndHeader("direct:in", "Five", "group", "odd");
    template.sendBodyAndHeader("direct:in", "Six", "group", "even");
    template.sendBodyAndHeader("direct:in", "Seven", "group", "odd");
    template.sendBodyAndHeader("direct:in", "Eight", "group", "even");
    template.sendBodyAndHeader("direct:in", "Nine", "group", "odd");
    template.sendBodyAndHeader("direct:in", "Ten", "group", "even");

    assertMockEndpointsSatisfied();

    for (Exchange exchange : mockOut.getReceivedExchanges()) {
        @SuppressWarnings("unchecked")
        Set<String> set = Collections.checkedSet(exchange.getIn().getBody(Set.class), String.class);
        if (set.contains("One")) { // odd
            assertTrue(set.containsAll(Arrays.asList("One", "Three", "Five", "Seven", "Nine")));
        } else { // even
            assertTrue(set.containsAll(Arrays.asList("Two", "Four", "Six", "Eight", "Ten")));
        }
    }
}
 
Example 18
Source File: ODataUpdateTests.java    From syndesis with Apache License 2.0 4 votes vote down vote up
/**
 * Tests alternative key predicate that is a string value
 * @see https://github.com/syndesisio/syndesis/issues/5241
 */
@Test
public void testPatchODataRouteOnRefServer() throws Exception {
    Step directStep = createDirectStep();

    //
    // Ensure we are using our own individual RW URI so not to impinge
    // on other tests seeing as we're modifying data
    //
    String refServiceURI = getRealRefServiceUrl(REF_SERVICE_URI);
    Connector odataConnector = createODataConnector(new PropertyBuilder<String>()
                                                        .property(SERVICE_URI, refServiceURI));

    String resourcePath = "People";
    String keyPredicate = "russellwhyte";
    String nameProperty = "MiddleName";
    String originalName = queryProperty(refServiceURI, resourcePath, keyPredicate, nameProperty);

    Step odataStep = createODataStep(odataConnector, resourcePath);

    ObjectNode newProduct = OBJECT_MAPPER.createObjectNode();
    // Append time to ensure old name is different from new name
    String newMiddleName = "Quentin" + System.currentTimeMillis();
    newProduct.put(nameProperty, newMiddleName);
    newProduct.put(KEY_PREDICATE, keyPredicate);

    Step mockStep = createMockStep();
    Integration odataIntegration = createIntegration(directStep, odataStep, mockStep);

    RouteBuilder routes = newIntegrationRouteBuilder(odataIntegration);
    context.addRoutes(routes);

    MockEndpoint result = initMockEndpoint();
    result.setExpectedMessageCount(1);

    DirectEndpoint directEndpoint = context.getEndpoint("direct://start", DirectEndpoint.class);
    ProducerTemplate template = context.createProducerTemplate();

    try {
        context.start();

        String inputJson = OBJECT_MAPPER.writeValueAsString(newProduct);
        template.sendBody(directEndpoint, inputJson);

        result.assertIsSatisfied();

        String status = extractJsonFromExchgMsg(result, 0);
        String expected = createResponseJson(HttpStatusCode.NO_CONTENT);
        assertThatJson(status).isEqualTo(expected);

        String newName = queryProperty(refServiceURI, resourcePath, keyPredicate, nameProperty);
        assertEquals(newMiddleName, newName);
        assertNotEquals(originalName, newName);
    } finally {
        //
        // Reset property back to original value
        // Not strictly necessary as our own special service created but
        // just in case it ever pops up again.
        //
        updateProperty(refServiceURI, resourcePath, keyPredicate, nameProperty, originalName);
    }
}
 
Example 19
Source File: EMailSendRouteTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSmtpSenderRoute() throws Exception {
    server = smtpServer();

    Step directStep = createDirectStep();

    Connector mailConnector = RouteUtils.createEMailConnector(server,
                                                   new PropertyBuilder<String>()
                                                           .property(PROTOCOL, Protocol.SMTP.id())
                                                           .property(HOST, server.getHost())
                                                           .property(PORT, Integer.toString(server.getPort()))
                                                           .property(USER, TEST_ADDRESS)
                                                           .property(PASSWORD, TEST_PASSWORD));

    Step mailStep = RouteUtils.createEMailStep(mailConnector, this::createConnectorAction);
    Integration mailIntegration = RouteUtils.createIntegrationWithMock(directStep, mailStep);

    RouteBuilder routes = RouteUtils.newIntegrationRouteBuilder(mailIntegration);
    context.addRoutes(routes);

    MockEndpoint result = RouteUtils.initMockEndpoint(context);
    result.setExpectedMessageCount(1);

    DirectEndpoint directEndpoint = context.getEndpoint("direct://start", DirectEndpoint.class);
    ProducerTemplate template = context.createProducerTemplate();

    context.start();

    EMailMessageModel msgModel = new EMailMessageModel();
    msgModel.setSubject("Test Email 1");
    msgModel.setFrom(TEST_ADDRESS);
    msgModel.setTo(TEST_ADDRESS);
    msgModel.setContent("Hello, I am sending emails to myself again!\r\n");

    template.sendBody(directEndpoint, msgModel);

    result.assertIsSatisfied();

    List<EMailMessageModel> emails = server.getEmails();
    assertEquals(1, emails.size());
    assertEquals(msgModel, emails.get(0));

    Exchange exchange = result.getReceivedExchanges().get(0);
    Map<String, Object> headers = exchange.getIn().getHeaders();
    assertNotNull(headers);
    Object contentType = headers.get(Exchange.CONTENT_TYPE);
    assertNotNull(contentType);
    assertEquals(EMailConstants.TEXT_PLAIN, contentType);
}
 
Example 20
Source File: ODataDeleteTests.java    From syndesis with Apache License 2.0 3 votes vote down vote up
@Test
public void testDeleteODataRouteKeyPredicateFilter() throws Exception {
    int initialResultCount = defaultTestServer.getResultCount();

    Step directStep = createDirectStep();

    Connector odataConnector = createODataConnector(new PropertyBuilder<String>()
                                                        .property(SERVICE_URI, defaultTestServer.servicePlainUri()));


    String resourcePath = defaultTestServer.resourcePath();

    ObjectNode keyPredicateJson = OBJECT_MAPPER.createObjectNode();
    keyPredicateJson.put(KEY_PREDICATE, "ID=2");

    Step odataStep = createODataStep(odataConnector, resourcePath);
    Step mockStep = createMockStep();
    Integration odataIntegration = createIntegration(directStep, odataStep, mockStep);

    RouteBuilder routes = newIntegrationRouteBuilder(odataIntegration);
    context.addRoutes(routes);

    MockEndpoint result = initMockEndpoint();
    result.setExpectedMessageCount(1);

    DirectEndpoint directEndpoint = context.getEndpoint("direct://start", DirectEndpoint.class);
    ProducerTemplate template = context.createProducerTemplate();

    context.start();
    String inputJson = OBJECT_MAPPER.writeValueAsString(keyPredicateJson);
    template.sendBody(directEndpoint, inputJson);

    result.assertIsSatisfied();

    String status = extractJsonFromExchgMsg(result, 0);
    String expected = createResponseJson(HttpStatusCode.NO_CONTENT);
    assertThatJson(status).isEqualTo(expected);

    assertEquals(initialResultCount - 1, defaultTestServer.getResultCount());
}