camel_from_the_field
TRANSCRIPT
Red Hat | Bryan Saunders
Camel from the FieldBryan Saunders Feb 16, 2015
AgendaIntroduction to Camel
What is CamelCamel FeaturesEnterprise Integration PatternsKey Components
Camel ArchitectureSupported PlatformsCamel Hands On
Common EIPsCamel on EAPUsing JMSWeb Services
Future of CamelQ & A
Introduction to Camel
What is CamelApache Camel ™ is a versatile open-source integration framework
based on known Enterprise Integration Patterns.
- Apache Camel Website
Apache Camel is an open source Java framework that focuses onmaking integration easier and more accessible to developers. It does
this by providing: concrete implementations of all the widely usedEIPs, connectivity to a great variety of transports and APIs, and easyto use Domain Specific Languages (DSLs) to wire EIPs and transports
together
- Jonathan Anstey
Why an Integration FrameworkIntegration is Critical for BusinessFramework does the Heavy LiftingLets you Focus on the ProblemPrevents Re-inventing the Wheel
History of CamelStarted in March 2007Founded by
James StrachanRob DaviesHiram ChirinoGuillaume Nodet
First Release in June 2007Spawned from Apache ServiceMix and Apache ActiveMQ
Camel FeaturesVery Leightweight , Consists of only a handful of JARsEasy ConfigurationNo Heavy SpecificationNo Container DependenciesPayload Agnostic
Simple ProgrammingMinimal ConfigurationDSL Based Programming6 DSL's and Counting
Java DSLSpring XMLBlueprint XMLRest DSLGroovy DSLScala DSLKotlin DSL in the works
Java DSL from("file:src/data?noop=true") .choice() .when(xpath("/person/city = 'London'")) .to("file:target/messages/uk") .otherwise() .to("file:target/messages/others");
Spring XML <route> <from uri="direct:a"/> <choice> <when> <xpath>$foo = 'bar'</xpath> <to uri="direct:b"/> </when> <when> <xpath>$foo = 'cheese'</xpath> <to uri="direct:c"/> </when> <otherwise> <to uri="direct:d"/> </otherwise> </choice></route>
Rest DSL
rest("/say") .get("/hello").to("direct:hello") .get("/bye").consumes("application/json").to("direct:bye")
<rest path="/say"> <get uri="/hello"> <to uri="direct:hello"/> </get> <get uri="/bye" consumes="application/json"> <to uri="direct:bye"/> </get></rest>
Components191 Components and countingComponent for pretty much anythingMost commonley used components
CXFCXFRSJMSActiveMQAMQPInfinispanCDIDrools
Lots of Componentsahc aws-ddb beanstalk cometid dataformat ejb
ahc-ws aws-sdb bean-validator context dataset eleasticsearch
amqp aws-ses box controlbus direct spring-event
apns aws-sns browse couchdb direct-vm eventadmin
atmosphere aws-sqs cache crypto dns exec
atom aws-swf class cxf disruptor facebook
avro aws-s3 chunk cxfbean docker file
aws-cw bean cmis cxfrs dropbox flatpack
More Componentsfreemarker google-drive hdfs imaps jira krati
ftp gogle-mail hdfs2 irc jms language
ftps gmail hl7 javaspace jmx ldap
gauth geocoder infinispan jclouds jpa linkedin
ghttp github http jcr jsch log
glogin guava-eventbus http4 jdbc jt400 lucene
gtask hazelcast ibatis jetty kafka metrics
google-calendar hbase imap jgroups kestrel mina
So Many Componentsmina2 nagios pax-logging rabbitmq rss sips
mock netty pop3 ref salesforce sjms
mongodb netty4 pop3s rest sap-netweaver smtp
mgtt netty-http printer restlet schematron smpp
msv netty4-http properties rmi seda smpps
mustache olingo2 quartz rnc servlet snmp
mvel openshift quartz2 rng sftp solr
mybatis optaplanner quickfix routebox sip spark-rest
Hundreds of Componentssplunk stax ssh xquery db4o nmr
spring-boot stream validation xslt esper rcode
spring-batch stomp velocity yammer fabric-amq scalate
spring-int string-temp vm zookeeper fabric-fabric smooks
spring-ldap stub weather activemq fabric-master spring-neo4j
spring-redis test websocket activemq-broker hibernate virutalbox
spring-ws timer xml-security activiti jbi zeromq
sql twitter xmpp couchbase jcifs
Error HandlingTry...Catch...FinallyException Clause in Java DSLError Handlers
Default Error HandlerDead Letter ChannelLogging Error HandlerNo Error HandlerTransaction Error Handler
Support for Exponential Backoff of Retries
Error Handling Code from("direct:start") .doTry() .process(new ProcessorFail()) .to("mock:result") .doCatch(IOException.class, IllegalStateException.class) .to("mock:catch") .doFinally() .to("mock:finally") .end();
onException(ValidationException.class) .to("activemq:validationFailed");
onException(ShipOrderException.class) .to("activemq:shipFailed");
from("seda:order").to("bean:processOrder");
errorHandler(deadLetterChannel("jms:queue:dead") .useOriginalMessage() .mamimumRedeliveries(5) .redeliverDelay(5000));
errorHandler(defaultErrorHandler() .allowRedeliveryWhileStopping(false) .maximumRedeliveries(20) .redeliveryDelay(1000) .retryAttemptedLogLevel(LoggingLevel.INFO));
Redelivery Delay PatternsAllows for custom backoff of retries.Syntax: limit:delay;limit2:delay2;limit3:delay3;...;limitN:delayNIf delayPattern=5:1000;10:5000;20:20000 then we get
Redelivery attempt number 1..4 = 0 sec (as the first group starts with 5)Redelivery attempt number 5..9 = 1 sec (the first group)Redelivery attempt number 10..19 = 5 sec (the second group)Redelivery attempt number 20.. = 20 sec (the last group)
SecurityFour Broad Categories of Security Offered
Route SecurityPayload SecurityEndpoint SecurityConfiguration Security
Route SecurityPolicy driven security for routes or route segments
Shiro SecuritySpring Security
Payload SecurityEncryption and decryption services for secure paylods
XMLSecurity DataFormat (XML Encryption support)XML Security component (XML Signature support)Crypto DataFormat (Encryption + PGP support)Crypto component (Signature support)
Endpoint SecuritySome components can be secured, but not all
Jetty - HTTP Basic & SSLCXF - HTTP Basic & WS-SecuritySpring Web Services - HTTP Basic & WS-SecurityNetty - SSLMINA - SSLCometd - SSLJMS - JAAS and SSL for client <--> broker communication
Configuration SecurityExternalize configuration properties
PropertiesJasypt - Encrypted valuesJSSE Utility - Configure SSL/TLS
ScalableLoad Balancing PoliciesThread and Service PoolsAsynchronous APIClustering
Same JVM & Context - Use direct or sedaSame JVM, Different Context - Use vmDifferent JVM - Use jms, activemq, ftp, etc...OSGi - Use Normalized Message Router (NMR)
HA & FailoverNot natively supportedProvided by the following components
Camel Fabric Master componentCamel ZooKeeper via a Route policyCamel JGroups
TestableNative test frameworksSupports unit and integration TestingBuilt in mock & stub supportAdvanced testing with NotifyBuilder and AdviceWithWorks with 3rd party test frameworks
PaxExamArquillianJUnitTestNG
Available Test HarnessesName Component Description
CamelTest
camel-test Standalone Java library to create Camel test cases using a single Javaclass for all your configuration and routing without using Spring orGuice
SpringTesting
camel-test-spring
Supports JUnit 4 tests that bootstrap a test environment using Springwithout needing to be familiar with Spring Test.
BlueprintTesting
camel-test-blueprint
Provides the ability to do unit testing on blueprint configurations
Guice camel-guice
Uses Guice to dependency inject your test classes
CamelTestNG
camel-testng
Supports plain TestNG based tests with or without Spring or Guice
Example Camel Test public class FilterTest extends CamelTestSupport @EndpointInject(uri = "mock:result") protected MockEndpoint resultEndpoint; @Produce(uri = "direct:start") protected ProducerTemplate template; @Test public void testSendMatchingMessage() throws Exception String expectedBody = "matched"; resultEndpoint.expectedBodiesReceived(expectedBody); template.sendBodyAndHeader(expectedBody, "foo", "bar"); resultEndpoint.assertIsSatisfied(); @Override protected RouteBuilder createRouteBuilder() return new RouteBuilder() public void configure() from("direct:start").filter(header("foo").isEqualTo("bar")).to("mock:result"); ;
ToolingSeveral tools exist for working with and monitoring Camel
Camel Maven PluginJBoss Tools for CamelTalend Open StudioHawtio Camel Plugin
JBoss Tools for Camel
JBoss Tools for Camel
Enterprise Integration PatternsSimilar to Design PatternsFocused specifically on IntegrationWritten by Gregor Hohpe & Bobby Wolf65 Documented PatternsCamel supports 53 of them
Enterprise Integration Patterns
EIP to Camel
Endpoint newOrder = endpoint("activemq:queue:newOrder");Predicate isWidget = xpath("/order/product ='widget'");Endpoint widget = endpoint("activemq:queue:widget");Endpoint gadget = endpoint("activemq:queue:gadget");
from(newOrder) .choice() .when(isWidget) .to(widget) .otherwise() .to(gadget) .end();
Architecture
High Level Architecture
Domain Specific LanguageUsed for defining routesMultiple DSL's exist
RouteSet of rules that define message flowConsists of:
EndpointsEIP ConstructsProcessors
EndpointImplementation of the Message Endpoint patternCreated by componentsReferred to by uniue URI's in the DSLConsumers receive messagesProducers send messages
ComponentEssentially a factory for Endpoint instancesAdds functionality to CamelCustom components extend DefaultComponent
ProcessorConsumes message exchangesProcessor interface for building custom ProcessorsUsed to encapsulate custom business logicCan be turned into a full Component
Message ExchangeSupports multiple Exchange Patterns
One Way Event Message EIPRequest Reply Message EIP
Implements Message EIP
Supported Platforms
Multiple PlatformsAnywhere that supports Java 1.6
Standard JVMOSGiTomcatApplication ServersSpring
Camel and Red HatIncluded in JBoss FuseIncluded in JBoss Fuse Service Works
Run as part of SwitchYardRun outside of SwitchYard on EAP Container
Supported on EAP 6.1.1+
Requires JBoss Fuse & JBoss EAP SubscriptionMust use Camel libraries from JBoss Fuse
JBoss Fuse
JBoss Fuse Service Works
Fuse or Service WorksUse Fuse if...
Dont use Java or JEEDont use EAPUse OSGi or KarafGovernance is not neededNo SCA requirement
Use Fuse Service Works if...
Use JEEWant to use JEE in ServicesCurrently use EAPNeed GovernanceNeed SCA or already use SwitchYard
Camel ConsiderationsFor Fuse...
Can use Blueprint/Spring/Java DSL for RoutesMost configuration is done via XMLTesting relies on PaxExam and Built in Camel Test Frameworks
For Fuse Service Works w/ SwitchYard...
SwitchYard limits amount of Components you can useJEE Stack well SupportedNo XML ConfigurationCan make use of Arquillian
For Camel on EAP...
Can use CDI or SpringJEE Stack not currently well supportedMost Components use Spring for configurationCan make use of Arquillian
Hands On Camel
Camel on EAPUse Camel without SwitchYard or KarafSupported on EAP 6.1.1 and up with Camel 2.12 Red Hat LibrariesTwo ways to use Libraries
Packaged inside ApplicationDeployed as EAP Module
Camel Started with 3 methods
Spring ContextLoaderListenerServletListener ComponentCDI Component
Starting with SpringRequires SpringBest if already using SpringCamel uses Spring's Bean RegistryStarted using Spring ContextLoaderListenerConfiguration very similar to Fuse with Spring or Blueprint
Spring ExampleExample web.xml
<webapp ...> <displayname>soapcontractfirst</displayname>
<! Config Location > <contextparam> <paramname>contextConfigLocation</paramname> <paramvalue>classpath:METAINF/spring/*.xml</paramvalue> </contextparam>
<! Spring Listener Servlet > <listener> <listenerclass>org.springframework.web.context.ContextLoaderListener</listenerclass> </listener></webapp>
Spring ExampleExample camel-route.xml
<beans ...>
<import resource="classpath:METAINF/spring/camelcxf.xml" /> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="cxf:bean:orderEndpoint" /> <log message=">> Received SOAP Endpoint: $body"></log> <setBody> <simple>DONE</simple> </setBody> </route> </camelContext>
</beans>
Starting with Spring Demo
https://github.com/bsaunder/camel/tree/master/eap_6/soap-contract-first
Starting without SpringDoes not Require SpringBest if using JEE, but do not need to access Camel with JEE StackCamel uses a Simple Map based Bean Registry (Can also use JNDI)Started using CamelServletContextListenerConfiguration XML Based
Route Builders defined in web.xml
ServletListener ConfigurationExample web.xml
<webapp ...> <displayname>servlet_listener</displayname>
<! Set CamelContext name > <contextparam> <paramname>name</paramname> <paramvalue>myCamelContext</paramvalue> </contextparam> <contextparam> <paramname>routeBuilderJavaRoute</paramname> <paramvalue>net.bryansaunders.camel.servlet_listener.JavaRoute</paramvalue> </contextparam> <contextparam> <paramname>routeBuilderXmlRoute</paramname> <paramvalue>classpath:camelroutes.xml</paramvalue> </contextparam> <listener> <listenerclass>org.apache.camel.component.servletlistener.SimpleCamelServletContextListener</listenerclass> </listener>
</webapp>
ServletListener Component Demo
https://github.com/bsaunder/camel/tree/master/eap_6/servlet_listener
Bootstrapping with CDIDoes not Require Spring or use ServletsBest if using JEE, Especially CDICamel uses CDI Bean ManagerStarted using an @Startup @Singleton Annotated BeanAll Configuration done in Java, No XML
Camel Bootstrap ClassMust be a Singleton, @SingletonMust run at Startup. @StartupInject an instance of CdiCamelContext
Adds a CDI Bean Registry that allows lookup of CDI Beans whenInstantiated
@PostConstruct method should Configure/Start Context and AddRoutes@PreDestroy should Stop Camel Context
Example Bootstrap Class
@Singleton@Startuppublic class Bootstrap
@Inject private CdiCamelContext camelCtx; @Inject private SomeRouteBuilder someRoute;
@PostConstruct public void init() throws Exception this.camelCtx.addRoutes(someRoute); this.camelCtx.setName("mycamelcontext"); this.camelCtx.start();
@PreDestroy public void stop() throws Exception this.camelCtx.stop();
Using the XML Based DSLSpring and Blueprint XML routes can also be usedRoutes loaded from XML file in Bootstrap Class
InputStream is = this.getClass().getClassLoader().getResourceAsStream("camelroutes.xml");if (is != null) RoutesDefinition routes = this.camelCtx.loadRoutesDefinition(is); this.camelCtx.addRouteDefinitions(routes.getRoutes());
CDI Component Demo
https://github.com/bsaunder/camel/tree/master/eap_6/cdi-soap-consume
Configuration with Camel CDINo Spring Config or ContextWith Camel CDI Components are Configured in JavaConfigured on the Camel ContextAll Components can be Configured
Configuring ComponentsConfigred in your Bootstrap ClassMust be Configured Prior to Start of Camel ContextLookup Existing Components with getComponent()
Lookup via Registered Name - jms, activemq, etc...Most Core Components already Registered on ContextLazily initialize Components that arent Registered
Add New Components with addComponent()
Sample Configuration
@Resource(mappedName = "java:/ConnectionFactory")private ConnectionFactory jmsConnFactory;
...
JmsConfiguration jmsConfig = new JmsConfiguration(jmsConnFactory);jmsConfig.setConcurrentConsumers(10);jmsConfig.setMaxConcurrentConsumers(10);
Component component = this.camelCtx.getComponent("jms");if (component != null) JmsComponent jmsComponent = (JmsComponent) component; jmsComponent.setConfiguration(jmsConfig); else this.camelCtx.addComponent("jms", new JmsComponent(jmsConfig));
JMS Configuration Demo
https://github.com/bsaunder/camel/tree/master/eap_6/cdi-jms
Camel & JBoss A-MQCamel has no JBoss A-MQ ComponentSeveral ways to Connect to A-MQ from Camel
JMS ComponentActiveMQ ComponentBean using JMS API
Camel JMS vs ActiveMQJMS component
Based on Spring JMSUses Spring JmsTemplate for SendingUses Spring MessageListenerContainer for Consuming
ActiveMQ Component
Based on JMS ComponentOptimized for ActiveMQSupports ActiveMQ Specific Features such as Destination Options
MDB vs Camel JMSUsing an MDB Generally offers Higher PerformanceUse a Producer Template to send to a Direct Camel RouteMDB Uses Containers Pooled Resource AdapterCamel JMS Component Built on Spring JMS
Uses the DefaultMessageListenerContainerShares a Single Connection for all Consumers
Attachments over JMSNot Supported by Camel or any of its JMS based ComponentsTwo Solutions
Move Attachment into Message Body with a Custom ObjectUse the Claim Check EIP
Claim Check EIPReplaces Message Data with a Unique ID for Future RetrievalData stored into Persistent Data StoreData Retrieved later using Unique ID
Claim Check EIP Example
from("direct:start").to("bean:checkLuggage").to("jms:queue:SomeQueue"); from("jms:queue:SomeQueue").to("bean:dataEnricher").log("Do Stuff");
public static final class CheckLuggageBean public void checkLuggage(Exchange exchange, @Body String body, @XPath("/order/@custId") String custId) dataStore.put(custId, body); exchange.getIn().setHeader("claimCheck", custId); exchange.getIn().setBody(null);
public static final class DataEnricherBean public void addDataBackIn(Exchange exchange, @Header("claimCheck") String claimCheck) exchange.getIn().setBody(dataStore.get(claimCheck)); dataStore.remove(claimCheck); exchange.getIn().removeHeader("claimCheck");
Web Services with Camel CDIWeb Services are common place in IntegrationCamel has Several Web Service Related Components
CXFCXFRSSpring Web ServicesRestSpark-Rest
Some of the ProblemsSpring Web Services require SpringRest and Spark-Rest Components not Available
Part of Camel 2.14
Only Leaves CXF and CXFRS
Dependent on Spring for ConfigurationNeeds Servlet to Start
Using Camel CXF with Camel CDIConfigured via Camel ContextEndpoints created ProgrammaticallyRequires Http Jetty Transport to Publish Service
CxfEndpoint orderEndpoint = new CxfEndpoint();orderEndpoint.setAddress("http://localhost:9595/order");orderEndpoint.setServiceClass("net.bryansaunders.camel.OrderEndpoint");orderEndpoint.setWsdlURL("wsdl/order.wsdl");orderEndpoint.setCamelContext(this.camelCtx);camelCtx.addEndpoint("cxf:bean:orderEndpoint", orderEndpoint);
Alternate SolutionUse the Web Services SubsystemDeploy Web Services using JAX-WSUse Producer Template to Call Camel from ImplementationUse a Direct RouteRoute is more Flexible, Can be Called without SOAPEasier to Configure more Advanced Web Services
JAX-WS Demo
https://github.com/bsaunder/camel/tree/master/eap_6/cdi-jaxws-publish
Camel & SwitchYard Test SupportCamel and SwitchYard both include Test FrameworksMocks created with Camel Test cannot replace SwitchYard Endpoints
Intercept Messages and Route to Mockable Endpoint
SwitchYard expects Route to Start with SwitchYard Endpoint
Define two RoutesFirst Route has SwitchYard Endpoint and Forwards to Second RouteSecond Route starts with a Mockable Endpoint (Usually Direct)
Camel & SwitchYard Test Support
public class SomeTestClass extends CamelTestSupport private static final String MESSAGE = "..."; @Test public void someTest() throws Exception MockEndpoint endpoint = getMockEndpoint("mock:switchyard:WebOutService"); endpoint.expectedBodiesReceived(MESSAGE); template.sendBody("direct:WebInService", MESSAGE); endpoint.assertIsSatisfied(); @Override protected RouteBuilder createRouteBuilder() throws Exception return new WebInServiceRoute() @Override public void configure() throws Exception interceptSendToEndpoint("switchyard://WebOutService") .skipSendToOriginalEndpoint().to( "mock:switchyard:WebOutService"); super.configure(); ;
from("switchyard://WebInService").to("direct:WebInService"); from("direct:WebInService").log("Doing something very clever").to("switchyard://WebInCanonicalSystem");
Testing with Pax ExamIn-Container Testing Framework for OSGi, Java EE, and CDISimilar to ArquillianUses a Test Driver and a Test Container
Test Driver launches the OSGi framework and the system under testProbe Builds Bundles from Test Cases and Injects into the Container
JUnit and TestNG DriversDrivers are Annotation Based
Pax ExamSupports All Major OSGi Frameworks
Equinox, Felix, Knoplerfish, Karaf
Multiple Strategies for Restarting and Reusing the Running OSGiFramework for each TestTwo Types of Containers
Native runs in the same VM as the Test DriverForked runs in a separate VM from the Test Driver
Pax Exam Karaf ContainerEases Integration Testing with Pax Exam and KarafProvides an Actual Karaf Container for TestingSupports any Karaf Based Distribution (Fuse, Service Mix, Geronimo)Maintained as Official Pax Exam modulesAdds Karaf Specific Support
Container ConfigurationControls the Host ContainerDetermines the Set of Bundles and Features provisioned to the ContainerBuilds and Configures the Container EnvironmentMultiple Methods of Specifying Configuration Options
One or more Methods Annotated with @Configuration that return Option[]
ProbeArtifact added to the Container for TestingCreated on the Fly by Pax TinyBundlesContains the Current Test Classes and All Classes/Resources under theSame RootCan be Configured inside the Test Class if needed
Writing Testable RoutesAnything that needs to Change during a Test should be Externalized
All EndpointsConfiguration ValuesHeader NamesEtc...
Integrations with External Resources should be Mock able
Database ConnectionsMessaging BrokersEtc...
Generating Dependency FileGenerate using the Maven Plugin
<plugin> <groupId>org.apache.servicemix.tooling</groupId> <artifactId>dependsmavenplugin</artifactId> <version>1.2</version> <executions> <execution> <id>generatedependsfile</id> <goals> <goal>generatedependsfile</goal> </goals> </execution> </executions></plugin>
Should use the versionAsInProject() method in Container Configuration
Configuring the ContainerContainer Configuration is Done with the @Configuration AnnotationMethod should Return Option[]Used for
Specifying the DistributionSetting Distribution Properties
Log Level, Unpack Directory, Start Method, Etc…Loading Features / BundlesAdding/Modifying Distribution Environment
Property Files, Etc…
Example Configuration
@Configurationpublic static Option[] configure() throws Exception return new Option[] karafDistributionConfiguration() .frameworkUrl( maven().groupId("org.apache.karaf").artifactId("apachekaraf").type("zip") .versionAsInProject()).useDeployFolder(false).karafVersion("3.0.0") .unpackDirectory(new File("target/paxexam/unpack/")), logLevel(LogLevel.WARN), features( maven().groupId("org.apache.camel.karaf").artifactId("apachecamel").type("xml") .classifier("features").versionAsInProject(), "camelblueprint", "cameljms", "cameljpa", "camelmvel", "cameljdbc", "camelcxf", "cameltest"), KarafDistributionOption.editConfigurationFilePut("etc/org.ops4j.pax.url.mvn.cfg", "org.ops4j.pax.url.mvn.proxySupport", "true"), keepRuntimeFolder(), KarafDistributionOption.replaceConfigurationFile("etc/com.walmart.mqm.gateway.routes.cfg", new File( "src/test/resources/com.walmart.mqm.gateway.routes.cfg")), mavenBundle().groupId("net.bryansaunders").artifactId("routeBundle").versionAsInProject() ;
Modifying the ProbeModified Using the @ProbeBuilder AnnotationUses the Following Method Signature
@ProbeBuilderpublic TestProbeBuilder probeConfiguration(TestProbeBuilder probe) // Do Things
Method should return the probe Parameter after ModificationSets Probe Specific Configurations via HeadersDynamically Imports all Packages by Default
Using Provisional PackagesProvisional Packages are by Default NOT ImportedProbe must be Modified to Import ThemAdd the Following Line to your ProbeBuilder Method
probe.setHeader(Constants.DYNAMICIMPORT_PACKAGE, "*;status=provisional");
Getting the Camel ContextThere will potentially be Multiple Camel Contexts running in theContainerNeed to get the Correct Context for Our TestsBest Done in doPreSetup() Method that can be Overridden fromCamelTestSupportCamel Context should be Looked Up by it’s name in the BundleContext
@Overrideprotected void doPreSetup() throws Exception camelContext = PaxExamTestUtil.getOsgiService(CamelContext.class, "(camel.context.name=" + CAMEL_CONTEXT_NAME + ")", 10000, bundleContext); assertNotNull(camelContext);
Sending Messages2 Steps
Create/Start Producer TemplateSend Message using Template
// Set Headers To Be Sentfinal Map<String, Object> headerMap = new HashMap<String, Object>();headerMap.put("WM_MSG_ID", null);headerMap.put("WM_HO_WMQ_QUEUE", null);
// Send the Message BodyProducerTemplate template = camelContext.createProducerTemplate();template.start();
template.send("direct:gateway_in", new Processor() public void process(Exchange exchange) Message in = exchange.getIn(); in.setBody("Hello from Camel"); in.setHeaders(headerMap); );
Using Mock QueuesGet the Endpoint from the Camel Context and Cast to a MockEndpoint
MockEndpoint mockNoHomeOfficeDlq = (MockEndpoint)CamelContext.getEndpoint("mock:gateway_noHomeOfficeDlq");
Set Mock Endpoint’s Expectations
mockNoHomeOfficeDlq.expectedMessageCount(1);mockNoHomeOfficeDlq.expectedBodiesReceived("Hello from Camel");
Send Messages to Mock EndpointAssert Mock Endpoint is Satisfied
mockNoHomeOfficeDlq.assertIsSatisfied(2500);
Pax Exam on Karaf Demo
https://github.com/bsaunder/camel/tree/master/fuse/pax-exam
What About Arquillian?Arquillian has OSGi supportWorks like standard ArquillianSupports Multiple Containers
JBoss (Embedded)Felix (Embedded)Equinox (Embedded)Karak (Embedded/Managed/Remote)
Not as Feature Rich as Pax Exam
Evolving Quickly
Future of Camel
Camel v3 ImprovementsImproved Test Support
Support for testing indiviual components, processors, etc...
Persistent Message StoreJava 8 DSLSplit/Optimize Camel-CXF
Camel on EAP SubsystemFull EAP SubsystemImproved Integration with JEE StandardsUpdated JEE Related Camel Components
camel-cdicamel-cxfcamel-jaxbcamel-jmscamel-jmxcamel-jpa
Full Arquillian SupportAvailable now in Wildfly 8.1Official Support in future Fuse Release
Targeted for Fuse 6.2
Questions?
Presentation is Available Athttps://github.com/bsaunder/camel_from_the_field
All Demo Code is Available Athttps://github.com/bsaunder/camel/