@Test public void testHandleException() throws Exception { for (int i = 0; i < DELIVERY_COUNT; i++) { MockEndpoint finish = consumerContext.getEndpoint("mock:finish" + i, MockEndpoint.class); finish.whenAnyExchangeReceived( new Processor() { @Override public void process(Exchange exchange) throws Exception { throw new RuntimeException("TestException!!!"); } }); finish.expectedBodiesReceived("1234567890"); } MockEndpoint finish4 = consumerContext.getEndpoint("mock:finish4", MockEndpoint.class); finish4.expectedBodiesReceived("1234567890-1"); MockEndpoint exception = producerContext.getEndpoint("mock:exception", MockEndpoint.class); exception.expectedBodiesReceived("1234567890"); ProducerTemplate producerTemplate = producerContext.createProducerTemplate(); try { producerTemplate.sendBody("direct:start", "1234567890"); fail("CamelExecutionException expected"); } catch (CamelExecutionException e) { assertEquals("TestException!!!", e.getCause().getMessage()); } producerTemplate.sendBody("direct:start", "1234567890-1"); MockEndpoint.assertIsSatisfied(consumerContext); MockEndpoint.assertIsSatisfied(producerContext); }
public void testThrottlingRoutePolicy() throws Exception { // trigger one in flight from the start template.sendBody("seda:bar", "Hello World"); MockEndpoint result = getMockEndpoint("mock:result"); result.expectedBodiesReceived("A"); // only 1 message will get completed as the throttler will suspend the consumer // when A is done template.sendBody("direct:start", "A"); // need a little slack to ensure the seda consumer will be suspended in between Thread.sleep(2000); template.sendBody("direct:start", "B"); result.assertIsSatisfied(); result.reset(); result.expectedBodiesReceived("B"); // trigger seda:bar to complete now, which should signal // to the throttler to resume the seda:foo consumer, so B can get done latch.countDown(); result.assertIsSatisfied(); }
public void testSpringTwoCamelContextDirectEndpoint() throws Exception { AbstractXmlApplicationContext ac = createApplicationContext(); ac.start(); CamelContext camel1 = (CamelContext) ac.getBean("myCamel-1", CamelContext.class); CamelContext camel2 = (CamelContext) ac.getBean("myCamel-2", CamelContext.class); Endpoint start1 = camel1.getEndpoint("direct:start"); Endpoint start2 = camel2.getEndpoint("direct:start"); assertNotSame(start1, start2); MockEndpoint mock1 = camel1.getEndpoint("mock:result", MockEndpoint.class); mock1.expectedBodiesReceived("Hello World"); MockEndpoint mock2 = camel2.getEndpoint("mock:result", MockEndpoint.class); mock2.expectedBodiesReceived("Bye World"); camel1.createProducerTemplate().sendBody("direct:start", "Hello World"); camel2.createProducerTemplate().sendBody("direct:start", "Bye World"); mock1.assertIsSatisfied(); mock2.assertIsSatisfied(); ac.stop(); }
@Test public void testBlueprintProperties() throws Exception { // start bundle getInstalledBundle(name).start(); // must use the camel context from osgi CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=" + name + ")", 10000); ProducerTemplate myTemplate = ctx.createProducerTemplate(); myTemplate.start(); // do our testing MockEndpoint foo = ctx.getEndpoint("mock:foo", MockEndpoint.class); foo.expectedMessageCount(1); MockEndpoint result = ctx.getEndpoint("mock:result", MockEndpoint.class); result.expectedMessageCount(1); myTemplate.sendBody("direct:start", "Hello World"); foo.assertIsSatisfied(); result.assertIsSatisfied(); myTemplate.stop(); }
@Test public void testScheduledStartRoutePolicyWithTwoRoutes() throws Exception { MockEndpoint success1 = context.getEndpoint("mock:success1", MockEndpoint.class); MockEndpoint success2 = context.getEndpoint("mock:success2", MockEndpoint.class); success1.expectedMessageCount(1); success2.expectedMessageCount(1); context .getComponent("quartz2", QuartzComponent.class) .setPropertiesFile("org/apache/camel/routepolicy/quartz2/myquartz.properties"); context.addRoutes( new RouteBuilder() { public void configure() { CronScheduledRoutePolicy policy = new CronScheduledRoutePolicy(); policy.setRouteStartTime("*/3 * * * * ?"); from("direct:start1").routeId("test1").routePolicy(policy).to("mock:success1"); from("direct:start2").routeId("test2").routePolicy(policy).to("mock:success2"); } }); context.start(); context.stopRoute("test1", 1000, TimeUnit.MILLISECONDS); context.stopRoute("test2", 1000, TimeUnit.MILLISECONDS); Thread.sleep(5000); assertTrue(context.getRouteStatus("test1") == ServiceStatus.Started); assertTrue(context.getRouteStatus("test2") == ServiceStatus.Started); template.sendBody("direct:start1", "Ready or not, Here, I come"); template.sendBody("direct:start2", "Ready or not, Here, I come"); success1.assertIsSatisfied(); success2.assertIsSatisfied(); }
@Test public void testTransaction() throws InterruptedException { // Assertions deletedEndpoint.expectedMessageCount(8); deletedEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 204); transactedEndpoint.expectedMessageCount(1); verifiedEndpoint.expectedMessageCount(3); midtransactionEndpoint.expectedMessageCount(3); midtransactionEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 201); notfoundEndpoint.expectedMessageCount(6); notfoundEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 404); // Start the transaction final Map<String, Object> headers = new HashMap<>(); headers.put(Exchange.HTTP_METHOD, "POST"); headers.put(Exchange.CONTENT_TYPE, "text/turtle"); // Create the object final String fullPath = template.requestBodyAndHeaders( "direct:create", FcrepoTestUtils.getTurtleDocument(), headers, String.class); assertNotNull(fullPath); final String identifier = fullPath.replaceAll(FcrepoTestUtils.getFcrepoBaseUrl(), ""); // Test the creation of several objects template.sendBodyAndHeader("direct:transact", null, "TestIdentifierBase", identifier); // Test the object template.sendBodyAndHeader( "direct:verify", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/one"); template.sendBodyAndHeader( "direct:verify", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/two"); template.sendBodyAndHeader( "direct:verify", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/three"); // Teardown template.sendBodyAndHeader( "direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/one"); template.sendBodyAndHeader( "direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/two"); template.sendBodyAndHeader( "direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/three"); template.sendBodyAndHeader( "direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier); // Confirm assertions verifiedEndpoint.assertIsSatisfied(); deletedEndpoint.assertIsSatisfied(); transactedEndpoint.assertIsSatisfied(); notfoundEndpoint.assertIsSatisfied(); midtransactionEndpoint.assertIsSatisfied(); }
@Test public void testIdempotent() throws Exception { String uri = "file:target/test-classes/idempotent?idempotent=true&delay=10"; context .getRouteDefinitions() .get(1) .adviceWith( context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith(uri); weaveByType(ToDefinition.class).selectFirst().replace().to("mock:endpoint"); } }); MockEndpoint end = context.getEndpoint("mock:endpoint", MockEndpoint.class); end.expectedMessageCount(1); producer.sendBodyAndHeader( "file://target/test-classes/idempotent", Exchange.FILE_NAME, "FCOO1.nc"); end.assertIsSatisfied(); String fileName = (String) end.getReceivedExchanges().get(0).getIn().getHeader(Exchange.FILE_NAME_ONLY); assertEquals(fileName, "FCOO1.nc"); // reset the mock end.reset(); end.expectedMessageCount(0); // move file back File file = new File("target/test-classes/idempotent/.camel/FCOO1.nc"); File renamed = new File("target/test-classes/idempotent/FCOO1.nc"); file.renameTo(renamed); producer.sendBodyAndHeader( "file://target/test-classes/idempotent", Exchange.FILE_NAME, "FCOO1.nc"); // let some time pass to let the consumer try to consume even though it cannot Thread.sleep(100); end.assertIsSatisfied(); FileEndpoint fe = context.getEndpoint(uri, FileEndpoint.class); assertNotNull(fe); // Make sure that there are no incoming messages MemoryIdempotentRepository repo = (MemoryIdempotentRepository) fe.getInProgressRepository(); assertEquals("Should be no in-progress files", 0, repo.getCacheSize()); }
@Test public void testNotTooOldFilter() throws Exception { fakeFtpServer.start(); int port = fakeFtpServer.getServerControlPort(); context .getRouteDefinitions() .get(0) .adviceWith( context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith( "ftp://[email protected]:" + port + "?password=password&filter=#notTooOld&passiveMode=true"); weaveByType(ToDefinition.class).selectFirst().replace().to("mock:end"); } }); MockEndpoint end = context.getEndpoint("mock:end", MockEndpoint.class); end.expectedMessageCount(1); end.assertIsSatisfied(); // Make sure that the received file has the correct file name String fileName = (String) end.getReceivedExchanges().get(0).getIn().getHeader(Exchange.FILE_NAME_ONLY); assertEquals(fileName, "DMI1.nc"); fakeFtpServer.stop(); }
@Test /** Operation: CREATE Body contains: Metacard */ public void testCreateWithIngestException() throws Exception { resetMocks(); // Setup expectations to verify final MockEndpoint mockVerifierEndpoint = getMockEndpoint("mock:result"); mockVerifierEndpoint.expectedMessageCount(1); final List<Metacard> metacards = new ArrayList<Metacard>(); metacards.add(metacard1); // Mock catalog framework final CreateRequest createRequest = new CreateRequestImpl(metacards); final CreateResponse createResponse = new CreateResponseImpl(createRequest, new HashMap(), metacards); when(catalogFramework.create(any(CreateRequest.class))).thenThrow(new IngestException()); // Exercise the route with a CREATE operation template.sendBodyAndHeader("direct:sampleInput", metacard1, "Operation", "CREATE"); // Verify that the number of metacards in the exchange after the records // is identical to the input assertListSize(mockVerifierEndpoint.getExchanges(), 1); final Exchange exchange = mockVerifierEndpoint.getExchanges().get(0); final List<Metacard> cardsCreated = (List<Metacard>) exchange.getIn().getBody(); assertListSize(cardsCreated, 0); mockVerifierEndpoint.assertIsSatisfied(); }
@Test public void testScheduledStartRoutePolicy() throws Exception { MockEndpoint success = (MockEndpoint) context.getEndpoint("mock:success"); success.expectedMessageCount(1); context .getComponent("quartz", QuartzComponent.class) .setPropertiesFile("org/apache/camel/routepolicy/quartz/myquartz.properties"); context.getComponent("quartz", QuartzComponent.class).start(); context.addRoutes( new RouteBuilder() { public void configure() { SimpleScheduledRoutePolicy policy = new SimpleScheduledRoutePolicy(); long startTime = System.currentTimeMillis() + 3000L; policy.setRouteStartDate(new Date(startTime)); policy.setRouteStartRepeatCount(1); policy.setRouteStartRepeatInterval(3000); from("direct:start").routeId("test").routePolicy(policy).to("mock:success"); } }); context.start(); context.stopRoute("test", 0, TimeUnit.MILLISECONDS); Thread.sleep(5000); assertTrue(context.getRouteStatus("test") == ServiceStatus.Started); template.sendBody("direct:start", "Ready or not, Here, I come"); context.getComponent("quartz", QuartzComponent.class).stop(); success.assertIsSatisfied(); }
@DirtiesContext @Test public void testSendInvalidData() throws Exception { resultEndpoint.expectedMessageCount(0); template.sendBody("CSV\nNullpointerException():100"); resultEndpoint.assertIsSatisfied(); }
@Test public void testLanguageCode() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); mock.assertIsSatisfied(); }
@DirtiesContext @Test public void testSendCsvDataZeroLines() throws Exception { resultEndpoint.expectedMessageCount(0); template.sendBody("only one line"); resultEndpoint.assertIsSatisfied(); }
public void testSendLotsOfMessagesSimultaneouslyButOnly3GetThrough() throws Exception { MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedMessageCount(messageCount); ExecutorService executor = Executors.newFixedThreadPool(messageCount); long start = System.currentTimeMillis(); for (int i = 0; i < messageCount; i++) { executor.execute( new Runnable() { public void run() { template.sendBody("direct:a", "<message>payload</message>"); } }); } // let's wait for the exchanges to arrive resultEndpoint.assertIsSatisfied(); // now assert that they have actually been throttled long minimumTime = (messageCount - 1) * INTERVAL; // add a little slack long delta = System.currentTimeMillis() - start + 200; assertTrue("Should take at least " + minimumTime + "ms, was: " + delta, delta >= minimumTime); }
public void testConcurrentPipeline() throws Exception { int total = 200; final int group = total / 20; MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(total); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(20); executor.afterPropertiesSet(); for (int i = 0; i < 20; i++) { final int threadCount = i; executor.execute( new Runnable() { public void run() { int start = threadCount * group; for (int i = 0; i < group; i++) { try { // do some random sleep to simulate spread in user activity Thread.sleep(new Random().nextInt(10)); } catch (InterruptedException e) { // ignore } template.sendBody(uri, "" + (start + i)); } } }); } mock.assertIsSatisfied(); mock.expectsNoDuplicates(body()); executor.shutdown(); }
@Test public void testFileToFile() throws Exception { // Body contains two CDs, one DVD and one BOOK. String bodyOfMessage = "eminem / cd,harry potter and the deathly hollows / dvd," + "Claus Ibsen - Camel in Action / book," + "Xzibit / cd"; // The TemplateProducer is part of CamelTestSupport. It is used to send messages to Camel // endpoints. template.sendBodyAndHeader( "file://orders/inbox", bodyOfMessage, Exchange.FILE_NAME, "order.csv"); // Mock is included implicitly. MockEndpoint mock = context.getEndpoint("mock:others", MockEndpoint.class); // The Mock expects only one message, because it only receives the BOOK order: mock.expectedMessageCount(1); mock.setResultWaitTime(1000); Thread.sleep(3000); String dvdBody = " harry potter and the deathly hollows / dvd"; File target = new File("orders/outbox/dvd/order.csv"); String content = context.getTypeConverter().convertTo(String.class, target); // Assertions mock.assertIsSatisfied(); assertEquals(dvdBody.toUpperCase(), content); }
@DirtiesContext @Test public void testSendCsvDataOneLine() throws Exception { resultEndpoint.expectedBodiesReceived(new MyCsvBean(1, "message", "db")); template.sendBody("CSV\n1,message,db"); resultEndpoint.assertIsSatisfied(); }
@Test public void testHeaderAndTrailer() throws Exception { results.expectedMessageCount(1); results.message(0).body().isInstanceOf(List.class); results.message(0).header("camelFlatpackCounter").isEqualTo(6); results.assertIsSatisfied(); List<Map<String, String>> data = CastUtils.cast(results.getExchanges().get(0).getIn().getBody(List.class)); // assert header Map<String, String> header = data.get(0); assertEquals("HBT", header.get("INDICATOR")); assertEquals("20080817", header.get("DATE")); // assert body int counter = 0; for (Map<String, String> row : data.subList(1, 5)) { assertEquals("FIRSTNAME", expectedFirstName[counter], row.get("FIRSTNAME")); LOG.info("Result: " + counter + " = " + row); counter++; } // assert trailer Map<String, String> trailer = data.get(5); assertEquals("FBT", trailer.get("INDICATOR")); assertEquals("SUCCESS", trailer.get("STATUS")); }
@Test public void testSqlIdempotentConsumer() throws Exception { Assert.assertNotNull("DataSource not null", dataSource); final JdbcMessageIdRepository jdbcMessageIdRepository = new JdbcMessageIdRepository(dataSource, "myProcessorName"); CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .idempotentConsumer(simple("${header.messageId}"), jdbcMessageIdRepository) .to("mock:result"); } }); camelctx.start(); try { MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class); mockEndpoint.expectedMessageCount(1); // Send 5 messages with the same messageId header. Only 1 should be forwarded to the // mock:result endpoint ProducerTemplate template = camelctx.createProducerTemplate(); for (int i = 0; i < 5; i++) { template.requestBodyAndHeader("direct:start", null, "messageId", "12345"); } mockEndpoint.assertIsSatisfied(); } finally { camelctx.stop(); } }
@Test /** Operation: DELETE Body contains: 12345678900987654321abcdeffedcba */ public void testDeleteWithIngestException() throws Exception { resetMocks(); // Setup expectations to verify final MockEndpoint mockVerifierEndpoint = getMockEndpoint("mock:result"); mockVerifierEndpoint.expectedMessageCount(1); final List<Metacard> metacards = new ArrayList<Metacard>(); metacards.add(metacard1); // setup mock catalog framework final String[] metacardIds = new String[metacards.size()]; for (int i = 0; i < metacards.size(); i++) { metacardIds[i] = metacards.get(i).getId(); } DeleteRequest deleteRequest = new DeleteRequestImpl(metacardIds); DeleteResponse deleteResponse = new DeleteResponseImpl(deleteRequest, new HashMap(), metacards); when(catalogFramework.delete(any(DeleteRequest.class))).thenThrow(new IngestException()); // Exercise the route with a DELETE operation template.sendBodyAndHeader("direct:sampleInput", metacardIds, "Operation", "DELETE"); // Verify that the number of metacards in the exchange after the records // is identical to the input assertListSize(mockVerifierEndpoint.getExchanges(), 1); final Exchange exchange = mockVerifierEndpoint.getExchanges().get(0); final List<Update> cardsDeleted = (List<Update>) exchange.getIn().getBody(); assertListSize(cardsDeleted, 0); mockVerifierEndpoint.assertIsSatisfied(); }
@Test public void uriRoutingKey() throws Exception { MockEndpoint mockEndpoint = getMockEndpoint("mock:test.u"); mockEndpoint.expectedMessageCount(1); context().createProducerTemplate().sendBody("direct:test.u", new ProducerTestObject()); mockEndpoint.assertIsSatisfied(); }
@Test public void testScheduledResumeRoutePolicy() throws Exception { MockEndpoint success = context.getEndpoint("mock:success", MockEndpoint.class); success.expectedMessageCount(1); context .getComponent("quartz2", QuartzComponent.class) .setPropertiesFile("org/apache/camel/routepolicy/quartz2/myquartz.properties"); context.addRoutes( new RouteBuilder() { public void configure() { CronScheduledRoutePolicy policy = new CronScheduledRoutePolicy(); policy.setRouteResumeTime("*/3 * * * * ?"); from("direct:start").routeId("test").routePolicy(policy).to("mock:success"); } }); context.start(); ServiceHelper.suspendService(context.getRoute("test").getConsumer()); Thread.sleep(5000); assertTrue(context.getRouteStatus("test") == ServiceStatus.Started); template.sendBody("direct:start", "Ready or not, Here, I come"); success.assertIsSatisfied(); }
@Test public void testGroovyLanguage() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); result.expectedBodiesReceived("Hello is processed!"); template.sendBody("direct:groovy", "Hello"); result.assertIsSatisfied(); }
@Test public void testBlobStorePut() throws InterruptedException { MockEndpoint mockEndpoint = resolveMandatoryEndpoint("mock:results", MockEndpoint.class); mockEndpoint.expectedMessageCount(1); template.sendBody("direct:put", "Some message"); mockEndpoint.assertIsSatisfied(); }
public void testSimpleSplitWriteRead() throws Exception { context.addRoutes( new RouteBuilder() { @Override public void configure() { from("direct:start") .to( "hdfs://localhost:9000/tmp/test/test-camel-simple-write-file?fileSystemType=HDFS&splitStrategy=BYTES:5,IDLE:1000"); from("hdfs://localhost:9000/tmp/test/test-camel-simple-write-file?pattern=seg*&initialDelay=2000&fileSystemType=HDFS&chunkSize=5") .to("mock:result"); } }); context.start(); for (int i = 0; i < 10; ++i) { template.sendBody("direct:start", "CIAO" + i); } MockEndpoint resultEndpoint = (MockEndpoint) context.getEndpoint("mock:result"); resultEndpoint.expectedMessageCount(10); resultEndpoint.assertIsSatisfied(); int i = 0; List<Exchange> exchanges = resultEndpoint.getExchanges(); for (Exchange exchange : exchanges) { Assert.assertEquals("CIAO" + i++, exchange.getIn().getBody(String.class)); } }
@Test @Ignore public void shouldNotThrowClassNotFoundException() throws InterruptedException { MockEndpoint mockEndpoint = camelContext.getEndpoint("mock:test", MockEndpoint.class); mockEndpoint.expectedMinimumMessageCount(5); mockEndpoint.assertIsSatisfied(); }
@Test public void testMarshallMessage() throws Exception { resultEndpoint.expectedBodiesReceived(result); template.sendBody(generateModel()); resultEndpoint.assertIsSatisfied(); }
public void testSendAMessageWhosInBodyIsTransformed() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint("mock:end"); resultEndpoint.expectedBodiesReceived("Hello World!"); sendBody("direct:start", "Hello"); resultEndpoint.assertIsSatisfied(); }
@Test public void testMocksIsValid() throws Exception { mock.expectedMessageCount(1); producer.sendBody(null); mock.assertIsSatisfied(); }
@Test public void testSendingOneWayMessage() throws Exception { MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedBodiesReceived(MESSAGE_BODY); MessageChannel outputChannel = (MessageChannel) applicationContext.getBean("channelA"); outputChannel.send(new GenericMessage<Object>(MESSAGE_BODY)); resultEndpoint.assertIsSatisfied(); }