camel_from_the_field

101
Red Hat | Bryan Saunders Camel from the Field Bryan Saunders Feb 16, 2015

Upload: bryan-saunders

Post on 17-Jul-2015

146 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Camel_From_The_Field

Red Hat | Bryan Saunders

Camel from the FieldBryan Saunders Feb 16, 2015

Page 2: Camel_From_The_Field

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

Page 3: Camel_From_The_Field

Introduction to Camel

Page 4: Camel_From_The_Field

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

Page 5: Camel_From_The_Field

Why an Integration FrameworkIntegration is Critical for BusinessFramework does the Heavy LiftingLets you Focus on the ProblemPrevents Re-inventing the Wheel

Page 6: Camel_From_The_Field

History of CamelStarted in March 2007Founded by

James StrachanRob DaviesHiram ChirinoGuillaume Nodet

First Release in June 2007Spawned from Apache ServiceMix and Apache ActiveMQ

Page 7: Camel_From_The_Field

Camel FeaturesVery Leightweight , Consists of only a handful of JARsEasy ConfigurationNo Heavy SpecificationNo Container DependenciesPayload Agnostic

Page 8: Camel_From_The_Field

Simple ProgrammingMinimal ConfigurationDSL Based Programming6 DSL's and Counting

Java DSLSpring XMLBlueprint XMLRest DSLGroovy DSLScala DSLKotlin DSL in the works

Page 9: Camel_From_The_Field

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");

Page 10: Camel_From_The_Field

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>

Page 11: Camel_From_The_Field

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>

Page 12: Camel_From_The_Field

Components191 Components and countingComponent for pretty much anythingMost commonley used components

CXFCXFRSJMSActiveMQAMQPInfinispanCDIDrools

Page 13: Camel_From_The_Field

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

Page 14: Camel_From_The_Field

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

Page 15: Camel_From_The_Field

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

Page 16: Camel_From_The_Field

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

Page 17: Camel_From_The_Field

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

Page 18: Camel_From_The_Field

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));

Page 19: Camel_From_The_Field

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)

Page 20: Camel_From_The_Field

SecurityFour Broad Categories of Security Offered

Route SecurityPayload SecurityEndpoint SecurityConfiguration Security

Page 21: Camel_From_The_Field

Route SecurityPolicy driven security for routes or route segments

Shiro SecuritySpring Security

Page 22: Camel_From_The_Field

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)

Page 23: Camel_From_The_Field

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

Page 24: Camel_From_The_Field

Configuration SecurityExternalize configuration properties

PropertiesJasypt - Encrypted valuesJSSE Utility - Configure SSL/TLS

Page 25: Camel_From_The_Field

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)

Page 26: Camel_From_The_Field

HA & FailoverNot natively supportedProvided by the following components

Camel Fabric Master componentCamel ZooKeeper via a Route policyCamel JGroups

Page 27: Camel_From_The_Field

TestableNative test frameworksSupports unit and integration TestingBuilt in mock & stub supportAdvanced testing with NotifyBuilder and AdviceWithWorks with 3rd party test frameworks

PaxExamArquillianJUnitTestNG

Page 28: Camel_From_The_Field

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

Page 29: Camel_From_The_Field

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"); ;

Page 30: Camel_From_The_Field

ToolingSeveral tools exist for working with and monitoring Camel

Camel Maven PluginJBoss Tools for CamelTalend Open StudioHawtio Camel Plugin

Page 31: Camel_From_The_Field

JBoss Tools for Camel

Page 32: Camel_From_The_Field

JBoss Tools for Camel

Page 33: Camel_From_The_Field

Enterprise Integration PatternsSimilar to Design PatternsFocused specifically on IntegrationWritten by Gregor Hohpe & Bobby Wolf65 Documented PatternsCamel supports 53 of them

Page 34: Camel_From_The_Field

Enterprise Integration Patterns

Page 35: Camel_From_The_Field

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();

Page 36: Camel_From_The_Field

Architecture

Page 37: Camel_From_The_Field

High Level Architecture

Page 38: Camel_From_The_Field

Domain Specific LanguageUsed for defining routesMultiple DSL's exist

Page 39: Camel_From_The_Field

RouteSet of rules that define message flowConsists of:

EndpointsEIP ConstructsProcessors

Page 40: Camel_From_The_Field

EndpointImplementation of the Message Endpoint patternCreated by componentsReferred to by uniue URI's in the DSLConsumers receive messagesProducers send messages

Page 41: Camel_From_The_Field

ComponentEssentially a factory for Endpoint instancesAdds functionality to CamelCustom components extend DefaultComponent

Page 42: Camel_From_The_Field

ProcessorConsumes message exchangesProcessor interface for building custom ProcessorsUsed to encapsulate custom business logicCan be turned into a full Component

Page 43: Camel_From_The_Field

Message ExchangeSupports multiple Exchange Patterns

One Way Event Message EIPRequest Reply Message EIP

Implements Message EIP

Page 44: Camel_From_The_Field

Supported Platforms

Page 45: Camel_From_The_Field

Multiple PlatformsAnywhere that supports Java 1.6

Standard JVMOSGiTomcatApplication ServersSpring

Page 46: Camel_From_The_Field

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

Page 47: Camel_From_The_Field

JBoss Fuse

Page 48: Camel_From_The_Field

JBoss Fuse Service Works

Page 49: Camel_From_The_Field

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

Page 50: Camel_From_The_Field

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

Page 51: Camel_From_The_Field

Hands On Camel

Page 52: Camel_From_The_Field

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

Page 53: Camel_From_The_Field

Starting with SpringRequires SpringBest if already using SpringCamel uses Spring's Bean RegistryStarted using Spring ContextLoaderListenerConfiguration very similar to Fuse with Spring or Blueprint

Page 54: Camel_From_The_Field

Spring ExampleExample web.xml

<web­app ...> <display­name>soap­contract­first</display­name>

<!­­ Config Location ­­> <context­param> <param­name>contextConfigLocation</param­name> <param­value>classpath:META­INF/spring/*.xml</param­value> </context­param>

<!­­ Spring Listener Servlet ­­> <listener> <listener­class>org.springframework.web.context.ContextLoaderListener</listener­class> </listener></web­app>

Page 55: Camel_From_The_Field

Spring ExampleExample camel-route.xml

<beans ...>

<import resource="classpath:META­INF/spring/camel­cxf.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>

Page 56: Camel_From_The_Field

Starting with Spring Demo

https://github.com/bsaunder/camel/tree/master/eap_6/soap-contract-first

Page 57: Camel_From_The_Field

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

Page 58: Camel_From_The_Field

ServletListener ConfigurationExample web.xml

<web­app ...> <display­name>servlet_listener</display­name>

<!­­ Set CamelContext name ­­> <context­param> <param­name>name</param­name> <param­value>myCamelContext</param­value> </context­param> <context­param> <param­name>routeBuilder­JavaRoute</param­name> <param­value>net.bryansaunders.camel.servlet_listener.JavaRoute</param­value> </context­param> <context­param> <param­name>routeBuilder­XmlRoute</param­name> <param­value>classpath:camel­routes.xml</param­value> </context­param> <listener> <listener­class>org.apache.camel.component.servletlistener.SimpleCamelServletContextListener</listener­class> </listener>

</web­app>

Page 59: Camel_From_The_Field

ServletListener Component Demo

https://github.com/bsaunder/camel/tree/master/eap_6/servlet_listener

Page 60: Camel_From_The_Field

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

Page 61: Camel_From_The_Field

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

Page 62: Camel_From_The_Field

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("my­camel­context"); this.camelCtx.start();

@PreDestroy public void stop() throws Exception this.camelCtx.stop();

Page 63: Camel_From_The_Field

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("camel­routes.xml");if (is != null) RoutesDefinition routes = this.camelCtx.loadRoutesDefinition(is); this.camelCtx.addRouteDefinitions(routes.getRoutes());

Page 64: Camel_From_The_Field

CDI Component Demo

https://github.com/bsaunder/camel/tree/master/eap_6/cdi-soap-consume

Page 65: Camel_From_The_Field

Configuration with Camel CDINo Spring Config or ContextWith Camel CDI Components are Configured in JavaConfigured on the Camel ContextAll Components can be Configured

Page 66: Camel_From_The_Field

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()

Page 67: Camel_From_The_Field

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));

Page 68: Camel_From_The_Field

JMS Configuration Demo

https://github.com/bsaunder/camel/tree/master/eap_6/cdi-jms

Page 69: Camel_From_The_Field

Camel & JBoss A-MQCamel has no JBoss A-MQ ComponentSeveral ways to Connect to A-MQ from Camel

JMS ComponentActiveMQ ComponentBean using JMS API

Page 70: Camel_From_The_Field

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

Page 71: Camel_From_The_Field

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

Page 72: Camel_From_The_Field

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

Page 73: Camel_From_The_Field

Claim Check EIPReplaces Message Data with a Unique ID for Future RetrievalData stored into Persistent Data StoreData Retrieved later using Unique ID

Page 74: Camel_From_The_Field

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");

Page 75: Camel_From_The_Field

Web Services with Camel CDIWeb Services are common place in IntegrationCamel has Several Web Service Related Components

CXFCXFRSSpring Web ServicesRestSpark-Rest

Page 76: Camel_From_The_Field

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

Page 77: Camel_From_The_Field

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);

Page 78: Camel_From_The_Field

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

Page 79: Camel_From_The_Field

JAX-WS Demo

https://github.com/bsaunder/camel/tree/master/eap_6/cdi-jaxws-publish

Page 80: Camel_From_The_Field

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)

Page 81: Camel_From_The_Field

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");

Page 82: Camel_From_The_Field

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

Page 83: Camel_From_The_Field

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

Page 84: Camel_From_The_Field

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

Page 85: Camel_From_The_Field

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[]

Page 86: Camel_From_The_Field

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

Page 87: Camel_From_The_Field

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...

Page 88: Camel_From_The_Field

Generating Dependency FileGenerate using the Maven Plugin

<plugin> <groupId>org.apache.servicemix.tooling</groupId> <artifactId>depends­maven­plugin</artifactId> <version>1.2</version> <executions> <execution> <id>generate­depends­file</id> <goals> <goal>generate­depends­file</goal> </goals> </execution> </executions></plugin>

Should use the versionAsInProject() method in Container Configuration

Page 89: Camel_From_The_Field

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…

Page 90: Camel_From_The_Field

Example Configuration

@Configurationpublic static Option[] configure() throws Exception return new Option[] karafDistributionConfiguration() .frameworkUrl( maven().groupId("org.apache.karaf").artifactId("apache­karaf").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("apache­camel").type("xml") .classifier("features").versionAsInProject(), "camel­blueprint", "camel­jms", "camel­jpa", "camel­mvel", "camel­jdbc", "camel­cxf", "camel­test"), 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() ;

Page 91: Camel_From_The_Field

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

Page 92: Camel_From_The_Field

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");

Page 93: Camel_From_The_Field

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);

Page 94: Camel_From_The_Field

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); );

Page 95: Camel_From_The_Field

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);

Page 96: Camel_From_The_Field

Pax Exam on Karaf Demo

https://github.com/bsaunder/camel/tree/master/fuse/pax-exam

Page 97: Camel_From_The_Field

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

Page 98: Camel_From_The_Field

Future of Camel

Page 99: Camel_From_The_Field

Camel v3 ImprovementsImproved Test Support

Support for testing indiviual components, processors, etc...

Persistent Message StoreJava 8 DSLSplit/Optimize Camel-CXF

Page 100: Camel_From_The_Field

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

Page 101: Camel_From_The_Field

Questions?

Presentation is Available Athttps://github.com/bsaunder/camel_from_the_field

All Demo Code is Available Athttps://github.com/bsaunder/camel/