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) {} }
/** * @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(); }
private void addDTSIncomingFileRouter(final CamelContext context) throws Exception { final CIAOConfig config = CamelApplication.getConfig(context); final DTSIncomingFileRouterRoute route = new DTSIncomingFileRouterRoute(); // IN folder properties route.setDTSInUri(context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/IN")); route.setDTSMessageReceiverUri("direct:dtsMessageReceiver"); route.setInIdempotentRepositoryId("dtsReceiverIdempotentRepository"); route.setInInProgressRepositoryId("dtsReceiverInProgressRepository"); // SEND folder properties route.setDTSSentUri(context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/SENT")); route.setDTSMessageSendNotificationReceiverUri("direct:dtsMessageSendNotificationReceiver"); route.setSentIdempotentRepositoryId("dtsSentIdempotentRepository"); route.setSentInProgressRepositoryId("dtsSentInProgressRepository"); route.setDTSFilePrefix(Strings.nullToEmpty(config.getConfigValue("dts.filePrefix"))); // common properties route.setMailboxes(Arrays.asList(config.getConfigValue("dts.senderMailbox"))); final Set<String> workflowIds = Sets.newHashSet(config.getConfigValue("dts.workflowId")); for (final String workflowId : config.getConfigValue("dts.receiverWorkflowIds").split(",")) { if (!workflowId.trim().isEmpty()) { workflowIds.add(workflowId); } } route.setWorkflowIds(workflowIds); context.addRoutes(route); }
@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(); } }
@Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); // simulate JMS with the SEDA component context.addComponent("jms", context.getComponent("seda")); return context; }
@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 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(); } }
@Override protected Object doExecute() throws Exception { CamelContext camel = camelController.getCamelContext(context); if (camel == null) { System.err.println("CamelContext " + context + " not found."); return null; } BacklogTracer backlogTracer = BacklogTracer.getBacklogTracer(camel); if (backlogTracer == null) { backlogTracer = (BacklogTracer) camel.getDefaultBacklogTracer(); } backlogTracer.setEnabled(true); if (backlogSize != null) { backlogTracer.setBacklogSize(backlogSize); } if (removeOnDump != null) { backlogTracer.setRemoveOnDump(removeOnDump); } backlogTracer.setTracePattern(pattern); backlogTracer.setTraceFilter(filter); System.out.println( "BacklogTracer started on " + camel.getName() + " with size: " + backlogTracer.getBacklogSize()); return null; }
@Override protected void doStart() throws Exception { ServiceHelper.startServices(output, outputAsync, deadLetter); // use a shared scheduler if (executorService == null || executorService.isShutdown()) { // camel context will shutdown the executor when it shutdown so no need to shut it down when // stopping if (executorServiceRef != null) { executorService = camelContext .getExecutorServiceStrategy() .lookupScheduled(this, "ErrorHandlerRedeliveryTask", executorServiceRef); if (executorService == null) { throw new IllegalArgumentException( "ExecutorServiceRef " + executorServiceRef + " not found in registry."); } } else { executorService = camelContext .getExecutorServiceStrategy() .newScheduledThreadPool(this, "ErrorHandlerRedeliveryTask"); } } // determine if redeliver is enabled or not redeliveryEnabled = determineIfRedeliveryIsEnabled(); if (log.isDebugEnabled()) { log.debug("Redelivery enabled: {} on error handler: {}", redeliveryEnabled, this); } }
@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(); } }
@Override public Transformer put(TransformerKey key, Transformer transformer) { // at first we must see if the key already exists and then replace it back, so it stays the same // spot Transformer answer = staticMap.remove(key); if (answer != null) { // replace existing staticMap.put(key, transformer); return answer; } answer = super.remove(key); if (answer != null) { // replace existing super.put(key, transformer); return answer; } // we want endpoints to be static if they are part of setting up or starting routes if (context.isSetupRoutes() || context.isStartingRoutes()) { answer = staticMap.put(key, transformer); } else { answer = super.put(key, transformer); } return answer; }
@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(); }
protected CamelContext createPropertiesPlaceholderAwareContext(Properties supplementalProperties) throws IOException { Properties properties = new Properties(supplementalProperties); properties.load(AbstractJsseParametersTest.class.getResourceAsStream("test.properties")); if (supplementalProperties != null) { Properties mergedProps = new Properties(); Set<String> keys = new HashSet<String>(); keys.addAll(properties.stringPropertyNames()); keys.addAll(supplementalProperties.stringPropertyNames()); for (String key : keys) { mergedProps.setProperty(key, properties.getProperty(key)); } properties = mergedProps; } properties.store( new FileOutputStream("./target/jsse-test.properties"), "Generated by " + AbstractJsseParametersTest.class.getName()); PropertiesComponent pc = new PropertiesComponent(); pc.setLocation("file:./target/jsse-test.properties"); CamelContext context = new DefaultCamelContext(); context.addComponent("properties", pc); return context; }
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")); } }
@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(); } }
@Override public Object execute(CamelController camelController, PrintStream out, PrintStream err) throws Exception { final List<CamelContext> camelContexts = camelController.getCamelContexts(); final Map<String, Integer> columnWidths = computeColumnWidths(camelContexts); final String headerFormat = buildFormatString(columnWidths, true); final String rowFormat = buildFormatString(columnWidths, false); if (camelContexts.size() > 0) { out.println( String.format( headerFormat, CONTEXT_COLUMN_LABEL, STATUS_COLUMN_LABEL, UPTIME_COLUMN_LABEL)); out.println(String.format(headerFormat, "-------", "------", "------")); for (final CamelContext camelContext : camelContexts) { out.println( String.format( rowFormat, camelContext.getName(), camelContext.getStatus(), camelContext.getUptime())); } } return null; }
@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(); } }
/** * Generate a "help" message. * * @param exchange the incoming message */ public void process(final Exchange exchange) throws IOException { final Message in = exchange.getIn(); final CamelContext context = exchange.getContext(); final String fedora; final String endpoint; try { fedora = context.resolvePropertyPlaceholders("{{fcrepo.baseUrl}}"); endpoint = InetAddress.getLocalHost().getHostName() + ":" + context.resolvePropertyPlaceholders("{{rest.port}}") + context.resolvePropertyPlaceholders("{{rest.prefix}}"); } catch (final Exception ex) { throw new RuntimeCamelException("Could not resolve property placeholders", ex); } final StringBuilder sb = new StringBuilder(); sb.append("Geneva Synchronization Service\n\n"); sb.append("\tConfigured Fedora Location: " + fedora + "\n"); sb.append("\tConfigured REST Endpoint: " + endpoint + "\n\n"); sb.append("You can POST to defined endpoint, and it will begin\n"); sb.append("a re-synchronization task with the configured datastore.\n\n"); sb.append("For example:\n\n"); sb.append("\tcurl -XPOST " + endpoint + "\n\n"); in.setBody(sb.toString()); }
/** * Resolves the XStream instance to be used by this data format. If XStream is not explicitly set, * new instance will be created and cached. * * @param context to be used during a configuration of the XStream instance * @return XStream instance used by this data format. */ public XStream getXStream(CamelContext context) { if (xstream == null) { xstream = createXStream(context.getClassResolver(), context.getApplicationContextClassLoader()); } return xstream; }
@Override protected CamelContext createCamelContext() throws Exception { // Since the Camel BlueprintComponentResolver does not execute outside // of an OSGi container, we cannot // rely on the CatalogComponentResolver to be used for resolving the // CatalogComponent when Camel loads the route. // Therefore, we Mock what the CatalogComponent's blueprint.xml file // would have done by creating a // CatalogComponent explicitly and adding it to the CamelContext used // for this unit test. // Configure PojoSR to be our mock OSGi Registry final PojoServiceRegistry reg = new PojoServiceRegistryFactoryImpl().newPojoServiceRegistry(new HashMap()); final BundleContext bundleContext = reg.getBundleContext(); final CamelContext camelContext = super.createCamelContext(); final CatalogComponent catalogComponent = new CatalogComponent(); catalogComponent.setBundleContext(bundleContext); catalogFramework = mock(CatalogFramework.class); catalogComponent.setCatalogFramework(catalogFramework); camelContext.addComponent(CatalogComponent.NAME, catalogComponent); return camelContext; }
private static Map<String, Integer> computeColumnWidths( final Iterable<CamelContext> camelContexts) throws Exception { if (camelContexts == null) { throw new IllegalArgumentException( "Unable to determine column widths from null Iterable<CamelContext>"); } else { int maxNameLen = 0; int maxStatusLen = 0; int maxUptimeLen = 0; for (final CamelContext camelContext : camelContexts) { final String name = camelContext.getName(); maxNameLen = java.lang.Math.max(maxNameLen, name == null ? 0 : name.length()); final String status = camelContext.getStatus().toString(); maxStatusLen = java.lang.Math.max(maxStatusLen, status == null ? 0 : status.length()); final String uptime = camelContext.getUptime(); maxUptimeLen = java.lang.Math.max(maxUptimeLen, uptime == null ? 0 : uptime.length()); } final Map<String, Integer> retval = new Hashtable<String, Integer>(3); retval.put(NAME_COLUMN_LABEL, maxNameLen); retval.put(STATUS_COLUMN_LABEL, maxStatusLen); retval.put(UPTIME_COLUMN_LABEL, maxUptimeLen); return retval; } }
protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); camelContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory)); return camelContext; }
private boolean addRouteToContext( Bean<?> routeBean, Bean<?> contextBean, BeanManager manager, AfterDeploymentValidation adv) { try { CamelContext context = getReference(manager, CamelContext.class, contextBean); try { Object route = getReference(manager, Object.class, routeBean); if (route instanceof RoutesBuilder) { context.addRoutes((RoutesBuilder) route); } else if (route instanceof RouteContainer) { context.addRouteDefinitions(((RouteContainer) route).getRoutes()); } else { throw new IllegalArgumentException( "Invalid routes type [" + routeBean.getBeanClass().getName() + "], " + "must be either of type RoutesBuilder or RouteContainer!"); } return true; } catch (Exception cause) { adv.addDeploymentProblem( new InjectionException( "Error adding routes of type [" + routeBean.getBeanClass().getName() + "] " + "to Camel context [" + context.getName() + "]", cause)); } } catch (Exception exception) { adv.addDeploymentProblem(exception); } return false; }
@Override protected CamelContext createCamelContext() throws Exception { final CamelContext context = super.createCamelContext(); // read Olingo component configuration from TEST_OPTIONS_PROPERTIES final Properties properties = new Properties(); try { properties.load(getClass().getResourceAsStream(TEST_OPTIONS_PROPERTIES)); } catch (Exception e) { throw new IOException( String.format("%s could not be loaded: %s", TEST_OPTIONS_PROPERTIES, e.getMessage()), e); } Map<String, Object> options = new HashMap<String, Object>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { options.put(entry.getKey().toString(), entry.getValue()); } final Olingo2Configuration configuration = new Olingo2Configuration(); IntrospectionSupport.setProperties(configuration, options); // add OlingoComponent to Camel context final Olingo2Component component = new Olingo2Component(context); component.setConfiguration(configuration); context.addComponent("olingo2", component); return context; }
@Lazy @Bean(name = "sql-stored-component") @ConditionalOnClass(CamelContext.class) @ConditionalOnMissingBean(SqlStoredComponent.class) public SqlStoredComponent configureSqlStoredComponent( CamelContext camelContext, SqlStoredComponentConfiguration configuration) throws Exception { SqlStoredComponent component = new SqlStoredComponent(); component.setCamelContext(camelContext); Map<String, Object> parameters = new HashMap<>(); IntrospectionSupport.getProperties(configuration, parameters, null, false); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object value = entry.getValue(); Class<?> paramClass = value.getClass(); if (paramClass.getName().endsWith("NestedConfiguration")) { Class nestedClass = null; try { nestedClass = (Class) paramClass.getDeclaredField("CAMEL_NESTED_CLASS").get(null); HashMap<String, Object> nestedParameters = new HashMap<>(); IntrospectionSupport.getProperties(value, nestedParameters, null, false); Object nestedProperty = nestedClass.newInstance(); IntrospectionSupport.setProperties( camelContext, camelContext.getTypeConverter(), nestedProperty, nestedParameters); entry.setValue(nestedProperty); } catch (NoSuchFieldException e) { } } } IntrospectionSupport.setProperties( camelContext, camelContext.getTypeConverter(), component, parameters); return component; }
@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(); } }
@Override protected DistributionEnvelopeSenderRoute createDistributionEnvelopeSenderRoute( final CamelContext context, final CIAOConfig config) throws Exception { final DTSDistributionEnvelopeSenderRoute route = new DTSDistributionEnvelopeSenderRoute(); route.setDTSMessageSenderUri( context.resolvePropertyPlaceholders("file://{{dts.rootFolder}}/OUT")); route.setDTSMessageSendNotificationReceiverUri("direct:dtsMessageSendNotificationReceiver"); route.setDTSTemporaryFolder(context.resolvePropertyPlaceholders("{{dts.temporaryFolder}}")); route.setDTSFilePrefix(Strings.nullToEmpty(config.getConfigValue("dts.filePrefix"))); route.setIdGenerator(get(context, IdGenerator.class, "dtsIdGenerator")); // File housekeeping final DTSFileHousekeeper fileHousekeeper = new DTSFileHousekeeper(); fileHousekeeper.setDestinationFolder( context.resolvePropertyPlaceholders("{{dts.completedFolder}}")); route.setFileHousekeeper(fileHousekeeper); final DTSFileHousekeeper errorFileHousekeeper = new DTSFileHousekeeper(); errorFileHousekeeper.setDestinationFolder( context.resolvePropertyPlaceholders("{{dts.errorFolder}}")); route.setErrorFileHousekeeper(errorFileHousekeeper); final ControlFile prototype = new ControlFile(); prototype.setWorkflowId(config.getConfigValue("dts.workflowId")); prototype.setFromDTS(config.getConfigValue("dts.senderMailbox")); route.setPrototypeControlFile(prototype); return route; }
@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 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); }
@Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); // to force a different management name than the camel id context.getManagementNameStrategy().setNamePattern("19-#name#"); return context; }