@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 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 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 testSingletonism() { Endpoint a1 = context.getEndpoint("smslib://asdf"); Endpoint a2 = context.getEndpoint("smslib://asdf"); assertTrue(a1 == a2); Endpoint b = context.getEndpoint("smslib://bcde"); assertFalse(a1 == b); }
@Test public void testSQLEndpoint() throws Exception { Assert.assertNotNull("DataSource not null", dataSource); CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("sql:select name from information_schema.users?dataSource=java:jboss/datasources/ExampleDS") .to("direct:end"); } }); camelctx.start(); try { PollingConsumer pollingConsumer = camelctx.getEndpoint("direct:end").createPollingConsumer(); pollingConsumer.start(); String result = (String) pollingConsumer.receive().getIn().getBody(Map.class).get("NAME"); Assert.assertEquals("SA", result); } finally { camelctx.stop(); } }
@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 public void shouldNotThrowClassNotFoundException() throws InterruptedException { MockEndpoint mockEndpoint = camelContext.getEndpoint("mock:test", MockEndpoint.class); mockEndpoint.expectedMinimumMessageCount(5); mockEndpoint.assertIsSatisfied(); }
@Override public Consumer createConsumer( CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, String consumes, String produces, Map<String, Object> parameters) throws Exception { // just use a seda endpoint for testing purpose String id; if (uriTemplate != null) { id = ActiveMQUuidGenerator.generateSanitizedId(basePath + uriTemplate); } else { id = ActiveMQUuidGenerator.generateSanitizedId(basePath); } // remove leading dash as we add that ourselves if (id.startsWith("-")) { id = id.substring(1); } SedaEndpoint seda = camelContext.getEndpoint("seda:" + verb + "-" + id, SedaEndpoint.class); return seda.createConsumer(processor); }
@Test public void testPriority() { BeanstalkEndpoint endpoint = context.getEndpoint("beanstalk:default?jobPriority=1000", BeanstalkEndpoint.class); assertNotNull("Beanstalk endpoint", endpoint); assertEquals("Priority", 1000, endpoint.getJobPriority()); }
@Test public void testCommand() { BeanstalkEndpoint endpoint = context.getEndpoint("beanstalk:default?command=release", BeanstalkEndpoint.class); assertNotNull("Beanstalk endpoint", endpoint); assertEquals("Command", BeanstalkComponent.COMMAND_RELEASE, endpoint.getCommand().name()); }
@Test public void testTimeToRun() { BeanstalkEndpoint endpoint = context.getEndpoint("beanstalk:default?jobTimeToRun=10", BeanstalkEndpoint.class); assertNotNull("Beanstalk endpoint", endpoint); assertEquals("Time to run", 10, endpoint.getJobTimeToRun()); }
@Test public void testDelay() { BeanstalkEndpoint endpoint = context.getEndpoint("beanstalk:default?jobDelay=10", BeanstalkEndpoint.class); assertNotNull("Beanstalk endpoint", endpoint); assertEquals("Delay", 10, endpoint.getJobDelay()); }
@Test public void testTubes() { BeanstalkEndpoint endpoint = context.getEndpoint( "beanstalk:host:11303/tube1+tube%2B+tube%3F?command=kick", BeanstalkEndpoint.class); assertNotNull("Beanstalk endpoint", endpoint); assertEquals("Command", BeanstalkComponent.COMMAND_KICK, endpoint.getCommand().name()); assertEquals("Host", "host", endpoint.conn.host); assertArrayEquals("Tubes", new String[] {"tube1", "tube+", "tube?"}, endpoint.conn.tubes); }
@Test public void onlyRequiredEndpointParams() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint( "aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient"); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.TRIM_HORIZON)); assertThat(endpoint.getMaxResultsPerRequest(), is(1)); }
@Override protected void doStart() throws Exception { ObjectHelper.notNull(camelContext, "camelContext", this); if (endpoint == null && endpointUri == null) { throw new IllegalArgumentException("Either endpoint or endpointUri must be configured"); } if (endpoint == null) { endpoint = camelContext.getEndpoint(endpointUri); } producer = endpoint.createProducer(); ServiceHelper.startService(producer); }
@Test public void testProducerSingletonism() throws Exception { // given Endpoint endpoint = context.getEndpoint("smslib://asdf"); endpoint.createProducer(); // when then try { endpoint.createProducer(); fail(); } catch (Exception e) { // expected } }
public void testConsumerSingletonism() throws Exception { // given Endpoint endpoint = context.getEndpoint("smslib://asdf"); Processor mockProcessor = mock(Processor.class); endpoint.createConsumer(mockProcessor); Processor anotherMockProcessor = mock(Processor.class); // when then try { endpoint.createConsumer(anotherMockProcessor); fail("Should only be able to create a single consumer."); } catch (Exception e) { // expected } }
@Test public void atSequenceNumberRequiresSequenceNumber() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint( "aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient" + "&iteratorType=AT_SEQUENCE_NUMBER" + "&shardId=abc" + "&sequenceNumber=123"); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.AT_SEQUENCE_NUMBER)); assertThat(endpoint.getShardId(), is("abc")); assertThat(endpoint.getSequenceNumber(), is("123")); }
@Test public void testSQLEndpointWithCDIContext() throws Exception { try { deployer.deploy(CAMEL_SQL_CDI_ROUTES_JAR); CamelContext camelctx = contextRegistry.getCamelContext("camel-sql-cdi-context"); Assert.assertNotNull("Camel context not null", camelctx); PollingConsumer pollingConsumer = camelctx.getEndpoint("direct:end").createPollingConsumer(); pollingConsumer.start(); String result = (String) pollingConsumer.receive().getIn().getBody(Map.class).get("NAME"); Assert.assertEquals("SA", result); } finally { deployer.undeploy(CAMEL_SQL_CDI_ROUTES_JAR); } }
@Test public void allTheEndpointParams() throws Exception { KinesisEndpoint endpoint = (KinesisEndpoint) camelContext.getEndpoint( "aws-kinesis://some_stream_name" + "?amazonKinesisClient=#kinesisClient" + "&maxResultsPerRequest=101" + "&iteratorType=latest" + "&shardId=abc" + "&sequenceNumber=123"); assertThat(endpoint.getClient(), is(amazonKinesisClient)); assertThat(endpoint.getStreamName(), is("some_stream_name")); assertThat(endpoint.getIteratorType(), is(ShardIteratorType.LATEST)); assertThat(endpoint.getMaxResultsPerRequest(), is(101)); assertThat(endpoint.getSequenceNumber(), is("123")); assertThat(endpoint.getShardId(), is("abc")); }
protected void setUp(String endpointUri) throws Exception { template = camelContext.createProducerTemplate(); startServices(template, camelContext); endpoint = camelContext.getEndpoint(endpointUri, JpaEndpoint.class); transactionStrategy = endpoint.createTransactionStrategy(); jpaTemplate = endpoint.getTemplate(); transactionStrategy.execute( new JpaCallback() { public Object doInJpa(EntityManager entityManager) throws PersistenceException { entityManager.createQuery("delete from " + Customer.class.getName()).executeUpdate(); return null; } }); assertEntitiesInDatabase(0, Customer.class.getName()); assertEntitiesInDatabase(0, Address.class.getName()); }
@Test public void testProducerAndConsumer() throws Exception { getInstalledBundle("CamelBlueprintJcloudsTestBundle").start(); CamelContext ctx = getOsgiService( CamelContext.class, "(camel.context.symbolicname=CamelBlueprintJcloudsTestBundle)", 20000); MockEndpoint mock = ctx.getEndpoint("mock:results", MockEndpoint.class); ProducerTemplate template = ctx.createProducerTemplate(); mock.expectedMessageCount(2); template.sendBodyAndHeader("direct:start", "Test 1", JcloudsConstants.BLOB_NAME, "blob1"); template.sendBodyAndHeader("direct:start", "Test 2", JcloudsConstants.BLOB_NAME, "blob2"); assertMockEndpointsSatisfied(); template.stop(); }
public void testUnmarshalNoEncoding() throws Exception { // NOTE: Here we can use a MockEndpoint as we unmarshal the inputstream to String final String title = "Hello World"; context.addRoutes( new RouteBuilder() { public void configure() { from("direct:start").unmarshal().string().to("mock:unmarshal"); } }); context.start(); byte[] bytes = title.getBytes(); InputStream in = new ByteArrayInputStream(bytes); template.sendBody("direct:start", in); MockEndpoint mock = context.getEndpoint("mock:unmarshal", MockEndpoint.class); mock.setExpectedMessageCount(1); mock.expectedBodiesReceived(title); }
@Test public void testQuartz2Scheduler() throws Exception { // start bundle getInstalledBundle(NAME).start(); // must use the camel context from osgi CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=" + NAME + ")", 10000); MockEndpoint mock = ctx.getEndpoint("mock:result", MockEndpoint.class); mock.expectedMessageCount(2); ProducerTemplate myTemplate = ctx.createProducerTemplate(); myTemplate.start(); myTemplate.sendBodyAndHeader("file:target/foo", "Hello World", Exchange.FILE_NAME, "hello.txt"); myTemplate.sendBodyAndHeader("file:target/foo", "Bye World", Exchange.FILE_NAME, "bye.txt"); mock.assertIsSatisfied(); myTemplate.stop(); }
@Test public void writesResultToMock() throws Exception { final String receiver = "*****@*****.**"; createMailUser(receiver, "loginIdReceiver", "secretOfReceiver"); String validSender = "*****@*****.**"; createMailUser(validSender, "loginIdSender", "secretOfSender"); sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText("usedScenario"); final String ardulink = makeURI( mockURI, newMapBuilder() .put("validfroms", validSender) .put("scenario.usedScenario", "D1=true") .build()); CamelContext context = new DefaultCamelContext(); final MockEndpoint mockEndpoint = context.getEndpoint("mock:result", MockEndpoint.class); context.addRoutes( new RouteBuilder() { @Override public void configure() { from(localImap(receiver)).to(ardulink).to(mockEndpoint); } }); context.start(); try { mockEndpoint.expectedMessageCount(1); mockEndpoint.expectedBodiesReceived("SwitchDigitalPinCommand " + "[pin=1, value=true]=OK"); mockEndpoint.assertIsSatisfied(); } finally { context.stop(); } }
Consumer doCreateConsumer( CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api) throws Exception { String path = basePath; if (uriTemplate != null) { // make sure to avoid double slashes if (uriTemplate.startsWith("/")) { path = path + uriTemplate; } else { path = path + "/" + uriTemplate; } } path = FileUtil.stripLeadingSeparator(path); RestConfiguration config = configuration; if (config == null) { config = getCamelContext().getRestConfiguration("spark-rest", true); } Map<String, Object> map = new HashMap<String, Object>(); if (consumes != null) { map.put("accept", consumes); } // setup endpoint options if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) { map.putAll(config.getEndpointProperties()); } if (ObjectHelper.isNotEmpty(path)) { // spark-rest uses :name syntax instead of {name} so we need to replace those Matcher matcher = pattern.matcher(path); path = matcher.replaceAll(":$1"); } // prefix path with context-path if configured in rest-dsl configuration String contextPath = config.getContextPath(); if (ObjectHelper.isNotEmpty(contextPath)) { contextPath = FileUtil.stripTrailingSeparator(contextPath); contextPath = FileUtil.stripLeadingSeparator(contextPath); if (ObjectHelper.isNotEmpty(contextPath)) { path = contextPath + "/" + path; } } String url; if (api) { url = "spark-rest:%s:%s?matchOnUriPrefix=true"; } else { url = "spark-rest:%s:%s"; } url = String.format(url, verb, path); String query = URISupport.createQueryString(map); if (!query.isEmpty()) { url = url + "?" + query; } // get the endpoint SparkEndpoint endpoint = camelContext.getEndpoint(url, SparkEndpoint.class); setProperties(endpoint, parameters); // configure consumer properties Consumer consumer = endpoint.createConsumer(processor); if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) { setProperties(consumer, config.getConsumerProperties()); } return consumer; }
protected Endpoint getMandatoryEndpoint(String uri) { Endpoint endpoint = context.getEndpoint(uri); assertNotNull("No endpoint found for uri: " + uri, endpoint); return endpoint; }
protected <T extends Endpoint> T getMandatoryEndpoint(String uri, Class<T> type) { T endpoint = context.getEndpoint(uri, type); assertNotNull("No endpoint found for uri: " + uri, endpoint); return endpoint; }
@Test public void testQuartzPersistentStoreClusteredApp() throws Exception { // boot up the database the two apps are going to share inside a clustered quartz setup AbstractXmlApplicationContext db = new ClassPathXmlApplicationContext( "org/apache/camel/component/quartz2/SpringQuartzConsumerClusteredAppDatabase.xml"); db.start(); // now launch the first clustered app which will acquire the quartz database lock and become the // master AbstractXmlApplicationContext app = new ClassPathXmlApplicationContext( "org/apache/camel/component/quartz2/SpringQuartzConsumerClusteredAppOne.xml"); app.start(); // as well as the second one which will run in slave mode as it will not be able to acquire the // same lock AbstractXmlApplicationContext app2 = new ClassPathXmlApplicationContext( "org/apache/camel/component/quartz2/SpringQuartzConsumerClusteredAppTwo.xml"); app2.start(); CamelContext camel = app.getBean("camelContext", CamelContext.class); MockEndpoint mock = camel.getEndpoint("mock:result", MockEndpoint.class); mock.expectedMinimumMessageCount(3); mock.expectedMessagesMatches(new ClusteringPredicate(true)); // let the route run a bit... Thread.sleep(5000); mock.assertIsSatisfied(); // now let's simulate a crash of the first app (the quartz instance 'app-one') log.warn("The first app is going to crash NOW!"); IOHelper.close(app); log.warn("Crashed..."); log.warn("Crashed..."); log.warn("Crashed..."); // wait long enough until the second app takes it over... Thread.sleep(20000); // inside the logs one can then clearly see how the route of the second app ('app-two') starts // consuming: // 2013-09-30 11:22:20,349 [main ] WARN erTwoAppsClusteredFailoverTest - Crashed... // 2013-09-30 11:22:20,349 [main ] WARN erTwoAppsClusteredFailoverTest - Crashed... // 2013-09-30 11:22:20,349 [main ] WARN erTwoAppsClusteredFailoverTest - Crashed... // 2013-09-30 11:22:35,340 [_ClusterManager] INFO LocalDataSourceJobStore - // ClusterManager: detected 1 failed or restarted instances. // 2013-09-30 11:22:35,340 [_ClusterManager] INFO LocalDataSourceJobStore - // ClusterManager: Scanning for instance "app-one"'s failed in-progress jobs. // 2013-09-30 11:22:35,369 [eduler_Worker-1] INFO triggered - // Exchange[ExchangePattern: InOnly, BodyType: String, Body: clustering PONGS!] CamelContext camel2 = app2.getBean("camelContext2", CamelContext.class); MockEndpoint mock2 = camel2.getEndpoint("mock:result", MockEndpoint.class); mock2.expectedMinimumMessageCount(3); mock2.expectedMessagesMatches(new ClusteringPredicate(false)); mock2.assertIsSatisfied(); // and as the last step shutdown the second app as well as the database IOHelper.close(app2, db); }
public CamelClient() { this.context = new DefaultCamelContext(); this.endpoint = context.getEndpoint("netty:tcp://localhost:{{port}}?sync=true"); this.producerTemplate = context.createProducerTemplate(); }