public void testTwoManagedCamelContextNoClashCustomPattern() throws Exception { camel1 = createCamelContext("foo", "killer-#counter#"); camel2 = createCamelContext("foo", "killer-#counter#"); camel1.start(); assertTrue("Should be started", camel1.getStatus().isStarted()); MBeanServer mbeanServer = camel1.getManagementStrategy().getManagementAgent().getMBeanServer(); ObjectName on = ObjectName.getInstance( "org.apache.camel:context=" + camel1.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); // the pattern has a counter so no clash camel2.start(); ObjectName on2 = ObjectName.getInstance( "org.apache.camel:context=" + camel2.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on2)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on2)); }
public void testTwoManagedCamelContextNoClashDefault() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } camel1 = createCamelContext("foo", null); camel2 = createCamelContext("foo", null); camel1.start(); assertTrue("Should be started", camel1.getStatus().isStarted()); MBeanServer mbeanServer = camel1.getManagementStrategy().getManagementAgent().getMBeanServer(); ObjectName on = ObjectName.getInstance( "org.apache.camel:context=" + camel1.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); // the default name pattern will ensure the JMX names is unique camel2.start(); ObjectName on2 = ObjectName.getInstance( "org.apache.camel:context=" + camel2.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on2)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on2)); }
public void testTwoManagedCamelContextClash() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } camel1 = createCamelContext("foo", "myFoo"); camel2 = createCamelContext("foo", "myFoo"); camel1.start(); assertTrue("Should be started", camel1.getStatus().isStarted()); MBeanServer mbeanServer = camel1.getManagementStrategy().getManagementAgent().getMBeanServer(); ObjectName on = ObjectName.getInstance( "org.apache.camel:context=" + camel1.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); // we use fixed names, so we will get a clash try { camel2.start(); fail("Should have thrown an exception"); } catch (VetoCamelContextStartException e) { assertTrue(e.getMessage().contains("is already registered")); } }
public static void main(String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("integration.xml"); CamelContext context = (CamelContext) ctx.getBean("camelContext"); ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(cf)); context.addRoutes( new RouteBuilder() { public void configure() { from("jms:queue:spring-tweets") .process( new Processor() { public void process(Exchange e) { System.out.println("Message: " + e.getIn().getBody()); Tweet tweet = (Tweet) e.getIn().getBody(); System.out.println("Sender: " + tweet.getFromUser()); System.out.println("Text: " + tweet.getText()); } }); } }); context.start(); while (true) {} }
@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 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(); } }
public void testMultipleLifecycleStrategies() throws Exception { CamelContext context = createCamelContext(); context.start(); Component log = new LogComponent(); context.addComponent("log", log); context.addEndpoint("log:/foo", log.createEndpoint("log://foo")); context.removeComponent("log"); context.stop(); List<String> expectedEvents = Arrays.asList( "onContextStart", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onComponentAdd", "onEndpointAdd", "onComponentRemove", "onContextStop"); assertEquals(expectedEvents, dummy1.getEvents()); assertEquals(expectedEvents, dummy2.getEvents()); }
@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(); } }
private void afterDeploymentValidation( @Observes AfterDeploymentValidation adv, BeanManager manager) { Collection<CamelContext> contexts = new ArrayList<>(); for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) { contexts.add(getReference(manager, CamelContext.class, context)); } // Add type converters to Camel contexts CdiTypeConverterLoader loader = new CdiTypeConverterLoader(); for (Class<?> converter : converters) { for (CamelContext context : contexts) { loader.loadConverterMethods(context.getTypeConverterRegistry(), converter); } } // Add routes to Camel contexts boolean deploymentException = false; Set<Bean<?>> routes = new HashSet<>(manager.getBeans(RoutesBuilder.class, ANY)); routes.addAll(manager.getBeans(RouteContainer.class, ANY)); for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) { for (Bean<?> route : routes) { Set<Annotation> qualifiers = new HashSet<>(context.getQualifiers()); qualifiers.retainAll(route.getQualifiers()); if (qualifiers.size() > 1) { deploymentException |= !addRouteToContext(route, context, manager, adv); } } } // Let's return to avoid starting misconfigured contexts if (deploymentException) { return; } // Trigger eager beans instantiation (calling toString is necessary to force // the initialization of normal-scoped beans). // FIXME: This does not work with OpenWebBeans for bean whose bean type is an // interface as the Object methods does not get forwarded to the bean instances! eagerBeans.forEach(type -> getReferencesByType(manager, type.getJavaClass(), ANY).toString()); manager .getBeans(Object.class, ANY, STARTUP) .stream() .forEach(bean -> getReference(manager, bean.getBeanClass(), bean).toString()); // Start Camel contexts for (CamelContext context : contexts) { if (ServiceStatus.Started.equals(context.getStatus())) { continue; } logger.info("Camel CDI is starting Camel context [{}]", context.getName()); try { context.start(); } catch (Exception exception) { adv.addDeploymentProblem(exception); } } // Clean-up Stream.of(converters, camelBeans, eagerBeans, cdiBeans).forEach(Set::clear); Stream.of(producerBeans, producerQualifiers).forEach(Map::clear); }
@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(); } }
public void testMessageDump() throws Exception { JAXBContext jaxb = JAXBContext.newInstance(MessageDump.class); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); CamelContext context = new DefaultCamelContext(); context.start(); message = new DefaultExchange(context).getIn(); // xml message body message.setBody("Hello World"); message.setHeader("foo", 123); String out = MessageHelper.dumpAsXml(message, true); MessageDump dump = (MessageDump) unmarshaller.unmarshal(new StringReader(out)); assertNotNull(dump); assertEquals("java.lang.String", dump.getBody().getType()); assertEquals("Hello World", dump.getBody().getValue()); assertEquals(1, dump.getHeaders().size()); assertEquals("foo", dump.getHeaders().get(0).getKey()); assertEquals("java.lang.Integer", dump.getHeaders().get(0).getType()); assertEquals("123", dump.getHeaders().get(0).getValue()); }
@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 testEndpointClass() throws Exception { final CountDownLatch latch = new CountDownLatch(3); CamelContext camelctx = new DefaultCamelContext(); camelctx.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("quartz2://mytimer?trigger.repeatCount=3&trigger.repeatInterval=100") .process( new Processor() { @Override public void process(Exchange exchange) throws Exception { latch.countDown(); } }) .to("mock:result"); } }); camelctx.start(); try { Assert.assertTrue("Countdown reached zero", latch.await(500, TimeUnit.MILLISECONDS)); } 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 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(); } }
/** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm:/localhost"); context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory)); context.addRoutes( new RouteBuilder() { public void configure() { from("ftp://127.0.0.1/orders?username=johnny&password=quest") .process( new Processor() { public void process(Exchange exchange) throws Exception { System.out.println( "\nWe just downloaded: " + exchange.getIn().getHeader("CamelFileName")); System.out.println("Body:"); System.out.println(exchange.getIn().getBody()); System.out.println("\n==================\n"); } }) .to("jms:incomingOrders"); } }); context.start(); Thread.sleep(60000); context.stop(); }
@Test public void writesResultToSender_ConfiguredViaXML() throws Exception { String receiver = "*****@*****.**"; createMailUser(receiver, "loginIdReceiver", "secretOfReceiver"); String validSender = "*****@*****.**"; createMailUser(validSender, "loginIdSender", "secretOfSender"); String commandName = "nameMe"; sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText(commandName); InputStream is = getClass().getResourceAsStream("/ardulinkmail.xml"); try { CamelContext context = new DefaultCamelContext(); loadRoutesDefinition(is, context, commandName); context.start(); try { assertThat( ((String) fetchMail("loginIdSender", "secretOfSender").getContent()), is( "SwitchDigitalPinCommand [pin=1, value=true]=OK\r\n" + "SwitchAnalogPinCommand [pin=2, value=123]=OK")); } finally { context.stop(); } } finally { is.close(); } }
@Test public void canProcessMultipleLinksWhenCommandNotKnownOnLink2() throws Exception { final String receiver = "*****@*****.**"; createMailUser(receiver, "loginIdReceiver", "secretOfReceiver"); String validSender = "*****@*****.**"; sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText("usedScenario"); Link link1 = Links.getLink(new URI(mockURI + "?num=1&foo=bar")); Link link2 = Links.getLink(new URI(mockURI + "?num=2&foo=bar")); final String to1 = makeURI( mockURI, newMapBuilder() .put("linkparams", encode("num=1&foo=bar")) .put("validfroms", validSender) .put("scenario.usedScenario", "D11=true;A12=11") .build()); final String to2 = makeURI( mockURI, newMapBuilder() .put("linkparams", encode("num=2&foo=bar")) .put("validfroms", validSender) .build()); try { CamelContext context = new DefaultCamelContext(); context.addRoutes( new RouteBuilder() { @Override public void configure() { from(localImap(receiver)) .multicast() .setAggregationStrategy(new UseOriginalAggregationStrategy()) .to(to1, to2); } }); context.start(); waitUntilMailWasFetched(); context.stop(); Link mock1 = getMock(link1); verify(mock1).switchDigitalPin(digitalPin(11), true); verify(mock1).switchAnalogPin(analogPin(12), 11); verify(mock1).close(); verifyNoMoreInteractions(mock1); Link mock2 = getMock(link2); verify(mock2).close(); verifyNoMoreInteractions(mock2); } finally { link1.close(); link2.close(); } }
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/camel.xml"); CamelContext camelContext = (CamelContext) context.getBean("camelContext"); camelContext.start(); Thread.sleep(3000); camelContext.stop(); context.close(); }
@Before public void setUp() throws Exception { startTestServer(); camelContext = new DefaultCamelContext(); camelContext.start(); setUpComponent(); template = camelContext.createProducerTemplate(); }
@Test public void writesResultToSender() 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;A2=123") .build()); SmtpServer smtpd = mailMock.getSmtp(); final String smtp = "smtp://" + smtpd.getBindTo() + ":" + smtpd.getPort() + "?username="******"loginIdReceiver" + "&password="******"secretOfReceiver" + "&debugMode=true"; CamelContext context = new DefaultCamelContext(); context.addRoutes( new RouteBuilder() { @Override public void configure() { from(localImap(receiver)) .to(ardulink) .setHeader("to", simple("${in.header.from}")) .setHeader("from", simple("${in.header.to}")) .to(smtp); } }); context.start(); try { assertThat( ((String) fetchMail("loginIdSender", "secretOfSender").getContent()), is( "SwitchDigitalPinCommand [pin=1, value=true]=OK\r\n" + "SwitchAnalogPinCommand [pin=2, value=123]=OK")); } finally { context.stop(); } }
protected void startCamelContext() throws Exception { if (camelContextService != null) { camelContextService.start(); } else { if (context instanceof DefaultCamelContext) { DefaultCamelContext defaultCamelContext = (DefaultCamelContext) context; if (!defaultCamelContext.isStarted()) { defaultCamelContext.start(); } } else { context.start(); } } }
public void testLoadFileNotFound() throws Exception { CamelContext context = new DefaultCamelContext(); context.start(); try { ResourceHelper.resolveMandatoryResourceAsInputStream( context, "file:src/test/resources/notfound.txt"); fail("Should not find file"); } catch (FileNotFoundException e) { assertTrue(e.getMessage().contains("notfound.txt")); } context.stop(); }
@Override public void deploy(Collection<RouteBuilder> routeBuilders) { try { camelContext = new DefaultCamelContext(); camelContextCustomizers.forEach(c -> c.customize(camelContext)); for (RouteBuilder routeBuilder : routeBuilders) { camelContext.addRoutes(routeBuilder); } camelContext.start(); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Activates the control channel, which will from now on behave in accordance with the routes you * set up in your bootstrap script(s). * * <p>See {@link ControlChannel#waitShutdown} and {@link ControlChannel#sendShutdownSignal()} for * instructions on shutting down an activated channel. */ public void activate() { try { log.info("Activating control channel."); final CamelContext context = getContext(); log.info("Configuring trace interceptor for {}.", context.getName()); TraceBuilder builder = new TraceBuilder(getConfig(), tracer); context.addInterceptStrategy(builder.build()); log.debug("Starting underlying camel context."); context.start(); } catch (Exception e) { throw new LifecycleException(e.getLocalizedMessage(), e); } }
public void testLoadClasspathDefault() throws Exception { CamelContext context = new DefaultCamelContext(); context.start(); InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, "log4j2.properties"); assertNotNull(is); String text = context.getTypeConverter().convertTo(String.class, is); assertNotNull(text); assertTrue(text.contains("log4j")); is.close(); context.stop(); }
public void testLoadClasspathAsUrl() throws Exception { CamelContext context = new DefaultCamelContext(); context.start(); URL url = ResourceHelper.resolveMandatoryResourceAsUrl( context.getClassResolver(), "classpath:log4j2.properties"); assertNotNull(url); String text = context.getTypeConverter().convertTo(String.class, url); assertNotNull(text); assertTrue(text.contains("log4j")); context.stop(); }
public void testLoadClasspathNotFound() throws Exception { CamelContext context = new DefaultCamelContext(); context.start(); try { ResourceHelper.resolveMandatoryResourceAsInputStream(context, "classpath:notfound.txt"); fail("Should not find file"); } catch (FileNotFoundException e) { assertEquals( "Cannot find resource: classpath:notfound.txt in classpath for URI: classpath:notfound.txt", e.getMessage()); } context.stop(); }
public void testDumpAsXmlPlainBody() throws Exception { CamelContext context = new DefaultCamelContext(); context.start(); message = new DefaultExchange(context).getIn(); // xml message body message.setBody("Hello World"); message.setHeader("foo", 123); String out = MessageHelper.dumpAsXml(message); assertTrue( "Should contain body", out.contains("<body type=\"java.lang.String\">Hello World</body>")); context.stop(); }
private void createCamelContext() throws Exception { log.info("creating context and sending message"); camelContext = new DefaultCamelContext(); camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent(BROKER_URL)); final String queueEndpointName = "activemq:queue" + QUEUE_NAME; camelContext.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from(queueEndpointName).bean(Consumer.class, "consume"); } }); camelContext.start(); final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); producerTemplate.sendBody(queueEndpointName, "message"); }