@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); }
@Test @Ignore public void testRuleOnBody() throws Exception { Person person = new Person(); person.setName("Young Scott"); person.setAge(18); Cheese cheese = new Cheese(); cheese.setPrice(10); cheese.setType("Stilton"); // Add cheese ruleOnBodyEndpoint.requestBody(cheese, Cheese.class); // Check If Person can Drink Person response = ruleOnBodyEndpoint.requestBody(person, Person.class); assertNotNull(response); assertFalse(person.isCanDrink()); // Test for alternative result person.setName("Scott"); person.setAge(21); response = ruleOnBodyEndpoint.requestBody(person, Person.class); assertNotNull(response); assertTrue(person.isCanDrink()); }
@Test public void testInvalidCredentials() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .policy(new DomainAuthorizationPolicy()) .transform(body().prepend("Hello ")); } }); camelctx.start(); try { ProducerTemplate producer = camelctx.createProducerTemplate(); try { Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, "bogus"); producer.requestBodyAndHeader( "direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class); Assert.fail("CamelExecutionException expected"); } catch (CamelExecutionException e) { // expected } } finally { camelctx.stop(); } }
@Test public void testRoleBasedAccess() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .policy(new DomainAuthorizationPolicy().roles("Role2")) .transform(body().prepend("Hello ")); } }); camelctx.start(); try { ProducerTemplate producer = camelctx.createProducerTemplate(); Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, AnnotatedSLSB.PASSWORD); String result = producer.requestBodyAndHeader( "direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class); Assert.assertEquals("Hello Kermit", result); } finally { camelctx.stop(); } }
@Test public void testNoAuthenticationHeader() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .policy(new DomainAuthorizationPolicy()) .transform(body().prepend("Hello ")); } }); camelctx.start(); try { ProducerTemplate producer = camelctx.createProducerTemplate(); try { producer.requestBody("direct:start", "Kermit", String.class); Assert.fail("CamelExecutionException expected"); } catch (CamelExecutionException e) { // expected } } finally { camelctx.stop(); } }
@Test public void testOgnlExpressionFromFile() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .choice() .when() .ognl("resource:classpath:test-ognl-expression.txt") .transform(simple("Hello ${body.name}")) .otherwise() .to("mock:dlq"); } }); Person person = new Person(); person.setName("Kermit"); camelctx.start(); try { ProducerTemplate producer = camelctx.createProducerTemplate(); String result = producer.requestBody("direct:start", person, String.class); Assert.assertEquals("Hello Kermit", result); } finally { camelctx.stop(); } }
@Test public void testUnmarshalJackson() throws Exception { CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").unmarshal().json(JsonLibrary.Jackson, Customer.class); } }); String input = "{'firstName':'John','lastName':'Doe'}"; camelctx.start(); try { ProducerTemplate producer = camelctx.createProducerTemplate(); Customer customer = producer.requestBody("direct:start", input.replace('\'', '"'), Customer.class); Assert.assertEquals("John", customer.getFirstName()); Assert.assertEquals("Doe", customer.getLastName()); } finally { camelctx.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 testFilePollerB() throws Exception { String expected = "xxx"; final MockEndpoint mockEndpoint = getMockEndpoint("mock:" + routeATo); cc.getRouteDefinitions() .get(0) .adviceWith( cc, new RouteBuilder() { @Override public void configure() throws Exception { // intercept sending to mock:foo and do something else interceptSendToEndpoint(routeATo).to(mockEndpoint); } }); mockEndpoint.expectedBodiesReceived(expected); Endpoint ep = cc.getEndpoint(routeAFrom); Assert.assertNotNull(ep); ProducerTemplate pt = cc.createProducerTemplate(); pt.start(); pt.sendBody(ep, expected); assertMockEndpointsSatisfied(); }
@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 @Ignore // TODO drools-camel component should be improved to allow to set Global value on the session public void testRuleOnCommand() throws Exception { Person person = new Person(); person.setName("Young Scott"); person.setAge(18); Cheese cheese = new Cheese(); cheese.setPrice(10); cheese.setType("Stilton"); // Add a Person ruleOnBodyEndpoint.requestBody(cheese, Cheese.class); // Add cheese ruleOnBodyEndpoint.requestBody(cheese, Cheese.class); // Remark : passing person here is not required ExecutionResultImpl response = ruleOnCommandEndpoint.requestBody(person, ExecutionResultImpl.class); assertNotNull(response); // Expecting single result value of type Person Collection<String> identifiers = response.getIdentifiers(); assertNotNull(identifiers); assertTrue(identifiers.size() >= 1); for (String identifier : identifiers) { final Object value = response.getValue(identifier); assertNotNull(value); assertIsInstanceOf(Person.class, value); assertFalse(((Person) value).isCanDrink()); System.out.println(identifier + " = " + value); } // Test for alternative result person.setName("Scott"); person.setAge(21); response = ruleOnCommandEndpoint.requestBody(person, ExecutionResultImpl.class); assertNotNull(response); // Expecting single result value of type Person identifiers = response.getIdentifiers(); assertNotNull(identifiers); assertTrue(identifiers.size() >= 1); for (String identifier : identifiers) { final Object value = response.getValue(identifier); assertNotNull(value); assertIsInstanceOf(Person.class, value); assertTrue(((Person) value).isCanDrink()); System.out.println(identifier + " = " + value); } }
private void sendBodyAndHeader( final String channelUri, final Object payload, final String header, final String headerValue) { final ProducerTemplate<Exchange> producer = getContext().createProducerTemplate(); producer.sendBodyAndHeader(channelUri, payload, header, headerValue); }
@Test public void testContextScan() throws Exception { CamelContext camelctx = contextRegistry.getCamelContext("contextScanA"); Assert.assertEquals(ServiceStatus.Started, camelctx.getStatus()); ProducerTemplate producer = camelctx.createProducerTemplate(); String result = producer.requestBody("direct:start", "Kermit", String.class); Assert.assertEquals("Hello Kermit", result); }
public void sendBody(String endpointUri, Object body) throws Exception { ProducerTemplate template = context.createProducerTemplate(); try { template.sendBody(endpointUri, body); } finally { template.stop(); } }
public void sendBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers) throws Exception { ProducerTemplate template = context.createProducerTemplate(); try { template.sendBodyAndHeaders(endpointUri, body, headers); } finally { template.stop(); } }
private static void put(CamelContext camelContext) { Put put = new Put(Bytes.toBytes("row1")); put.add(Bytes.toBytes("fam1"), Bytes.toBytes("qual1"), Bytes.toBytes("val1")); put.add(Bytes.toBytes("fam2"), Bytes.toBytes("qual2"), Bytes.toBytes("val2")); put.add(Bytes.toBytes("fam3"), Bytes.toBytes("qual3"), Bytes.toBytes("val3")); ProducerTemplate producer = camelContext.createProducerTemplate(); producer.requestBody("direct:start-put", put); }
@Test public void testCallFromCamel() throws Exception { // get camel context CamelContext context = (CamelContext) applicationContext.getBean("conduit_context"); ProducerTemplate producer = context.createProducerTemplate(); // The echo parameter will be ignore, since the service has the fix response String response = producer.requestBody("direct://jbiStart", "Hello World!", String.class); assertEquals("Get a wrong response ", "echo Hello World!", response); }
public Object requestBody(String endpointUri, Object body) throws Exception { ProducerTemplate template = context.createProducerTemplate(); Object answer = null; try { answer = template.requestBody(endpointUri, body); } finally { template.stop(); } return answer; }
@Test public void aggregatesTwoMessagesIntoOne() throws Exception { mockAggregated.expectedHeaderReceived("invoiceItemTotal", BigDecimal.valueOf(5)); mockAggregated.expectedMessageCount(1); start.sendBodyAndHeaders( null, toHeadersMap("invoiceId", "invoiceOne", "invoiceItemTotal", BigDecimal.valueOf(2))); start.sendBodyAndHeaders( null, toHeadersMap("invoiceId", "invoiceOne", "invoiceItemTotal", BigDecimal.valueOf(3))); assertMockEndpointsSatisfied(); }
@Test public void testRoute() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World 2"); template.sendBodyAndHeader("direct:start", "Hello World 1", "isfailed", true); template.sendBodyAndHeader("direct:start", "Hello World 2", "isfailed", false); mock.assertIsSatisfied(); }
public void directStartTask(DirectConfig directConfig) { try { ProducerTemplate template = context.createProducerTemplate(); Router createRouter = directConfig.getRouter(); template.sendBody( "direct:" + createRouter.getFrom().getName(), createRouter.getFrom().getParaText()); } catch (Exception e) { e.printStackTrace(); // this.updateTaskStatus(task, TaskStatus.ERROR_ON_STARTING); } }
@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 shouldDLQOrginalHandler() throws Exception { ModelCamelContext context = new DefaultCamelContext(); context.setTracing(true); ProducerTemplate pt = context.createProducerTemplate(); context.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { // will use original ErrorHandlerBuilder a = deadLetterChannel("seda:dead") .maximumRedeliveries(1) .redeliveryDelay(300) .logStackTrace(false) .useOriginalMessage() .logHandled(false); from("seda:start") .errorHandler(a) .log(LoggingLevel.INFO, "myCamel", "==== ${body}") .bean(SampleErrorBean.class) .bean(ChangeBody.class) .bean(ErrorBean.class) .bean(SampleErrorBean.class) .transform(constant("ok")); from("seda:dead") .bean(FailureBean.class) .process( exchange -> { counterA.incrementAndGet(); Throwable e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class); log.info("+++ properties : {}", exchange.getProperties()); log.info("+++ body : {}", exchange.getIn().getBody()); log.info("+++ headers : {}", exchange.getIn().getHeaders()); log.info("+++ exception Processor : {}", e); log.info( "+++ counterA : {} , header : {}", counterA.get(), exchange.getProperty("CamelExceptionCaught")); }) .convertBodyTo(String.class) .bean(SampleErrorBean.class); } }); context.start(); String result = (String) pt.requestBody("seda:start", "test"); Assertions.assertThat(result).isEqualTo("test"); Thread.sleep(3000); }
@Test public void aggregatesMessagesByCorrelationKey() throws Exception { mockAggregated.expectedHeaderValuesReceivedInAnyOrder( "invoiceItemTotal", BigDecimal.valueOf(5), BigDecimal.valueOf(4)); mockAggregated.expectedMessageCount(2); start.sendBodyAndHeaders( null, toHeadersMap("invoiceId", "invoiceOne", "invoiceItemTotal", BigDecimal.valueOf(2))); start.sendBodyAndHeaders( null, toHeadersMap("invoiceId", "invoiceTwo", "invoiceItemTotal", BigDecimal.valueOf(4))); start.sendBodyAndHeaders( null, toHeadersMap("invoiceId", "invoiceOne", "invoiceItemTotal", BigDecimal.valueOf(3))); assertMockEndpointsSatisfied(); }
@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 testInsert() throws IOException, InterruptedException { final String base = "http://localhost/rest"; final String path = "/path/a/b/c"; final String document = getN3Document(); // Assertions resultEndpoint.allMessages().body().contains("update=INSERT DATA { "); resultEndpoint.allMessages().body().contains(" }"); for (final String s : document.split("\n")) { resultEndpoint.expectedBodyReceived().body().contains(s); } resultEndpoint .expectedBodyReceived() .body() .contains("<" + base + path + "> dc:title \"some title\" ."); resultEndpoint.expectedHeaderReceived("Content-Type", "application/x-www-form-urlencoded"); resultEndpoint.expectedHeaderReceived(Exchange.HTTP_METHOD, "POST"); // Test final Map<String, Object> headers = new HashMap<>(); headers.put(FcrepoHeaders.FCREPO_BASE_URL, base); headers.put(FcrepoHeaders.FCREPO_IDENTIFIER, path); headers.put(Exchange.CONTENT_TYPE, "application/n-triples"); template.sendBodyAndHeaders(document, headers); headers.clear(); headers.put(JmsHeaders.BASE_URL, base); headers.put(JmsHeaders.IDENTIFIER, path); headers.put(Exchange.CONTENT_TYPE, "application/n-triples"); template.sendBodyAndHeaders(document, headers); headers.clear(); headers.put(JmsHeaders.BASE_URL, base); headers.put(FcrepoHeaders.FCREPO_IDENTIFIER, path); headers.put(Exchange.CONTENT_TYPE, "text/turtle"); template.sendBodyAndHeaders(getTurtleDocument(), headers); headers.clear(); headers.put(FcrepoHeaders.FCREPO_BASE_URL, base); headers.put(JmsHeaders.IDENTIFIER, path); headers.put(Exchange.CONTENT_TYPE, "application/n-triples"); template.sendBodyAndHeaders(document, headers); // Confirm that assertions passed resultEndpoint.expectedMessageCount(4); resultEndpoint.assertIsSatisfied(); }
private void handleInOnly(final Exchange exchange) throws HandlerException { try { _producerTemplate.send(_uri, createProcessor(exchange)); } catch (final CamelExecutionException e) { throw new HandlerException(e); } }
@Listen("onClick = button#cfgSave") public void cfgSaveClick(MouseEvent event) { if (logger.isDebugEnabled()) logger.debug(" cfgSave button event = " + event); try { Properties config = Util.getConfig(null); if (isValidPort(portsToScan.getText())) { config.setProperty(Constants.SERIAL_PORTS, portsToScan.getValue()); } else { Messagebox.show( "Device ports to scan is invalid. In Linux (pi) '/dev/ttyUSB0,/dev/ttyUSB1,etc', in MS Windows 'COM1,COM2,COM3,etc'"); } if (isValidBaudRate(portBaudRate.getValue())) { config.setProperty(Constants.SERIAL_PORT_BAUD, portBaudRate.getValue()); Util.saveConfig(); } else { Messagebox.show("Device baud rate (speed) must be one of 4800,9600,19200,38400,57600"); } if (NumberUtils.isNumber(cfgWindOffset.getValue())) { config.setProperty(Constants.WIND_ZERO_OFFSET, cfgWindOffset.getValue()); Util.saveConfig(); // notify others producer.sendBody(Constants.WIND_ZERO_ADJUST_CMD + ":" + cfgWindOffset.getValue() + ","); } else { Messagebox.show("Wind offset must be numeric"); } config.setProperty(Constants.PREFER_RMC, (String) useRmcGroup.getSelectedItem().getValue()); config.setProperty( Constants.DNS_USE_CHOICE, (String) useHomeGroup.getSelectedItem().getValue()); Util.saveConfig(); } catch (Exception e) { logger.error(e.getMessage(), e); } }
public ConfigViewModel() { super(); producer = CamelContextFactory.getInstance().createProducerTemplate(); producer.setDefaultEndpointUri("seda:input"); allListMap = new TreeMap<String, String>(); selectedListArray = new ArrayList<String>(); }
/** * Publish upload events to the queue * * @param username * @param siteName * @param eventType * @param numOfDays */ public static void createHistoricEvents( String testName, ProducerTemplate template, String username, String siteName, String eventType, int numberOfUploadEvents, int numOfDays) { for (int i = 0; i < numberOfUploadEvents; i++) { String fileName = getFileName(testName + "_" + i + "." + "txt"); Event event = new ActivityEvent( eventType, "a52fbbf9-a297-4fb5-aeea-8f5fe8087c7b", "alfresco.com", getEventDate(numOfDays), username, "e346bfa0-3177-4d64-b86d-05b433307d3b", siteName.toLowerCase(), "{http://www.alfresco.org/model/content/1.0}content", null, "{\"nodeRef\": \"workspace:\\/\\/SpacesStore\\/e346bfa0-3177-4d64-b86d-05b433307d3b\", \"title\": \"Filemiojkli-SiteContentReadsReportTest_0.txt\", \"page\": \"document-details?nodeRef=workspace:\\/\\/SpacesStore\\/e346bfa0-3177-4d64-b86d-05b433307d3b\"}", fileName, "text/plain", 600L, "UTF-8"); template.sendBody("activemq:alfresco.events.raw?requestTimeout=5000", event); } }