Red Hat build of Apache Camel for Spring Boot Reference
Red Hat build of Apache Camel for Spring Boot Reference Red Hat build of Apache Camel 4.8 Red Hat build of Apache Camel for Spring Boot Reference Red Hat build of Apache Camel Documentation Team fuse-docs-support@redhat.com Red Hat build of Apache Camel Support Team http://access.redhat.com/support
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-amqp-starter</artifactId> </dependency> amqp:[queue:|topic:]destinationName[?options] amqp:destinationType:destinationName // Consuming from AMQP queue from("amqp:queue:incoming"). to(...); // Sending message to the AMQP topic from(...). to("amqp:topic:notify"); AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672"); AMQPComponent authorizedAmqp = AMQPComponent.amqpComponent("amqp://localhost:5672", "user", "password"); @Bean AMQPConnectionDetails amqpConnection() { return new AMQPConnectionDetails("amqp://localhost:5672"); } @Bean AMQPConnectionDetails securedAmqpConnection() { return new AMQPConnectionDetails("amqp://localhost:5672", "username", "password"); } @Produces AMQPConnectionDetails amqpConnection() { return new AMQPConnectionDetails("amqp://localhost:5672"); } export AMQP_SERVICE_HOST = "mybroker.com" export AMQP_SERVICE_PORT = "6666" export AMQP_SERVICE_USERNAME = "username" export AMQP_SERVICE_PASSWORD = "password" @Bean AMQPConnectionDetails amqpConnection() { return AMQPConnectionDetails.discoverAMQP(); } AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672?amqp.traceFrames=true"); <bean id="amqp" class="org.apache.camel.component.amqp.AmqpComponent"> <property name="connectionFactory"> <bean class="org.apache.qpid.jms.JmsConnectionFactory" factory-method="createFromURL"> <property name="remoteURI" value="amqp://localhost:5672" /> <property name="topicPrefix" value="topic://" /> <!-- only necessary when connecting to ActiveMQ over AMQP 1.0 --> </bean> </property> </bean> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-avro-starter</artifactId> </dependency> AvroDataFormat format = new AvroDataFormat(Value.SCHEMAUSD); from("direct:in").marshal(format).to("direct:marshal"); from("direct:back").unmarshal(format).to("direct:unmarshal"); <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:in"/> <marshal> <avro instanceClass="org.apache.camel.dataformat.avro.Message"/> </marshal> <to uri="log:out"/> </route> </camelContext> <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"> <dataFormats> <avro id="avro" instanceClass="org.apache.camel.dataformat.avro.Message"/> </dataFormats> <route> <from uri="direct:in"/> <marshal><custom ref="avro"/></marshal> <to uri="log:out"/> </route> </camelContext> from("kafka:topic"). unmarshal().avro(AvroLibrary.Jackson, JsonNode.class). to("log:info"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jackson-avro-starter</artifactId> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-cw-starter</artifactId> </dependency> aws2-cw://namespace[?options] aws2-cw:namespace from("direct:start") .to("aws2-cw://namespace?amazonCwClient=#client"); from("direct:start") .to("aws2-cw://http://camel.apache.org/aws-cw"); exchange.getIn().setHeader(Cw2Constants.METRIC_NAME, "ExchangesCompleted"); exchange.getIn().setHeader(Cw2Constants.METRIC_VALUE, "2.0"); exchange.getIn().setHeader(Cw2Constants.METRIC_UNIT, "Count"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-ddb-starter</artifactId> </dependency> aws2-ddb://domainName[?options] aws2-ddb:tableName from("direct:start") .to("aws2-ddb://domainName?amazonDDBClient=#client"); from("direct:start") .setHeader(Ddb2Constants.OPERATION, Ddb2Operations.PutItem) .setHeader(Ddb2Constants.CONSISTENT_READ, "true") .setHeader(Ddb2Constants.RETURN_VALUES, "ALL_OLD") .setHeader(Ddb2Constants.ITEM, attributeMap) .setHeader(Ddb2Constants.ATTRIBUTE_NAMES, attributeMap.keySet()); .to("aws2-ddb://" + tableName + "?keyAttributeName=" + attributeName + "&keyAttributeType=" + KeyType.HASH + "&keyScalarType=" + ScalarAttributeType.S + "&readCapacity=1&writeCapacity=1"); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-aws2-ddb</artifactId> <version>USD{camel-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-kinesis-starter</artifactId> </dependency> aws2-kinesis://stream-name[?options] aws2-kinesis:streamName from("aws2-kinesis://mykinesisstream?amazonKinesisClient=#kinesisClient") .to("log:out?showAll=true"); from("aws2-kinesis://mykinesisstream?asyncClient=true&useDefaultCredentialsProvider=true&useKclConsumers=true") .to("log:out?showAll=true"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-lambda-starter</artifactId> </dependency> aws2-lambda://functionName[?options] aws2-lambda:function from("direct:createFunction").to("aws2-lambda://GetHelloWithName?operation=createFunction").to("mock:result"); template.send("direct:createFunction", ExchangePattern.InOut, new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(Lambda2Constants.RUNTIME, "nodejs6.10"); exchange.getIn().setHeader(Lambda2Constants.HANDLER, "GetHelloWithName.handler"); exchange.getIn().setHeader(Lambda2Constants.DESCRIPTION, "Hello with node.js on Lambda"); exchange.getIn().setHeader(Lambda2Constants.ROLE, "arn:aws:iam::643534317684:role/lambda-execution-role"); ClassLoader classLoader = getClass().getClassLoader(); File file = new File( classLoader .getResource("org/apache/camel/component/aws2/lambda/function/node/GetHelloWithName.zip") .getFile()); FileInputStream inputStream = new FileInputStream(file); exchange.getIn().setBody(inputStream); } }); from("direct:getFunction") .setBody(GetFunctionRequest.builder().functionName("test").build()) .to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=getFunction&pojoRequest=true") <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-aws2-lambda</artifactId> <version>USD{camel-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-s3-starter</artifactId> </dependency> aws2-s3://bucketNameOrArn[?options] aws2-s3://bucketNameOrArn from("aws2-s3://helloBucket?accessKey=yourAccessKey&secretKey=yourSecretKey&prefix=hello.txt") .to("file:/var/downloaded"); from("aws2-s3://MyBucket?amazonS3Client=#client&delay=5000&maxMessagesPerPoll=5") .to("mock:result"); from("file:tmp/test?fileName=test.txt") .setHeader(S3Constants.KEY, constant("testFile")) .to("aws2-s3://mybucket?amazonS3Client=#client&useAwsKMS=true&awsKMSKeyId=3f0637ad-296a-3dfe-a796-e60654fb128c"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(S3Constants.KEY, "camel.txt"); exchange.getIn().setBody("Camel rocks!"); } }) .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(AWS2S3Constants.KEY, "empty.txt"); exchange.getIn().setBody(new File("src/empty.txt")); } }) .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&multiPartUpload=true&autoCreateBucket=true&partSize=1048576") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(S3Constants.BUCKET_DESTINATION_NAME, "camelDestinationBucket"); exchange.getIn().setHeader(S3Constants.KEY, "camelKey"); exchange.getIn().setHeader(S3Constants.DESTINATION_KEY, "camelDestinationKey"); } }) .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=copyObject") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(S3Constants.KEY, "camelKey"); } }) .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=deleteObject") .to("mock:result"); from("direct:start") .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=listBuckets") .to("mock:result"); from("direct:start") .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=deleteBucket") .to("mock:result"); from("direct:start") .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=listObjects") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(S3Constants.KEY, "camelKey"); } }) .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=getObject") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(S3Constants.KEY, "camelKey"); exchange.getIn().setHeader(S3Constants.RANGE_START, "0"); exchange.getIn().setHeader(S3Constants.RANGE_END, "9"); } }) .to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=getObjectRange") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(S3Constants.KEY, "camelKey"); } }) .to("aws2-s3://mycamelbucket?accessKey=xxx&secretKey=yyy&region=region&operation=createDownloadLink") .to("mock:result"); from(kafka("topic1").brokers("localhost:9092")) .log("Kafka Message is: USD{body}") .to(aws2S3("camel-bucket").streamingUploadMode(true).batchMessageNumber(25).namingStrategy(AWS2S3EndpointBuilderFactory.AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic1}}/{{kafkaTopic1}}.txt")); from(kafka("topic2").brokers("localhost:9092")) .log("Kafka Message is: USD{body}") .to(aws2S3("camel-bucket").streamingUploadMode(true).batchMessageNumber(25).namingStrategy(AWS2S3EndpointBuilderFactory.AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic2}}/{{kafkaTopic2}}.txt")); from(kafka("topic1").brokers("localhost:9092")) .log("Kafka Message is: USD{body}") .to(aws2S3("camel-bucket").streamingUploadMode(true).batchMessageNumber(25).streamingUploadTimeout(10000).namingStrategy(AWS2S3EndpointBuilderFactory.AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic1}}/{{kafkaTopic1}}.txt")); from("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&moveAfterRead=true&destinationBucket=myothercamelbucket") .to("mock:result"); from("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&moveAfterRead=true&destinationBucket=myothercamelbucket&destinationBucketPrefix=RAW(pre-)&destinationBucketSuffix=RAW(-suff)") .to("mock:result"); String key = UUID.randomUUID().toString(); byte[] secretKey = generateSecretKey(); String b64Key = Base64.getEncoder().encodeToString(secretKey); String b64KeyMd5 = Md5Utils.md5AsBase64(secretKey); String awsEndpoint = "aws2-s3://mycamel?autoCreateBucket=false&useCustomerKey=true&customerKeyId=RAW(" + b64Key + ")&customerKeyMD5=RAW(" + b64KeyMd5 + ")&customerAlgorithm=" + AES256.name(); from("direct:putObject") .setHeader(AWS2S3Constants.KEY, constant("test.txt")) .setBody(constant("Test")) .to(awsEndpoint); from("direct:aws2-s3") .setBody(ListObjectsRequest.builder().bucket(bucketName).build()) .to("aws2-s3://test?amazonS3Client=#amazonS3Client&operation=listObjects&pojoRequest=true") String awsBucketAccessKey = "your_access_key"; String awsBucketSecretKey = "your_secret_key"; S3Client s3Client = S3Client.builder().credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(awsBucketAccessKey, awsBucketSecretKey))) .region(Region.US_EAST_1).build(); AWS2S3Configuration configuration = new AWS2S3Configuration(); configuration.setAmazonS3Client(s3Client); configuration.setAutoDiscoverClient(true); configuration.setBucketName("s3bucket2020"); configuration.setRegion("us-east-1"); AWS2S3Component s3Component = new AWS2S3Component(getContext()); s3Component.setConfiguration(configuration); s3Component.setLazyStartProducer(true); camelContext.addComponent("aws2-s3", s3Component); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-aws2-s3</artifactId> <version>USD{camel-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-sns-starter</artifactId> </dependency> aws2-sns://topicNameOrArn[?options] ?options=value&option2=value&... aws2-sns:topicNameOrArn from("direct:start") .to("aws2-sns://MyTopic?amazonSNSClient=#client"); from("direct:start") .to("aws2-sns://test-camel-sns1?amazonSNSClient=#amazonSNSClient&subscribeSNStoSQS=true&queueUrl=https://sqs.eu-central-1.amazonaws.com/780410022472/test-camel"); from("aws2-sqs://test-camel?amazonSQSClient=#amazonSQSClient&delay=50&maxMessagesPerPoll=5") .to(...); { "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__owner_statement", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::780560123482:root" }, "Action": "SQS:*", "Resource": "arn:aws:sqs:eu-west-1:780560123482:QueueSub.fifo" }, { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "SQS:SendMessage", "Resource": "arn:aws:sqs:eu-west-1:780560123482:QueueSub.fifo", "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:sns:eu-west-1:780410022472:Order.fifo" } } } ] } from("direct:start") .to("aws2-sns://camel-topic?subject=The+subject+message&autoCreateTopic=true"); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-aws2-sns</artifactId> <version>USD{camel-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-sqs-starter</artifactId> </dependency> aws2-sqs://queueNameOrArn[?options] aws2-sqs:queueNameOrArn from("aws2-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5") .to("mock:result"); from("aws2-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5") .to("mock:result"); from("aws2-sqs://MyQueue?amazonSQSClient=#client&defaultVisibilityTimeout=5000&deleteIfFiltered=false&deleteAfterRead=false") .filter("USD{header.login} == true") .setProperty(Sqs2Constants.SQS_DELETE_FILTERED, constant(true)) .to("mock:filter"); from("direct:start") .setBody(constant("Camel rocks!")) .to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)&region=eu-west-1"); from("direct:start") .setHeader(SqsConstants.SQS_OPERATION, constant("sendBatchMessage")) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Collection c = new ArrayList(); c.add("team1"); c.add("team2"); c.add("team3"); c.add("team4"); exchange.getIn().setBody(c); } }) .to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)&region=eu-west-1"); from("direct:start") .setHeader(SqsConstants.SQS_OPERATION, constant("deleteMessage")) .setHeader(SqsConstants.RECEIPT_HANDLE, constant("123456")) .to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)&region=eu-west-1"); from("direct:start") .setHeader(SqsConstants.SQS_OPERATION, constant("listQueues")) .to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)&region=eu-west-1"); from("direct:start") .setHeader(SqsConstants.SQS_OPERATION, constant("purgeQueue")) .to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)&region=eu-west-1"); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-aws2-sqs</artifactId> <version>USD{camel-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws-secrets-manager-starter</artifactId> </dependency> aws-secrets-manager://label[?options] `?options=value&option2=value&... ` aws-secrets-manager:label export CAMEL_VAULT_AWS_ACCESS_KEY=accessKey export CAMEL_VAULT_AWS_SECRET_KEY=secretKey export CAMEL_VAULT_AWS_REGION=region camel.vault.aws.accessKey = accessKey camel.vault.aws.secretKey = secretKey camel.vault.aws.region = region export CAMEL_VAULT_AWS_USE_DEFAULT_CREDENTIALS_PROVIDER=true export CAMEL_VAULT_AWS_REGION=region camel.vault.aws.defaultCredentialsProvider = true camel.vault.aws.region = region export CAMEL_VAULT_AWS_USE_PROFILE_CREDENTIALS_PROVIDER=true export CAMEL_VAULT_AWS_PROFILE_NAME=test-account export CAMEL_VAULT_AWS_REGION=region camel.vault.aws.profileCredentialsProvider = true camel.vault.aws.profileName = test-account camel.vault.aws.region = region <camelContext> <route> <from uri="direct:start"/> <to uri="{{aws:route}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{aws:route:default}}"/> </route> </camelContext> { "username": "admin", "password": "password123", "engine": "postgres", "host": "127.0.0.1", "port": "3128", "dbname": "db" } <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{aws:database/username}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{aws:database/username:admin}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{aws:route@bf9b4f4b-8e63-43fd-a73c-3e2d3748b451}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{aws:route:default@bf9b4f4b-8e63-43fd-a73c-3e2d3748b451}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{aws:database/username:admin@bf9b4f4b-8e63-43fd-a73c-3e2d3748b451}}"/> </route> </camelContext> export CAMEL_VAULT_AWS_USE_DEFAULT_CREDENTIALS_PROVIDER=accessKey export CAMEL_VAULT_AWS_REGION=region camel.vault.aws.useDefaultCredentialProvider = true camel.vault.aws.region = region camel.vault.aws.refreshEnabled=true camel.vault.aws.refreshPeriod=60000 camel.vault.aws.secrets=Secret camel.main.context-reload-enabled = true { "source": ["aws.secretsmanager"], "detail-type": ["AWS API Call via CloudTrail"], "detail": { "eventSource": ["secretsmanager.amazonaws.com"] } } { "Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"<queue_arn>/SQSDefaultPolicy\",\"Statement\":[{\"Sid\": \"EventsToMyQueue\", \"Effect\": \"Allow\", \"Principal\": {\"Service\": \"events.amazonaws.com\"}, \"Action\": \"sqs:SendMessage\", \"Resource\": \"<queue_arn>\", \"Condition\": {\"ArnEquals\": {\"aws:SourceArn\": \"<eventbridge_rule_arn>\"}}}]}" } aws sqs set-queue-attributes --queue-url <queue_url> --attributes file://policy.json camel.vault.aws.refreshEnabled=true camel.vault.aws.refreshPeriod=60000 camel.vault.aws.secrets=Secret camel.main.context-reload-enabled = true camel.vault.aws.useSqsNotification=true camel.vault.aws.sqsQueueUrl=<queue_url> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-key-vault-starter</artifactId> </dependency> azure-key-vault://vaultName[?options] azure-key-vault:vaultName export USDCAMEL_VAULT_AZURE_TENANT_ID=tenantId export USDCAMEL_VAULT_AZURE_CLIENT_ID=clientId export USDCAMEL_VAULT_AZURE_CLIENT_SECRET=clientSecret export USDCAMEL_VAULT_AZURE_VAULT_NAME=vaultName camel.vault.azure.tenantId = accessKey camel.vault.azure.clientId = clientId camel.vault.azure.clientSecret = clientSecret camel.vault.azure.vaultName = vaultName export USDCAMEL_VAULT_AZURE_IDENTITY_ENABLED=true export USDCAMEL_VAULT_AZURE_VAULT_NAME=vaultName camel.vault.azure.azureIdentityEnabled = true camel.vault.azure.vaultName = vaultName <camelContext> <route> <from uri="direct:start"/> <to uri="{{azure:route}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{azure:route:default}}"/> </route> </camelContext> { "username": "admin", "password": "password123", "engine": "postgres", "host": "127.0.0.1", "port": "3128", "dbname": "db" } <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{azure:database/username}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{azure:database/username:admin}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{azure:route@bf9b4f4b-8e63-43fd-a73c-3e2d3748b451}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{azure:route:default@bf9b4f4b-8e63-43fd-a73c-3e2d3748b451}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{azure:database/username:admin@bf9b4f4b-8e63-43fd-a73c-3e2d3748b451}}"/> </route> </camelContext> export USDCAMEL_VAULT_AZURE_TENANT_ID=tenantId export USDCAMEL_VAULT_AZURE_CLIENT_ID=clientId export USDCAMEL_VAULT_AZURE_CLIENT_SECRET=clientSecret export USDCAMEL_VAULT_AZURE_VAULT_NAME=vaultName camel.vault.azure.tenantId = accessKey camel.vault.azure.clientId = clientId camel.vault.azure.clientSecret = clientSecret camel.vault.azure.vaultName = vaultName export USDCAMEL_VAULT_AZURE_IDENTITY_ENABLED=true export USDCAMEL_VAULT_AZURE_VAULT_NAME=vaultName camel.vault.azure.azureIdentityEnabled = true camel.vault.azure.vaultName = vaultName camel.vault.azure.refreshEnabled=true camel.vault.azure.refreshPeriod=60000 camel.vault.azure.secrets=Secret camel.vault.azure.eventhubConnectionString=eventhub_conn_string camel.vault.azure.blobAccountName=blob_account_name camel.vault.azure.blobContainerName=blob_container_name camel.vault.azure.blobAccessKey=blob_access_key camel.main.context-reload-enabled = true az ad app create --display-name test-app-key-vault az ad app credential reset --id <appId> --append --display-name 'Description: Key Vault app client' --end-date '2024-12-31' { "appId": "appId", "password": "pwd", "tenant": "tenantId" } az keyvault create --name <vaultName> --resource-group <resourceGroup> az ad sp create --id <appId> az role assignment create --assignee <appId> --role "Key Vault Administrator" --scope /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.KeyVault/vaults/<vaultName> az keyvault set-policy --name <vaultName> --spn <appId> --secret-permissions get az keyvault secret set --name <secret_name> --vault-name <vaultName> -f <json-secret> az storage account create --name <blobAccountName> --resource-group <resourceGroup> az storage container create --account-name <blobAccountName> --name <blobContainerName> az storage account keys list -g <resourceGroup> -n <blobAccountName> az eventhubs namespace create --resource-group <resourceGroup> --name <eventhub-namespace> --location westus --sku Standard --enable-auto-inflate --maximum-throughput-units 20 az eventhubs eventhub create --resource-group <resourceGroup> --namespace-name <eventhub-namespace> --name <eventhub-name> --cleanup-policy Delete --partition-count 15 from("direct:createSecret") .setHeader(KeyVaultConstants.SECRET_NAME, "Test") .setBody(constant("Test")) .to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})") from("direct:getSecret") .setHeader(KeyVaultConstants.SECRET_NAME, "Test") .to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=getSecret") from("direct:deleteSecret") .setHeader(KeyVaultConstants.SECRET_NAME, "Test") .to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=deleteSecret") from("direct:purgeDeletedSecret") .setHeader(KeyVaultConstants.SECRET_NAME, "Test") .to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=purgeDeletedSecret") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-servicebus-starter</artifactId> </dependency> azure-servicebus:topicOrQueueName from("direct:start") .process(exchange -> { final List<Object> inputBatch = new LinkedList<>(); inputBatch.add("test batch 1"); inputBatch.add("test batch 2"); inputBatch.add("test batch 3"); inputBatch.add(123456); exchange.getIn().setBody(inputBatch); }) .to("azure-servicebus:test//?connectionString=test") .to("mock:result"); from("direct:start") .process(exchange -> { final List<Object> inputBatch = new LinkedList<>(); inputBatch.add("test batch 1"); inputBatch.add("test batch 2"); inputBatch.add("test batch 3"); inputBatch.add(123456); exchange.getIn().setHeader(ServiceBusConstants.SCHEDULED_ENQUEUE_TIME, OffsetDateTime.now()); exchange.getIn().setBody(inputBatch); }) .to("azure-servicebus:test//?connectionString=test&producerOperation=scheduleMessages") .to("mock:result"); from("azure-servicebus:test//?connectionString=test") .log("USD{body}") .to("mock:result"); from("azure-servicebus:test//?connectionString=test&consumerOperation=peekMessages&peekNumMaxMessages=3") .log("USD{body}") .to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-storage-blob-starter</artifactId> </dependency> azure-storage-blob://accountName[/containerName][?options] azure-storage-blob:accountName/containerName from("azure-storage-blob://camelazure/container1?blobName=hello.txt&credentialType=SHARED_ACCOUNT_KEY&accessKey=RAW(yourAccessKey)").to("file://blobdirectory"); StorageSharedKeyCredential credential = new StorageSharedKeyCredential("yourAccountName", "yourAccessKey"); String uri = String.format("https://%s.blob.core.windows.net", "yourAccountName"); BlobServiceClient client = new BlobServiceClientBuilder() .endpoint(uri) .credential(credential) .buildClient(); // This is camel context context.getRegistry().bind("client", client); from("azure-storage-blob://cameldev/container1?blobName=myblob&serviceClient=#client") .to("mock:result"); from("azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey"). to("file://blobdirectory"); from("azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir"). to("mock:results"); from("azure-storage-blob://camelazure/container1?accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir"). to("mock:results"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.LIST_BLOB_CONTAINERS_OPTIONS, new ListBlobContainersOptions().setMaxResultsPerPage(10)); }) .to("azure-storage-blob://camelazure?operation=listBlobContainers&client&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, "newContainerName"); }) .to("azure-storage-blob://camelazure/container1?operation=createBlobContainer&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, "overridenName"); }) .to("azure-storage-blob://camelazure/container1?operation=deleteBlobContainer&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, "overridenName"); }) .to("azure-storage-blob://camelazure/container1?operation=listBlobs&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, "overridenName"); // set our body exchange.getIn().setBody(outputStream); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlob&serviceClient=#client") .process(exchange -> { InputStream inputStream = exchange.getMessage().getBody(InputStream.class); // We use Apache common IO for simplicity, but you are free to do whatever dealing // with inputStream System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8.name())); }) .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_NAME, "overridenName"); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=deleteBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_NAME, "overridenName"); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=downloadBlobToFile&fileDir=/var/mydir&serviceClient=#client") .to("mock:result"); from("direct:start") .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=downloadLink&serviceClient=#client") .process(exchange -> { String link = exchange.getMessage().getHeader(BlobConstants.DOWNLOAD_LINK, String.class); System.out.println("My link " + link); }) .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_NAME, "overridenName"); exchange.getIn().setBody("Block Blob"); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=uploadBlockBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { final List<BlobBlock> blocks = new LinkedList<>(); blocks.add(BlobBlock.createBlobBlock(new ByteArrayInputStream("Hello".getBytes()))); blocks.add(BlobBlock.createBlobBlock(new ByteArrayInputStream("From".getBytes()))); blocks.add(BlobBlock.createBlobBlock(new ByteArrayInputStream("Camel".getBytes()))); exchange.getIn().setBody(blocks); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=stageBlockBlobList&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { // We assume here you have the knowledge of these blocks you want to commit final List<Block> blocksIds = new LinkedList<>(); blocksIds.add(new Block().setName("id-1")); blocksIds.add(new Block().setName("id-2")); blocksIds.add(new Block().setName("id-3")); exchange.getIn().setBody(blocksIds); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=commitBlockBlobList&serviceClient=#client") .to("mock:result"); from("direct:start") .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlobBlockList&serviceClient=#client") .log("USD{body}") .to("mock:result"); from("direct:start") .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=createAppendBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { final String data = "Hello world from my awesome tests!"; final InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); exchange.getIn().setBody(dataStream); // of course you can set whatever headers you like, refer to the headers section to learn more }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=commitAppendBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=createPageBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { byte[] dataBytes = new byte[512]; // we set range for the page from 0-511 new Random().nextBytes(dataBytes); final InputStream dataStream = new ByteArrayInputStream(dataBytes); final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); exchange.getIn().setBody(dataStream); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=uploadPageBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=resizePageBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=clearPageBlob&serviceClient=#client") .to("mock:result"); from("direct:start") .process(exchange -> { final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); }) .to("azure-storage-blob://camelazure/container1?blobName=blob&operation=getPageBlobRanges&serviceClient=#client") .log("USD{body}") .to("mock:result"); from("direct:copyBlob") .process(exchange -> { exchange.getIn().setHeader(BlobConstants.BLOB_NAME, "file.txt"); exchange.getMessage().setHeader(BlobConstants.SOURCE_BLOB_CONTAINER_NAME, "containerblob1"); exchange.getMessage().setHeader(BlobConstants.SOURCE_BLOB_ACCOUNT_NAME, "account"); }) .to("azure-storage-blob://account/containerblob2?operation=copyBlob&sourceBlobAccessKey=RAW(accessKey)") .to("mock:result"); BlobContainerClient blobClient = new BlobContainerClientBuilder() .endpoint(String.format("https://%s.blob.core.windows.net/%s", accountName, accessKey)) .containerName(containerName) .credential(new StorageSharedKeyCredential(accountName, accessKey)) .buildClient(); // Create a SAS token that's valid for 1 day, as an example OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); // Assign permissions to the SAS token BlobContainerSasPermission blobContainerSasPermission = new BlobContainerSasPermission() .setWritePermission(true) .setListPermission(true) .setCreatePermission(true) .setDeletePermission(true) .setAddPermission(true) .setReadPermission(true); BlobServiceSasSignatureValues sasSignatureValues = new BlobServiceSasSignatureValues(expiryTime, blobContainerSasPermission); return blobClient.generateSas(sasSignatureValues); camel.component.azure-storage-blob.sas-token=MY_TOKEN_HERE from("direct:copyBlob") .to("azure-storage-blob://account/containerblob2?operation=uploadBlockBlob&credentialType=AZURE_SAS") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-storage-queue-starter</artifactId> </dependency> azure-storage-queue://accountName[/queueName][?options] azure-storage-queue:accountName/queueName from("azure-storage-queue://storageAccount/messageQueue?accessKey=yourAccessKey"). to("file://queuedirectory"); StorageSharedKeyCredential credential = new StorageSharedKeyCredential("yourAccountName", "yourAccessKey"); String uri = String.format("https://%s.queue.core.windows.net", "yourAccountName"); QueueServiceClient client = new QueueServiceClientBuilder() .endpoint(uri) .credential(credential) .buildClient(); // This is camel context context.getRegistry().bind("client", client); from("azure-storage-queue://cameldev/queue1?serviceClient=#client") .to("file://outputFolder?fileName=output.txt&fileExist=Append"); from("azure-storage-queue://cameldev/queue1?serviceClient=#client&maxMessages=5") .to("file://outputFolder?fileName=output.txt&fileExist=Append"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g, to only returns list of queues with 'awesome' prefix: exchange.getIn().setHeader(QueueConstants.QUEUES_SEGMENT_OPTIONS, new QueuesSegmentOptions().setPrefix("awesome")); }) .to("azure-storage-queue://cameldev?serviceClient=#client&operation=listQueues") .log("USD{body}") .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(QueueConstants.QUEUE_NAME, "overrideName"); }) .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=createQueue"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(QueueConstants.QUEUE_NAME, "overrideName"); }) .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=deleteQueue"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(QueueConstants.QUEUE_NAME, "overrideName"); }) .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=clearQueue"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setBody("message to send"); // we set a visibility of 1min exchange.getIn().setHeader(QueueConstants.VISIBILITY_TIMEOUT, Duration.ofMinutes(1)); }) .to("azure-storage-queue://cameldev/test?serviceClient=#client"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: // Mandatory header: exchange.getIn().setHeader(QueueConstants.MESSAGE_ID, "1"); // Mandatory header: exchange.getIn().setHeader(QueueConstants.POP_RECEIPT, "PAAAAHEEERXXX-1"); }) .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=deleteMessage"); from("direct:start") .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=receiveMessages") .process(exchange -> { final List<QueueMessageItem> messageItems = exchange.getMessage().getBody(List.class); messageItems.forEach(messageItem -> System.out.println(messageItem.getMessageText())); }) .to("mock:result"); from("direct:start") .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=peekMessages") .process(exchange -> { final List<PeekedMessageItem> messageItems = exchange.getMessage().getBody(List.class); messageItems.forEach(messageItem -> System.out.println(messageItem.getMessageText())); }) .to("mock:result"); from("direct:start") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setBody("new message text"); // Mandatory header: exchange.getIn().setHeader(QueueConstants.MESSAGE_ID, "1"); // Mandatory header: exchange.getIn().setHeader(QueueConstants.POP_RECEIPT, "PAAAAHEEERXXX-1"); // Mandatory header: exchange.getIn().setHeader(QueueConstants.VISIBILITY_TIMEOUT, Duration.ofMinutes(1)); }) .to("azure-storage-queue://cameldev/test?serviceClient=#client&operation=updateMessage"); mvn verify -PfullTests -DaccountName=myacc -DaccessKey=mykey <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-bean-starter</artifactId> </dependency> bean:beanName[?options] bean:beanName <route> <from uri="direct:hello"/> <to uri="bean:bye"/> </route> // Send message to the bean endpoint // and invoke method resolved using Bean Binding. from("direct:start").bean("beanName"); // Send message to the bean endpoint // and invoke given method. from("direct:start").bean("beanName", "methodName"); // Send message to the given bean instance. from("direct:start").bean(new ExampleBean()); // Explicit selection of bean method to be invoked. from("direct:start").bean(new ExampleBean(), "methodName"); // Camel will create the instance of bean and cache it for you. from("direct:start").bean(ExampleBean.class); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-beanio-starter</artifactId> </dependency> DataFormat format = new BeanIODataFormat( "org/apache/camel/dataformat/beanio/mappings.xml", "employeeFile"); // a route which uses the bean io data format to format the CSV data // to java objects from("direct:unmarshal") .unmarshal(format) // and then split the message body, so we get a message for each row .split(body()) .to("mock:beanio-unmarshal"); // convert a list of java objects back to flat format from("direct:marshal") .marshal(format) .to("mock:beanio-marshal"); <route> <from uri="direct:unmarshal"/> <unmarshal> <beanio mapping="org/apache/camel/dataformat/beanio/mappings.xml" streamName="employeeFile"/> </unmarshal> <split> <simple>USD{body}</simple> <to uri="mock:beanio-unmarshal"/> </split> </route> <route> <from uri="direct:marshal"/> <marshal> <beanio mapping="org/apache/camel/dataformat/beanio/mappings.xml" streamName="employeeFile"/> </marshal> <to uri="mock:beanio-marshal"/> </route> Joe,Smith,Developer,75000,10012009 Jane,Doe,Architect,80000,01152008 Jon,Anderson,Manager,85000,03182007 <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-bean-validator-starter</artifactId> </dependency> bean-validator:label[?options] bean-validator:label public class Car { @NotNull private String manufacturer; @NotNull @Size(min = 5, max = 14, groups = OptionalChecks.class) private String licensePlate; // getter and setter } public interface OptionalChecks { } from("direct:start") .to("bean-validator://x") .to("mock:end") from("direct:start") .to("bean-validator://x?group=OptionalChecks") .to("mock:end") @GroupSequence({Default.class, OptionalChecks.class}) public interface AllChecks { } from("direct:start") .to("bean-validator://x?group=AllChecks") .to("mock:end") <bean id="myMessageInterpolator" class="my.ConstraintValidatorFactory" /> <bean id="myTraversableResolver" class="my.TraversableResolver" /> <bean id="myConstraintValidatorFactory" class="my.ConstraintValidatorFactory" /> from("direct:start") .to("bean-validator://x?group=AllChecks&messageInterpolator=#myMessageInterpolator &traversableResolver=#myTraversableResolver&constraintValidatorFactory=#myConstraintValidatorFactory") .to("mock:end") <validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration"> <default-provider>org.hibernate.validator.HibernateValidator</default-provider> <message-interpolator>org.hibernate.validator.engine.ResourceBundleMessageInterpolator</message-interpolator> <traversable-resolver>org.hibernate.validator.engine.resolver.DefaultTraversableResolver</traversable-resolver> <constraint-validator-factory>org.hibernate.validator.engine.ConstraintValidatorFactoryImpl</constraint-validator-factory> <constraint-mapping>/constraints-car.xml</constraint-mapping> </validation-config> <constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd" xmlns="http://jboss.org/xml/ns/javax/validation/mapping"> <default-package>org.apache.camel.component.bean.validator</default-package> <bean class="CarWithoutAnnotations" ignore-annotations="true"> <field name="manufacturer"> <constraint annotation="javax.validation.constraints.NotNull" /> </field> <field name="licensePlate"> <constraint annotation="javax.validation.constraints.NotNull" /> <constraint annotation="javax.validation.constraints.Size"> <groups> <value>org.apache.camel.component.bean.validator.OptionalChecks</value> </groups> <element name="min">5</element> <element name="max">14</element> </constraint> </field> </bean> </constraint-mappings> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start"/> <to uri="bean-validator://x?group=org.apache.camel.component.bean.validator.OrderedChecks"/> </route> </camelContext> </beans> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-bindy-starter</artifactId> </dependency> 10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD, 08-01-2009 @CsvRecord( separator = "," ) public Class Order { } 10; J; Pauline; M; XD12345678; Fortis Dynamic 15/15; 2500; USD; 08-01-2009 @CsvRecord( separator = ";" ) public Class Order { } 10| J| Pauline| M| XD12345678| Fortis Dynamic 15/15| 2500| USD| 08-01-2009 @CsvRecord( separator = "\\|" ) public Class Order { } "10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15","2500","USD","08-01-2009" @CsvRecord( separator = "\",\"" ) public Class Order { } "10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15","2500","USD","08-01-2009" @CsvRecord( separator = "," ) public Class Order { } @CsvRecord( separator = ",", quote = "\"" ) public Class Order { } order id, client id, first name, last name, isin code, instrument name, quantity, currency, date @CsvRecord(separator = ",", skipFirstLine = true) public Class Order { } @CsvRecord( generateHeaderColumns = true ) public Class Order { } order id, client id, first name, last name, isin code, instrument name, quantity, currency, date 10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD, 08-01-2009 @CsvRecord(separator = ",", crlf="MAC") public Class Order { } @CsvRecord(separator = ",", crlf=",\n") public Class Order { } @CsvRecord(isOrdered = true) public Class Order { @DataField(pos = 1, position = 11) private int orderNr; @DataField(pos = 2, position = 10) private String clientNr; } @CsvRecord(separator = ",") public class Order { @DataField(pos = 1) private int orderNr; @Link private Client client; } @Link public class Client { } @CsvRecord(separator = ",") public class Order { @DataField(pos = 1) private int orderNr; @DataField(pos = 5) private String isinCode; } public class Client { @DataField(pos = 2) private String clientNr; @DataField(pos = 3) private String firstName; @DataField(pos = 4) private String lastName; } @CsvRecord(separator = ",") public class Order { @DataField(pos = 1) private int orderNr; @DataField(pos = 5) private String isinCode; @DataField(name = "Name", pos = 6) private String instrumentName; @DataField(pos = 7, precision = 2) private BigDecimal amount; @DataField(pos = 8) private String currency; // pattern used during parsing or when the date is created @DataField(pos = 9, pattern = "dd-MM-yyyy") private Date orderDate; } @CsvRecord(separator = ",") public class Order { @DataField(pos = 1) private int orderNr; @Link private Client client; @DataField(pos = 5) private String isinCode; @DataField(name = "Name", pos = 6) private String instrumentName; @DataField(pos = 7, precision = 2) private BigDecimal amount; @DataField(pos = 8) private String currency; @DataField(pos = 9, pattern = "dd-MM-yyyy") private Date orderDate; } @CsvRecord(separator = ",", isOrdered = true) public class Order { // Positions of the fields start from 1 and not from 0 @DataField(pos = 1, position = 11) private int orderNr; @DataField(pos = 2, position = 10) private String clientNr; @DataField(pos = 3, position = 9) private String firstName; @DataField(pos = 4, position = 8) private String lastName; @DataField(pos = 5, position = 7) private String instrumentCode; @DataField(pos = 6, position = 6) private String instrumentNumber; } @CsvRecord(separator = ",") public class Order { @DataField(pos = 1) private int orderNr; @DataField(pos = 2, required = true) private String clientNr; @DataField(pos = 3, required = true) private String firstName; @DataField(pos = 4, required = true) private String lastName; } Some fields are missing (optional or mandatory), line : @CsvRecord(separator = ",") public class Order { @DataField(pos = 1, trim = true) private int orderNr; @DataField(pos = 2, trim = true) private Integer clientNr; @DataField(pos = 3, required = true) private String firstName; @DataField(pos = 4) private String lastName; } @CsvRecord(separator = ",") public class Order { @DataField(pos = 1) private int orderNr; @DataField(pos = 2) private Integer clientNr; @DataField(pos = 3, required = true) private String firstName; @DataField(pos = 4, defaultValue = "Barin") private String lastName; } @CsvRecord(separator = ",", generateHeaderColumns = true) public class Order { @DataField(pos = 1) private int orderNr; @DataField(pos = 5, columnName = "ISIN") private String isinCode; @DataField(name = "Name", pos = 6) private String instrumentName; } 10A9PaulineMISINXD12345678BUYShare2500.45USD01-08-2009 @FixedLengthRecord(length=54, paddingChar=' ') public static class Order { @DataField(pos = 1, length=2) private int orderNr; @DataField(pos = 3, length=2) private String clientNr; @DataField(pos = 5, length=7) private String firstName; @DataField(pos = 12, length=1, align="L") private String lastName; @DataField(pos = 13, length=4) private String instrumentCode; @DataField(pos = 17, length=10) private String instrumentNumber; @DataField(pos = 27, length=3) private String orderType; @DataField(pos = 30, length=5) private String instrumentType; @DataField(pos = 35, precision = 2, length=7) private BigDecimal amount; @DataField(pos = 42, length=3) private String currency; @DataField(pos = 45, length=10, pattern = "dd-MM-yyyy") private Date orderDate; } 10A9 PaulineM ISINXD12345678BUYShare2500.45USD01-08-2009 @FixedLengthRecord(length=60, paddingChar=' ') public static class Order { @DataField(pos = 1, length=2) private int orderNr; @DataField(pos = 3, length=2) private String clientNr; @DataField(pos = 5, length=9) private String firstName; @DataField(pos = 14, length=5, align="L") // align text to the LEFT zone of the block private String lastName; @DataField(pos = 19, length=4) private String instrumentCode; @DataField(pos = 23, length=10) private String instrumentNumber; @DataField(pos = 33, length=3) private String orderType; @DataField(pos = 36, length=5) private String instrumentType; @DataField(pos = 41, precision = 2, length=7) private BigDecimal amount; @DataField(pos = 48, length=3) private String currency; @DataField(pos = 51, length=10, pattern = "dd-MM-yyyy") private Date orderDate; } 10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009 @FixedLengthRecord(length = 65, paddingChar = ' ') public static class Order { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 3, length = 2) private String clientNr; @DataField(pos = 5, length = 9) private String firstName; @DataField(pos = 14, length = 5, align = "L") private String lastName; @DataField(pos = 19, length = 4) private String instrumentCode; @DataField(pos = 23, length = 10) private String instrumentNumber; @DataField(pos = 33, length = 3) private String orderType; @DataField(pos = 36, length = 5) private String instrumentType; @DataField(pos = 41, precision = 2, length = 12, paddingChar = '0') private BigDecimal amount; @DataField(pos = 53, length = 3) private String currency; @DataField(pos = 56, length = 10, pattern = "dd-MM-yyyy") private Date orderDate; } 10A9Pauline^M^ISINXD12345678BUYShare000002500.45USD01-08-2009 @FixedLengthRecord public static class Order { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 2, length = 2) private String clientNr; @DataField(pos = 3, delimiter = "^") private String firstName; @DataField(pos = 4, delimiter = "^") private String lastName; @DataField(pos = 5, length = 4) private String instrumentCode; @DataField(pos = 6, length = 10) private String instrumentNumber; @DataField(pos = 7, length = 3) private String orderType; @DataField(pos = 8, length = 5) private String instrumentType; @DataField(pos = 9, precision = 2, length = 12, paddingChar = '0') private BigDecimal amount; @DataField(pos = 10, length = 3) private String currency; @DataField(pos = 11, length = 10, pattern = "dd-MM-yyyy") private Date orderDate; } 10A9Pauline^M^ISIN10XD12345678BUYShare000002500.45USD01-08-2009 @FixedLengthRecord public static class Order { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 2, length = 2) private String clientNr; @DataField(pos = 3, delimiter = "^") private String firstName; @DataField(pos = 4, delimiter = "^") private String lastName; @DataField(pos = 5, length = 4) private String instrumentCode; @DataField(pos = 6, length = 2, align = "R", paddingChar = '0') private int instrumentNumberLen; @DataField(pos = 7, lengthPos=6) private String instrumentNumber; @DataField(pos = 8, length = 3) private String orderType; @DataField(pos = 9, length = 5) private String instrumentType; @DataField(pos = 10, precision = 2, length = 12, paddingChar = '0') private BigDecimal amount; @DataField(pos = 11, length = 3) private String currency; @DataField(pos = 12, length = 10, pattern = "dd-MM-yyyy") private Date orderDate; } 101-08-2009 10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009 10A9 RichN ISINXD12345678BUYShare000002700.45USD01-08-2009 9000000002 @FixedLengthRecord(header = OrderHeader.class, footer = OrderFooter.class) public class Order { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 2, length = 2) private String clientNr; @DataField(pos = 3, length = 9) private String firstName; @DataField(pos = 4, length = 5, align = "L") private String lastName; @DataField(pos = 5, length = 4) private String instrumentCode; @DataField(pos = 6, length = 10) private String instrumentNumber; @DataField(pos = 7, length = 3) private String orderType; @DataField(pos = 8, length = 5) private String instrumentType; @DataField(pos = 9, precision = 2, length = 12, paddingChar = '0') private BigDecimal amount; @DataField(pos = 10, length = 3) private String currency; @DataField(pos = 11, length = 10, pattern = "dd-MM-yyyy") private Date orderDate; } @FixedLengthRecord public class OrderHeader { @DataField(pos = 1, length = 1) private int recordType = 1; @DataField(pos = 2, length = 10, pattern = "dd-MM-yyyy") private Date recordDate; } @FixedLengthRecord public class OrderFooter { @DataField(pos = 1, length = 1) private int recordType = 9; @DataField(pos = 2, length = 9, align = "R", paddingChar = '0') private int numberOfRecordsInTheFile; } @FixedLengthRecord(ignoreTrailingChars = true) public static class Order { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 3, length = 2) private String clientNr; // any characters that appear beyond the last mapped field will be ignored } 8=FIX.4.1 9=20 34=1 35=0 49=INVMGR 56=BRKR 1=BE.CHM.001 11=CHM0001-01 22=4 @Message(keyValuePairSeparator = "=", pairSeparator = "\u0001", type="FIX", version="4.1") public class Order { } @Message(keyValuePairSeparator = "=", pairSeparator = "\u0001", type="FIX", version="4.1") public class Order { @Link Header header; @Link Trailer trailer; @KeyValuePairField(tag = 1) // Client reference private String Account; @KeyValuePairField(tag = 11) // Order reference private String ClOrdId; @KeyValuePairField(tag = 22) // Fund ID type (Sedol, ISIN, ...) private String IDSource; @KeyValuePairField(tag = 48) // Fund code private String SecurityId; @KeyValuePairField(tag = 54) // Movement type ( 1 = Buy, 2 = sell) private String Side; @KeyValuePairField(tag = 58) // Free text private String Text; } @Message(keyValuePairSeparator = "=", pairSeparator = "\\u0001", type = "FIX", version = "4.1", isOrdered = true) public class Order { @Link Header header; @Link Trailer trailer; @KeyValuePairField(tag = 1, position = 1) // Client reference private String account; @KeyValuePairField(tag = 11, position = 3) // Order reference private String clOrdId; } @Section(number = 1) public class Header { @KeyValuePairField(tag = 8, position = 1) // Message Header private String beginString; @KeyValuePairField(tag = 9, position = 2) // Checksum private int bodyLength; } @Section(number = 2) @Message(keyValuePairSeparator = "=", pairSeparator = "\\u0001", type = "FIX", version = "4.1", isOrdered = true) public class Order { @Link Header header; @Link Trailer trailer; @KeyValuePairField(tag = 1, position = 1) // Client reference private String account; @KeyValuePairField(tag = 11, position = 3) // Order reference private String clOrdId; @Section(number = 3) public class Trailer { @KeyValuePairField(tag = 10, position = 1) // CheckSum private int checkSum; public int getCheckSum() { return checkSum; } Claus,Ibsen,Camel in Action 1,2010,35 Claus,Ibsen,Camel in Action 2,2012,35 Claus,Ibsen,Camel in Action 3,2013,35 Claus,Ibsen,Camel in Action 4,2014,35 @CsvRecord(separator=",") public class Author { @DataField(pos = 1) private String firstName; @DataField(pos = 2) private String lastName; @OneToMany private List<Book> books; @DataField(pos = 5) private String Age; } public class Book { @DataField(pos = 3) private String title; @DataField(pos = 4) private String year; } 8=FIX 4.19=2034=135=049=INVMGR56=BRKR 1=BE.CHM.00111=CHM0001-0158=this is a camel - bindy test 22=448=BE000124567854=1 22=548=BE000987654354=2 22=648=BE000999999954=3 10=220 public class Order { @Link Header header; @Link Trailer trailer; @KeyValuePairField(tag = 1) // Client reference private String account; @KeyValuePairField(tag = 11) // Order reference private String clOrdId; @KeyValuePairField(tag = 58) // Free text private String text; @OneToMany(mappedTo = "org.apache.camel.dataformat.bindy.model.fix.complex.onetomany.Security") List<Security> securities; } public class Security { @KeyValuePairField(tag = 22) // Fund ID type (Sedol, ISIN, ...) private String idSource; @KeyValuePairField(tag = 48) // Fund code private String securityCode; @KeyValuePairField(tag = 54) // Movement type ( 1 = Buy, 2 = sell) private String side; } @FixedLengthRecord(length = 10, paddingChar = ' ') public static class DataModel { @DataField(pos = 1, length = 10, trim = true) @BindyConverter(CustomConverter.class) public String field1; } public static class CustomConverter implements Format<String> { @Override public String format(String object) throws Exception { return (new StringBuilder(object)).reverse().toString(); } @Override public String parse(String string) throws Exception { return (new StringBuilder(string)).reverse().toString(); } } @CsvRecord(separator = ",") @FormatFactories({OrderNumberFormatFactory.class}) public static class Order { @DataField(pos = 1) private OrderNumber orderNr; @DataField(pos = 2) private String firstName; } public static class OrderNumber { private int orderNr; public static OrderNumber ofString(String orderNumber) { OrderNumber result = new OrderNumber(); result.orderNr = Integer.valueOf(orderNumber); return result; } } public static class OrderNumberFormatFactory extends AbstractFormatFactory { { supportedClasses.add(OrderNumber.class); } @Override public Format<?> build(FormattingOptions formattingOptions) { return new Format<OrderNumber>() { @Override public String format(OrderNumber object) throws Exception { return String.valueOf(object.orderNr); } @Override public OrderNumber parse(String string) throws Exception { return OrderNumber.ofString(string); } }; } } DataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class); BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class); bindy.setLocale("us"); BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class); bindy.setLocale("default"); from("file://inbox") .unmarshal(bindy) .to("direct:handleOrders"); from("file://inbox") .unmarshal("myBindyDataFormat") .to("direct:handleOrders"); List<Map<String, Object>> unmarshaledModels = (List<Map<String, Object>>) exchange.getIn().getBody(); int modelCount = 0; for (Map<String, Object> model : unmarshaledModels) { for (String className : model.keySet()) { Object obj = model.get(className); LOG.info("Count : " + modelCount + ", " + obj.toString()); } modelCount++; } LOG.info("Total CSV records received by the csv bean : " + modelCount); from("file://inbox") .unmarshal(bindy) .split(body()) .process(new Processor() { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Map<String, Object> modelMap = (Map<String, Object>) in.getBody(); in.setBody(modelMap.get(Order.class.getCanonicalName())); } }) .to("direct:handleSingleOrder") .end(); from("file://inbox?charset=Cp922") .removeProperty(Exchange.CHARSET_NAME) .unmarshal("myBindyDataFormat") .to("direct:handleOrders"); from("direct:handleOrders") .marshal(bindy) .to("file://outbox") <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <!-- Queuing engine - ActiveMq - work locally in mode virtual memory --> <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent"> <property name="brokerURL" value="vm://localhost:61616"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <dataFormats> <bindy id="bindyDataformat" type="Csv" classType="org.apache.camel.bindy.model.Order"/> </dataFormats> <route> <from uri="file://src/data/csv/?noop=true" /> <unmarshal ref="bindyDataformat" /> <to uri="bean:csv" /> <to uri="activemq:queue:in" /> </route> <route> <from uri="activemq:queue:in" /> <marshal ref="bindyDataformat" /> <to uri="file://src/data/csv/out/" /> </route> </camelContext> </beans> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-bindy</artifactId> <version>{CamelSBVersion}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-browse-starter</artifactId> </dependency> browse:someName[?options] browse:name from("activemq:order.in").to("browse:orderReceived").to("bean:processOrder"); private CamelContext context; public void inspectReceivedOrders() { BrowsableEndpoint browse = context.getEndpoint("browse:orderReceived", BrowsableEndpoint.class); List<Exchange> exchanges = browse.getExchanges(); // then we can inspect the list of received exchanges from Java for (Exchange exchange : exchanges) { String payload = exchange.getIn().getBody(); // do something with payload } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cassandraql-starter</artifactId> </dependency> cql:beanRef:hosts:port/keyspace CREATE TABLE CAMEL_IDEMPOTENT ( NAME varchar, -- Repository name KEY varchar, -- Message key PRIMARY KEY (NAME, KEY) ) WITH compaction = {'class':'LeveledCompactionStrategy'} AND gc_grace_seconds = 86400; CREATE TABLE CAMEL_AGGREGATION ( NAME varchar, -- Repository name KEY varchar, -- Correlation id EXCHANGE_ID varchar, -- Exchange id EXCHANGE blob, -- Serialized exchange PRIMARY KEY (NAME, KEY) ) WITH compaction = {'class':'LeveledCompactionStrategy'} AND gc_grace_seconds = 86400; String CQL = "insert into camel_user(login, first_name, last_name) values (?, ?, ?)"; from("direct:input") .to("cql://localhost/camel_ks?cql=" + CQL); Arrays.asList("davsclaus", "Claus", "Ibsen") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cics-starter</artifactId> </dependency> <dependency> <artifactId>com.ibm</artifactId> <groupId>ctgclient</groupId> <scope>system</scope> <systemPath>USD{basedir}/lib/ctgclient.jar</systemPath> </dependency> cics://[interfaceType]/[dataExchangeType][?options] cics://eci?host=xxx&port=xxx cics://eci/channel?host=xxx&port=xxx cics://[interfaceType]/[dataExchangeType][?options] //.. import static com.redhat.camel.component.cics.CICSConstants.CICS_PROGRAM_NAME_HEADER; import static com.redhat.camel.component.cics.CICSConstants.CICS_COMM_AREA_SIZE_HEADER; //. from("direct:run"). setHeader(CICS_PROGRAM_NAME_HEADER, "ECIREADY"). setHeader(CICS_COMM_AREA_SIZE_HEADER, 18). setBody(constant("My input data")). to("cics:eci/commarea?host=192.168.0.23&port=2006&protocol=tcp&userId=foo&password=bar"); //.. import static com.redhat.camel.component.cics.CICSConstants.CICS_PROGRAM_NAME_HEADER; import static com.redhat.camel.component.cics.CICSConstants.CICS_CHANNEL_NAME_HEADER; import static com.redhat.camel.component.cics.CICSConstants.CICS_CONTAINER_NAME_HEADER; // from("direct:run"). setHeader(CICS_PROGRAM_NAME_HEADER, "EC03"). setHeader(CICS_CHANNEL_NAME_HEADER, "SAMPLECHANNEL"). setHeader(CICS_CONTAINER_NAME_HEADER, "INPUTDATA"). setBody(constant("My input data")). to("cics:eci/channel?host=192.168.0.23&port=2006&protocol=tcp&userId=foo&password=bar"); //.. import static com.redhat.camel.component.cics.CICSConstants.CICS_PROGRAM_NAME_HEADER; import static com.redhat.camel.component.cics.CICSConstants.CICS_CHANNEL_NAME_HEADER; // from("direct:run"). setHeader(CICS_PROGRAM_NAME_HEADER, "EC03"). setHeader(CICS_CHANNEL_NAME_HEADER, "SAMPLECHANNEL"). process(exchange->{ byte[] thirdContainerData = HexFormat.of().parseHex("e04fd020ea3a6910a2d808002b30309d"); Map<String,Object> containers = Map.of( "firstContainerName", "firstContainerData", "secondContainerName", "secondContainerData", "thirdContainerName", thirdContainerData ); exchange.getMessage().setBody(containers); }). to("cics:eci/channel?host=192.168.0.23&port=2006&protocol=tcp&userId=foo&password=bar"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> <route> <from uri="seda:a"/> <setHeader name="theHeader"> <constant>the value</constant> </setHeader> <to uri="mock:b"/> </route> from("seda:a") .setHeader("theHeader", constant("the value")) .to("mock:b"); <route> <from uri="seda:a"/> <setHeader name="zipCode"> <constant resultType="int">90210</constant> </setHeader> <to uri="mock:b"/> </route> .setHeader("myHeader").constant("resource:classpath:constant.txt") controlbus:command[?options] <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-controlbus-starter</artifactId> </dependency> controlbus:command:language template.sendBody("controlbus:route?routeId=foo&action=start", null); String status = template.requestBody("controlbus:route?routeId=foo&action=status", null, String.class); String xml = template.requestBody("controlbus:route?routeId=foo&action=stats", null, String.class); String xml = template.requestBody("controlbus:route?action=stats", null, String.class); template.sendBody("controlbus:language:simple", "USD{camelContext.getRouteController().stopRoute('myRoute')}"); String status = template.requestBody("controlbus:language:simple", "USD{camelContext.getRouteStatus('myRoute')}", String.class); template.sendBody("controlbus:language:simple?async=true", "USD{camelContext.stop()}"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cron-starter</artifactId> </dependency> cron:name from("cron:tab?schedule=0/1+*+*+*+*+?") .setBody().constant("event") .log("USD{body}"); <route> <from uri="cron:tab?schedule=0/1+*+*+*+*+?"/> <setBody> <constant>event</constant> </setBody> <to uri="log:info"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-crypto-starter</artifactId> </dependency> crypto:sign:name[?options] crypto:verify:name[?options] crypto:cryptoOperation:name KeyPair keyPair = KeyGenerator.getInstance("RSA").generateKeyPair(); from("direct:sign") .setHeader(DigitalSignatureConstants.SIGNATURE_PRIVATE_KEY, constant(keys.getPrivate())) .to("crypto:sign:message") .to("direct:verify"); from("direct:verify") .setHeader(DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT, constant(keys.getPublic())) .to("crypto:verify:check"); keytool -genkey -keyalg RSA -keysize 2048 -keystore keystore.jks -storepass letmein -alias bob -dname "CN=Bob,OU=IT,O=Camel" -noprompt from("direct:sign") .to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein") .log("Signature: USD{header.CamelDigitalSignature}") .to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein") .log("Verified: USD{body}"); @Configuration public class KeystoreConfig { @BindToRegistry public KeyStore myKeystore() throws Exception { KeyStore store = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream("keystore.jks")) { store.load(fis, "letmein".toCharArray()); } return store; } } from("direct:sign") .to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature") .log("Signature: USD{header.mySignature}") .to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature"); Exchange unsigned = getMandatoryEndpoint("direct:alias-sign").createExchange(); unsigned.getIn().setBody(payload); unsigned.getIn().setHeader(DigitalSignatureConstants.KEYSTORE_ALIAS, "bob"); unsigned.getIn().setHeader(DigitalSignatureConstants.KEYSTORE_PASSWORD, "letmein".toCharArray()); template.send("direct:alias-sign", unsigned); Exchange signed = getMandatoryEndpoint("direct:alias-sign").createExchange(); signed.getIn().copyFrom(unsigned.getMessage()); signed.getIn().setHeader(DigitalSignatureConstants.KEYSTORE_ALIAS, "bob"); template.send("direct:alias-verify", signed); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> Hello USD\{body[0].name} Hello USD\{bodyAsIndex(com.foo.MyUser, 0).name} <plugins> <!-- generate source code for csimple languages --> <plugin> <groupId>org.apache.camel</groupId> <artifactId>camel-csimple-maven-plugin</artifactId> <version>USD{camel.version}</version> <executions> <execution> <id>generate</id> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> <!-- include source code generated to maven sources paths --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>add-source</goal> <goal>add-resource</goal> </goals> <configuration> <sources> <source>src/generated/java</source> </sources> <resources> <resource> <directory>src/generated/resources</directory> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-csimple-joor</artifactId> <version>{CamelSBProjectVersion}</version> </dependency> Hello USD{bean:greeter(USD{body}, USD{header.counter})} USD{bodyAs(MyUser)?.address?.zip} > 10000 import java.util.*; import java.util.concurrent.*; import java.util.stream.*; import org.apache.camel.*; import org.apache.camel.util.*; import com.foo.MyUser; import com.bar.*; import static com.foo.MyHelper.*; echo()=USD{bodyAs(String)} USD{bodyAs(String)} from("direct:hello") .transform(csimple("Hello echo()")) .log("You said USD{body}"); .transform(csimple("Hello USD{bodyAs(String)} USD{bodyAs(String)}")) <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cxf-soap-starter</artifactId> </dependency> cxf:bean:cxfEndpoint[?options] cxf://someAddress[?options] cxf:bean:cxfEndpoint?wsdlURL=wsdl/hello_world.wsdl&dataFormat=PAYLOAD cxf:beanId:address @Bean public CxfEndpoint serviceEndpoint(LoggingOutInterceptor loggingOutInterceptor) { CxfSpringEndpoint cxfEndpoint = new CxfSpringEndpoint(); cxfEndpoint.setAddress("http://localhost:" + port + "/services" + SERVICE_ADDRESS); cxfEndpoint.setServiceClass(org.apache.camel.component.cxf.HelloService.class); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("dataFormat", "RAW"); cxfEndpoint.setProperties(properties); cxfEndpoint.getOutInterceptors().add(loggingOutInterceptor); return cxfEndpoint; } @Bean public LoggingOutInterceptor loggingOutInterceptor() { LoggingOutInterceptor logger = new LoggingOutInterceptor("write"); return logger; } <cxf:cxfEndpoint ...> <cxf:properties> <entry key="org.apache.camel.cxf.message.headers.relays"> <list> <ref bean="customHeadersRelay"/> </list> </entry> </cxf:properties> </cxf:cxfEndpoint> <bean id="customHeadersRelay" class="org.apache.camel.component.cxf.soap.headers.CustomHeadersRelay"/> @Bean public HeaderFilterStrategy dropAllMessageHeadersStrategy() { CxfHeaderFilterStrategy headerFilterStrategy = new CxfHeaderFilterStrategy(); headerFilterStrategy.setRelayHeaders(false); return headerFilterStrategy; } @Bean public CxfEndpoint routerNoRelayEndpoint(HeaderFilterStrategy dropAllMessageHeadersStrategy) { CxfSpringEndpoint cxfEndpoint = new CxfSpringEndpoint(); cxfEndpoint.setServiceClass(org.apache.camel.component.cxf.soap.headers.HeaderTester.class); cxfEndpoint.setAddress("/CxfMessageHeadersRelayTest/HeaderService/routerNoRelayEndpoint"); cxfEndpoint.setWsdlURL("soap_header.wsdl"); cxfEndpoint.setEndpointNameAsQName( QName.valueOf("{http://apache.org/camel/component/cxf/soap/headers}SoapPortNoRelay")); cxfEndpoint.setServiceNameAsQName(SERVICENAME); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("dataFormat", "PAYLOAD"); cxfEndpoint.setProperties(properties); cxfEndpoint.setHeaderFilterStrategy(dropAllMessageHeadersStrategy); return cxfEndpoint; } @Bean public CxfEndpoint serviceNoRelayEndpoint(HeaderFilterStrategy dropAllMessageHeadersStrategy) { CxfSpringEndpoint cxfEndpoint = new CxfSpringEndpoint(); cxfEndpoint.setServiceClass(org.apache.camel.component.cxf.soap.headers.HeaderTester.class); cxfEndpoint.setAddress("http://localhost:" + port + "/services/CxfMessageHeadersRelayTest/HeaderService/routerNoRelayEndpointBackend"); cxfEndpoint.setWsdlURL("soap_header.wsdl"); cxfEndpoint.setEndpointNameAsQName( QName.valueOf("{http://apache.org/camel/component/cxf/soap/headers}SoapPortNoRelay")); cxfEndpoint.setServiceNameAsQName(SERVICENAME); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("dataFormat", "PAYLOAD"); cxfEndpoint.setProperties(properties); cxfEndpoint.setHeaderFilterStrategy(dropAllMessageHeadersStrategy); return cxfEndpoint; } rom("cxf:bean:routerNoRelayEndpoint") .to("cxf:bean:serviceNoRelayEndpoint"); @Bean public HeaderFilterStrategy customMessageFilterStrategy() { CxfHeaderFilterStrategy headerFilterStrategy = new CxfHeaderFilterStrategy(); List<MessageHeaderFilter> headerFilterList = new ArrayList<MessageHeaderFilter>(); headerFilterList.add(new SoapMessageHeaderFilter()); headerFilterList.add(new CustomHeaderFilter()); headerFilterStrategy.setMessageHeaderFilters(headerFilterList); return headerFilterStrategy; } <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf/jaxws" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/cxf/jaxws http://camel.apache.org/schema/cxf/jaxws/camel-cxf.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <cxf:cxfEndpoint id="routerEndpoint" address="http://localhost:9003/CamelContext/RouterPort" serviceClass="org.apache.hello_world_soap_http.GreeterImpl"/> <cxf:cxfEndpoint id="serviceEndpoint" address="http://localhost:9000/SoapContext/SoapPort" wsdlURL="testutils/hello_world.wsdl" serviceClass="org.apache.hello_world_soap_http.Greeter" endpointName="s:SoapPort" serviceName="s:SOAPService" xmlns:s="http://apache.org/hello_world_soap_http" /> <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="cxf:bean:routerEndpoint" /> <to uri="cxf:bean:serviceEndpoint" /> </route> </camelContext> </beans> <cxf:cxfEndpoint id="testEndpoint" address="http://localhost:9000/router" serviceClass="org.apache.camel.component.cxf.HelloService" endpointName="s:PortName" serviceName="s:ServiceName" xmlns:s="http://www.example.com/test"> <cxf:properties> <entry key="dataFormat" value="RAW"/> <entry key="setDefaultBus" value="true"/> </cxf:properties> </cxf:cxfEndpoint> @ImportResource({ "classpath:spring-configuration.xml" }) Error:sendSms: SoapFault exception: [Client] looks like we got no XML document in [...] public class WriteXmlDeclarationInterceptor extends AbstractPhaseInterceptor<SoapMessage> { public WriteXmlDeclarationInterceptor() { super(Phase.PRE_STREAM); addBefore(StaxOutInterceptor.class.getName()); } public void handleMessage(SoapMessage message) throws Fault { message.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE); } } // set up the response context which force start document Map<String, Object> map = new HashMap<String, Object>(); map.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE); exchange.getOut().setHeader(Client.RESPONSE_CONTEXT, map); // set up the service address from the message header to override the setting of CXF endpoint exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, constant(getServiceAddress())); public class PersonProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(PersonProcessor.class); @Override @SuppressWarnings("unchecked") public void process(Exchange exchange) throws Exception { LOG.info("processing exchange in camel"); BindingOperationInfo boi = (BindingOperationInfo) exchange.getProperty(BindingOperationInfo.class.getName()); if (boi != null) { LOG.info("boi.isUnwrapped" + boi.isUnwrapped()); } // Get the parameters list which element is the holder. MessageContentsList msgList = (MessageContentsList) exchange.getIn().getBody(); Holder<String> personId = (Holder<String>) msgList.get(0); Holder<String> ssn = (Holder<String>) msgList.get(1); Holder<String> name = (Holder<String>) msgList.get(2); if (personId.value == null || personId.value.length() == 0) { LOG.info("person id 123, so throwing exception"); // Try to throw out the soap fault message org.apache.camel.wsdl_first.types.UnknownPersonFault personFault = new org.apache.camel.wsdl_first.types.UnknownPersonFault(); personFault.setPersonId(""); org.apache.camel.wsdl_first.UnknownPersonFault fault = new org.apache.camel.wsdl_first.UnknownPersonFault("Get the null value of person name", personFault); exchange.getMessage().setBody(fault); return; } name.value = "Bonjour"; ssn.value = "123"; LOG.info("setting Bonjour as the response"); // Set the response message, first element is the return value of the operation, // the others are the holders of method parameters exchange.getMessage().setBody(new Object[] { null, personId, ssn, name }); } } Exchange senderExchange = new DefaultExchange(context, ExchangePattern.InOut); final List<String> params = new ArrayList<>(); // Prepare the request message for the camel-cxf procedure params.add(TEST_MESSAGE); senderExchange.getIn().setBody(params); senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, ECHO_OPERATION); Exchange exchange = template.send("direct:EndpointA", senderExchange); org.apache.camel.Message out = exchange.getMessage(); // The response message's body is an MessageContentsList which first element is the return value of the operation, // If there are some holder parameters, the holder parameter will be filled in the reset of List. // The result will be extract from the MessageContentsList with the String class type MessageContentsList result = (MessageContentsList) out.getBody(); LOG.info("Received output text: " + result.get(0)); Map<String, Object> responseContext = CastUtils.cast((Map<?, ?>) out.getHeader(Client.RESPONSE_CONTEXT)); assertNotNull(responseContext); assertEquals("UTF-8", responseContext.get(org.apache.cxf.message.Message.ENCODING), "We should get the response context here"); assertEquals("echo " + TEST_MESSAGE, result.get(0), "Reply body on Camel is wrong"); protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(simpleEndpointURI + "&dataFormat=PAYLOAD").to("log:info").process(new Processor() { @SuppressWarnings("unchecked") public void process(final Exchange exchange) throws Exception { CxfPayload<SoapHeader> requestPayload = exchange.getIn().getBody(CxfPayload.class); List<Source> inElements = requestPayload.getBodySources(); List<Source> outElements = new ArrayList<>(); // You can use a customer toStringConverter to turn a CxfPayLoad message into String as you want String request = exchange.getIn().getBody(String.class); XmlConverter converter = new XmlConverter(); String documentString = ECHO_RESPONSE; Element in = new XmlConverter().toDOMElement(inElements.get(0)); // Just check the element namespace if (!in.getNamespaceURI().equals(ELEMENT_NAMESPACE)) { throw new IllegalArgumentException("Wrong element namespace"); } if (in.getLocalName().equals("echoBoolean")) { documentString = ECHO_BOOLEAN_RESPONSE; checkRequest("ECHO_BOOLEAN_REQUEST", request); } else { documentString = ECHO_RESPONSE; checkRequest("ECHO_REQUEST", request); } Document outDocument = converter.toDOMDocument(documentString, exchange); outElements.add(new DOMSource(outDocument.getDocumentElement())); // set the payload header with null CxfPayload<SoapHeader> responsePayload = new CxfPayload<>(null, outElements, null); exchange.getMessage().setBody(responsePayload); } }); } }; } from("cxf:bean:routerRelayEndpointWithInsertion") .process(new InsertRequestOutHeaderProcessor()) .to("cxf:bean:serviceRelayEndpointWithInsertion") .process(new InsertResponseOutHeaderProcessor()); @Bean public CxfEndpoint routerRelayEndpointWithInsertion() { CxfSpringEndpoint cxfEndpoint = new CxfSpringEndpoint(); cxfEndpoint.setServiceClass(org.apache.camel.component.cxf.soap.headers.HeaderTester.class); cxfEndpoint.setAddress("/CxfMessageHeadersRelayTest/HeaderService/routerRelayEndpointWithInsertion"); cxfEndpoint.setWsdlURL("soap_header.wsdl"); cxfEndpoint.setEndpointNameAsQName( QName.valueOf("{http://apache.org/camel/component/cxf/soap/headers}SoapPortRelayWithInsertion")); cxfEndpoint.setServiceNameAsQName(SERVICENAME); cxfEndpoint.getFeatures().add(new LoggingFeature()); return cxfEndpoint; } @Bean public CxfEndpoint serviceRelayEndpointWithInsertion() { CxfSpringEndpoint cxfEndpoint = new CxfSpringEndpoint(); cxfEndpoint.setServiceClass(org.apache.camel.component.cxf.soap.headers.HeaderTester.class); cxfEndpoint.setAddress("http://localhost:" + port + "/services/CxfMessageHeadersRelayTest/HeaderService/routerRelayEndpointWithInsertionBackend"); cxfEndpoint.setWsdlURL("soap_header.wsdl"); cxfEndpoint.setEndpointNameAsQName( QName.valueOf("{http://apache.org/camel/component/cxf/soap/headers}SoapPortRelayWithInsertion")); cxfEndpoint.setServiceNameAsQName(SERVICENAME); cxfEndpoint.getFeatures().add(new LoggingFeature()); return cxfEndpoint; } public static class InsertResponseOutHeaderProcessor implements Processor { public void process(Exchange exchange) throws Exception { List<SoapHeader> soapHeaders = CastUtils.cast((List<?>)exchange.getIn().getHeader(Header.HEADER_LIST)); // Insert a new header String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><outofbandHeader " + "xmlns=\"http://cxf.apache.org/outofband/Header\" hdrAttribute=\"testHdrAttribute\" " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:mustUnderstand=\"1\">" + "<name>New_testOobHeader</name><value>New_testOobHeaderValue</value></outofbandHeader>"; SoapHeader newHeader = new SoapHeader(soapHeaders.get(0).getName(), DOMUtils.readXml(new StringReader(xml)).getDocumentElement()); // make sure direction is OUT since it is a response message. newHeader.setDirection(Direction.DIRECTION_OUT); //newHeader.setMustUnderstand(false); soapHeaders.add(newHeader); } } from(getRouterEndpointURI()).process(new Processor() { @SuppressWarnings("unchecked") public void process(Exchange exchange) throws Exception { CxfPayload<SoapHeader> payload = exchange.getIn().getBody(CxfPayload.class); List<Source> elements = payload.getBodySources(); assertNotNull(elements, "We should get the elements here"); assertEquals(1, elements.size(), "Get the wrong elements size"); Element el = new XmlConverter().toDOMElement(elements.get(0)); elements.set(0, new DOMSource(el)); assertEquals("http://camel.apache.org/pizza/types", el.getNamespaceURI(), "Get the wrong namespace URI"); List<SoapHeader> headers = payload.getHeaders(); assertNotNull(headers, "We should get the headers here"); assertEquals(1, headers.size(), "Get the wrong headers size"); assertEquals("http://camel.apache.org/pizza/types", ((Element) (headers.get(0).getObject())).getNamespaceURI(), "Get the wrong namespace URI"); // alternatively you can also get the SOAP header via the camel header: headers = exchange.getIn().getHeader(Header.HEADER_LIST, List.class); assertNotNull(headers, "We should get the headers here"); assertEquals(1, headers.size(), "Get the wrong headers size"); assertEquals("http://camel.apache.org/pizza/types", ((Element) (headers.get(0).getObject())).getNamespaceURI(), "Get the wrong namespace URI"); } }) .to(getServiceEndpointURI()); SOAP_FAULT = new SoapFault(EXCEPTION_MESSAGE, SoapFault.FAULT_CODE_CLIENT); Element detail = SOAP_FAULT.getOrCreateDetail(); Document doc = detail.getOwnerDocument(); Text tn = doc.createTextNode(DETAIL_TEXT); detail.appendChild(tn); from(routerEndpointURI).setFaultBody(constant(SOAP_FAULT)); from(routerEndpointURI).process(new Processor() { public void process(Exchange exchange) throws Exception { Message out = exchange.getOut(); // Set the message body with the out.setBody(this.getClass().getResourceAsStream("SoapFaultMessage.xml")); // Set the response code here out.setHeader(org.apache.cxf.message.Message.RESPONSE_CODE, new Integer(500)); } }); CxfExchange exchange = (CxfExchange)template.send(getJaxwsEndpointUri(), new Processor() { public void process(final Exchange exchange) { final List<String> params = new ArrayList<String>(); params.add(TEST_MESSAGE); // Set the request context to the inMessage Map<String, Object> requestContext = new HashMap<String, Object>(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, JAXWS_SERVER_ADDRESS); exchange.getIn().setBody(params); exchange.getIn().setHeader(Client.REQUEST_CONTEXT , requestContext); exchange.getIn().setHeader(CxfConstants.OPERATION_NAME, GREET_ME_OPERATION); } }); org.apache.camel.Message out = exchange.getOut(); // The output is an object array, the first element of the array is the return value Object\[\] output = out.getBody(Object\[\].class); LOG.info("Received output text: " + output\[0\]); // Get the response context form outMessage Map<String, Object> responseContext = CastUtils.cast((Map)out.getHeader(Client.RESPONSE_CONTEXT)); assertNotNull(responseContext); assertEquals("Get the wrong wsdl operation name", "{http://apache.org/hello_world_soap_http}greetMe", responseContext.get("javax.xml.ws.wsdl.operation").toString()); DataHandler Message.getAttachment(String id) @Bean public CxfEndpoint routerEndpoint() { CxfSpringEndpoint cxfEndpoint = new CxfSpringEndpoint(); cxfEndpoint.setServiceNameAsQName(SERVICE_QNAME); cxfEndpoint.setEndpointNameAsQName(PORT_QNAME); cxfEndpoint.setAddress("/" + getClass().getSimpleName()+ "/jaxws-mtom/hello"); cxfEndpoint.setWsdlURL("mtom.wsdl"); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("dataFormat", "PAYLOAD"); properties.put("mtom-enabled", true); cxfEndpoint.setProperties(properties); return cxfEndpoint; } Exchange exchange = context.createProducerTemplate().send("direct:testEndpoint", new Processor() { public void process(Exchange exchange) throws Exception { exchange.setPattern(ExchangePattern.InOut); List<Source> elements = new ArrayList<Source>(); elements.add(new DOMSource(DOMUtils.readXml(new StringReader(MtomTestHelper.REQ_MESSAGE)).getDocumentElement())); CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null); exchange.getIn().setBody(body); exchange.getIn().addAttachment(MtomTestHelper.REQ_PHOTO_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream"))); exchange.getIn().addAttachment(MtomTestHelper.REQ_IMAGE_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.requestJpeg, "image/jpeg"))); } }); // process response CxfPayload<SoapHeader> out = exchange.getOut().getBody(CxfPayload.class); Assert.assertEquals(1, out.getBody().size()); Map<String, String> ns = new HashMap<String, String>(); ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS); ns.put("xop", MtomTestHelper.XOP_NS); XPathUtils xu = new XPathUtils(ns); Element oute = new XmlConverter().toDOMElement(out.getBody().get(0)); Element ele = (Element)xu.getValue("//ns:DetailResponse/ns:photo/xop:Include", oute, XPathConstants.NODE); String photoId = ele.getAttribute("href").substring(4); // skip "cid:" ele = (Element)xu.getValue("//ns:DetailResponse/ns:image/xop:Include", oute, XPathConstants.NODE); String imageId = ele.getAttribute("href").substring(4); // skip "cid:" DataHandler dr = exchange.getOut().getAttachment(photoId); Assert.assertEquals("application/octet-stream", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.RESP_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream())); dr = exchange.getOut().getAttachment(imageId); Assert.assertEquals("image/jpeg", dr.getContentType()); BufferedImage image = ImageIO.read(dr.getInputStream()); Assert.assertEquals(560, image.getWidth()); Assert.assertEquals(300, image.getHeight()); public static class MyProcessor implements Processor { @SuppressWarnings("unchecked") public void process(Exchange exchange) throws Exception { CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class); // verify request Assert.assertEquals(1, in.getBody().size()); Map<String, String> ns = new HashMap<String, String>(); ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS); ns.put("xop", MtomTestHelper.XOP_NS); XPathUtils xu = new XPathUtils(ns); Element body = new XmlConverter().toDOMElement(in.getBody().get(0)); Element ele = (Element)xu.getValue("//ns:Detail/ns:photo/xop:Include", body, XPathConstants.NODE); String photoId = ele.getAttribute("href").substring(4); // skip "cid:" Assert.assertEquals(MtomTestHelper.REQ_PHOTO_CID, photoId); ele = (Element)xu.getValue("//ns:Detail/ns:image/xop:Include", body, XPathConstants.NODE); String imageId = ele.getAttribute("href").substring(4); // skip "cid:" Assert.assertEquals(MtomTestHelper.REQ_IMAGE_CID, imageId); DataHandler dr = exchange.getIn().getAttachment(photoId); Assert.assertEquals("application/octet-stream", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream())); dr = exchange.getIn().getAttachment(imageId); Assert.assertEquals("image/jpeg", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream())); // create response List<Source> elements = new ArrayList<Source>(); elements.add(new DOMSource(DOMUtils.readXml(new StringReader(MtomTestHelper.RESP_MESSAGE)).getDocumentElement())); CxfPayload<SoapHeader> sbody = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null); exchange.getOut().setBody(sbody); exchange.getOut().addAttachment(MtomTestHelper.RESP_PHOTO_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream"))); exchange.getOut().addAttachment(MtomTestHelper.RESP_IMAGE_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg"))); } } <cxf:cxfEndpoint id="testEndpoint" address="http://localhost:9000/SoapContext/SoapAnyPort"> <cxf:properties> <entry key="dataFormat" value="PAYLOAD"/> </cxf:properties> </cxf:cxfEndpoint> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cxf-rest-starter</artifactId> </dependency> cxfrs://address?options cxfrs:bean:rsEndpoint cxfrs:bean:cxfEndpoint?resourceClasses=org.apache.camel.rs.Example cxfrs:beanId:address // set up the service address from the message header to override the setting of CXF endpoint exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, constant(getServiceAddress())); from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer") .to("log:TEST?showAll=true"); @POST @Path("/customers/{type}") public Response newCustomer(Customer customer, @PathParam("type") String type, @QueryParam("active") @DefaultValue("true") boolean active) { return null; } from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer") .recipientList(simple("direct:USD{header.operationName}")); from("direct:newCustomer") .log("Request: type=USD{header.type}, active=USD{header.active}, customerData=USD{body}"); POST /customers/gold?active=true Payload: <Customer> <fullName>Raul Kripalani</fullName> <country>Spain</country> <project>Apache Camel</project> </Customer> Request: type=gold, active=true, customerData=<Customer.toString() representation> private static final String CXF_RS_ENDPOINT_URI = "cxfrs://http://localhost:" + CXT + "/rest?resourceClasses=org.apache.camel.component.cxf.jaxrs.testbean.CustomerServiceResource"; private static final String CXF_RS_ENDPOINT_URI2 = "cxfrs://http://localhost:" + CXT + "/rest2?resourceClasses=org.apache.camel.component.cxf.jaxrs.testbean.CustomerService"; private static final String CXF_RS_ENDPOINT_URI3 = "cxfrs://http://localhost:" + CXT + "/rest3?" + "resourceClasses=org.apache.camel.component.cxf.jaxrs.testbean.CustomerServiceNoAnnotations&" + "modelRef=classpath:/org/apache/camel/component/cxf/jaxrs/CustomerServiceModel.xml"; private static final String CXF_RS_ENDPOINT_URI4 = "cxfrs://http://localhost:" + CXT + "/rest4?" + "modelRef=classpath:/org/apache/camel/component/cxf/jaxrs/CustomerServiceDefaultHandlerModel.xml"; private static final String CXF_RS_ENDPOINT_URI5 = "cxfrs://http://localhost:" + CXT + "/rest5?" + "propagateContexts=true&" + "modelRef=classpath:/org/apache/camel/component/cxf/jaxrs/CustomerServiceDefaultHandlerModel.xml"; protected RouteBuilder createRouteBuilder() throws Exception { final Processor testProcessor = new TestProcessor(); final Processor testProcessor2 = new TestProcessor2(); final Processor testProcessor3 = new TestProcessor3(); return new RouteBuilder() { public void configure() { errorHandler(new NoErrorHandlerBuilder()); from(CXF_RS_ENDPOINT_URI).process(testProcessor); from(CXF_RS_ENDPOINT_URI2).process(testProcessor); from(CXF_RS_ENDPOINT_URI3).process(testProcessor); from(CXF_RS_ENDPOINT_URI4).process(testProcessor2); from(CXF_RS_ENDPOINT_URI5).process(testProcessor3); } }; } @Path("/customerservice/") public interface CustomerServiceResource { @GET @Path("/customers/{id}/") Customer getCustomer(@PathParam("id") String id); @PUT @Path("/customers/") Response updateCustomer(Customer customer); @Path("/{id}") @PUT() @Consumes({ "application/xml", "text/plain", "application/json" }) @Produces({ "application/xml", "text/plain", "application/json" }) Object invoke(@PathParam("id") String id, String payload); } Exchange exchange = template.send("direct://proxy", new Processor() { public void process(Exchange exchange) throws Exception { exchange.setPattern(ExchangePattern.InOut); Message inMessage = exchange.getIn(); // set the operation name inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomer"); // using the proxy client API inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE); // set a customer header inMessage.setHeader("key", "value"); // set up the accepted content type inMessage.setHeader(Exchange.ACCEPT_CONTENT_TYPE, "application/json"); // set the parameters, if you just have one parameter, // camel will put this object into an Object[] itself inMessage.setBody("123"); } }); // get the response message Customer response = (Customer) exchange.getMessage().getBody(); assertNotNull(response, "The response should not be null"); assertEquals(123, response.getId(), "Get a wrong customer id"); assertEquals("John", response.getName(), "Get a wrong customer name"); assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code"); assertEquals("value", exchange.getMessage().getHeader("key"), "Get a wrong header value"); Exchange exchange = template.send("direct://http", new Processor() { public void process(Exchange exchange) throws Exception { exchange.setPattern(ExchangePattern.InOut) Message inMessage = exchange.getIn(); // using the http central client API inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE); // set the Http method inMessage.setHeader(Exchange.HTTP_METHOD, "GET"); // set the relative path inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123"); // Specify the response class, cxfrs will use InputStream as the response object type inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class); // set a customer header inMessage.setHeader("key", "value"); // since we use the Get method, so we don't need to set the message body inMessage.setBody(null); } }); Exchange exchange = template.send("cxfrs://http://localhost:9003/testQuery?httpClientAPI=true&q1=12&q2=13" Map<String, String> queryMap = new LinkedHashMap<>(); queryMap.put("q1", "new"); queryMap.put("q2", "world"); inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_QUERY_MAP, queryMap); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-dataformat-starter</artifactId> </dependency> dataformat:name:(marshal|unmarshal)[?options] dataformat:name:operation from("activemq:My.Queue"). to("dataformat:jaxb:unmarshal?contextPath=com.acme.model"). to("mqseries:Another.Queue"); <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="activemq:My.Queue"/> <to uri="dataformat:jaxb:unmarshal?contextPath=com.acme.model"/> <to uri="mqseries:Another.Queue"/> </route> </camelContext> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-dataset-starter</artifactId> </dependency> dataset:name[?options] dataset:name <bean id="myDataSet" class="com.mycompany.MyDataSet"> <property name="size" value="100"/> </bean> // send the dataset to a queue from("dataset:foo").to("activemq:SomeQueue"); // now lets test that the messages are consumed correctly from("activemq:SomeQueue").to("dataset:foo"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-direct-starter</artifactId> </dependency> direct:someName[?options] direct:name from("activemq:queue:order.in") .to("bean:orderServer?method=validate") .to("direct:processOrder"); from("direct:processOrder") .to("bean:orderService?method=process") .to("activemq:queue:order.out"); <route> <from uri="activemq:queue:order.in"/> <to uri="bean:orderService?method=validate"/> <to uri="direct:processOrder"/> </route> <route> <from uri="direct:processOrder"/> <to uri="bean:orderService?method=process"/> <to uri="activemq:queue:order.out"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-elasticsearch-starter</artifactId> </dependency> elasticsearch://clusterName[?options] elasticsearch:clusterName ElasticsearchComponent elasticsearchComponent = new ElasticsearchComponent(); elasticsearchComponent.setHostAddresses("myelkhost:9200"); camelContext.addComponent("elasticsearch", elasticsearchComponent); ElasticsearchComponent elasticsearchComponent = new ElasticsearchComponent(); elasticsearchComponent.setHostAddresses("myelkhost:9200"); elasticsearchComponent.setUser("elkuser"); elasticsearchComponent.setPassword("secure!!"); elasticsearchComponent.setEnableSSL(true); elasticsearchComponent.setCertificatePath(certPath); camelContext.addComponent("elasticsearch", elasticsearchComponent); from("direct:index") .to("elasticsearch://elasticsearch?operation=Index&indexName=twitter"); <route> <from uri="direct:index"/> <to uri="elasticsearch://elasticsearch?operation=Index&amp;indexName=twitter"/> </route> Map<String, String> map = new HashMap<String, String>(); map.put("content", "test"); String indexId = template.requestBody("direct:index", map, String.class); from("direct:search") .to("elasticsearch://elasticsearch?operation=Search&indexName=twitter"); <route> <from uri="direct:search"/> <to uri="elasticsearch://elasticsearch?operation=Search&amp;indexName=twitter"/> </route> String query = "{\"query\":{\"match\":{\"doc.content\":\"new release of ApacheCamel\"}}}"; HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); Map<String, Object> actualQuery = new HashMap<>(); actualQuery.put("doc.content", "new release of ApacheCamel"); Map<String, Object> match = new HashMap<>(); match.put("match", actualQuery); Map<String, Object> query = new HashMap<>(); query.put("query", match); HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); from("direct:search") .to("elasticsearch://elasticsearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"); <route> <from uri="direct:search"/> <to uri="elasticsearch://elasticsearch?operation=Search&amp;indexName=twitter&amp;useScroll=true&amp;scrollKeepAliveMs=30000"/> </route> String query = "{\"query\":{\"match\":{\"doc.content\":\"new release of ApacheCamel\"}}}"; try (ElasticsearchScrollRequestIterator response = template.requestBody("direct:search", query, ElasticsearchScrollRequestIterator.class)) { // do something smart with results } from("direct:search") .to("elasticsearch://elasticsearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000") .split() .body() .streaming() .to("mock:output") .end(); from("direct:multiSearch") .to("elasticsearch://elasticsearch?operation=MultiSearch"); <route> <from uri="direct:multiSearch"/> <to uri="elasticsearch://elasticsearch?operation=MultiSearch"/> </route> MsearchRequest.Builder builder = new MsearchRequest.Builder().index("twitter").searches( new RequestItem.Builder().header(new MultisearchHeader.Builder().build()) .body(new MultisearchBody.Builder().query(b -> b.matchAll(x -> x)).build()).build(), new RequestItem.Builder().header(new MultisearchHeader.Builder().build()) .body(new MultisearchBody.Builder().query(b -> b.matchAll(x -> x)).build()).build()); List<MultiSearchResponseItem<?>> response = template.requestBody("direct:multiSearch", builder, List.class); <dependency> <groupId>jakarta.json</groupId> <artifactId>jakarta.json-api</artifactId> <version>2.0.2</version> </dependency> spring.elasticsearch.uris=myelkhost:9200 spring.elasticsearch.username=elkuser spring.elasticsearch.password=secure!! spring: autoconfigure: exclude: org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> <route> <from uri="direct:a" /> <recipientList> <exchangeProperty>myProperty</exchangeProperty> </recipientList> </route> from("direct:a").recipientList(exchangeProperty("myProperty")); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-fhir-starter</artifactId> </dependency> fhir://endpoint-prefix/endpoint?[options] fhir:apiName/methodName fhir:apiName/methodName fhir:capabilities/methodName?[parameters] fhir:create/methodName?[parameters] fhir:delete/methodName?[parameters] fhir:history/methodName?[parameters] fhir:load-page/methodName?[parameters] fhir:meta/methodName?[parameters] fhir:operation/methodName?[parameters] fhir:patch/methodName?[parameters] fhir:read/methodName?[parameters] fhir:search/methodName?[parameters] fhir:transaction/methodName?[parameters] fhir:update/methodName?[parameters] fhir:validate/methodName?[parameters] <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-file-starter</artifactId> </dependency> file:directoryName[?options] file:directoryName from("file://inbox?move=.done").to("bean:handleOrder"); move=../backup/copy-of-USD{file:name} from("file://inbox?delete=true").to("bean:handleOrder"); from("file://inbox?preMove=inprogress").to("bean:handleOrder"); from("file://inbox?preMove=inprogress&move=.done").to("bean:handleOrder"); move=backup/USD{date:now:yyyyMMdd}/USD{file:name} from("file:inbox?charset=utf-8") .to("file:outbox?charset=iso-8859-1") from("file:inbox?charset=utf-8") .convertBodyTo(byte[].class, "iso-8859-1") .to("bean:myBean") .to("file:outbox"); from("file:inbox") .convertBodyTo(byte[].class, "iso-8859-1") .to("bean:myBean") .to("file:outbox"); from("file:inbox") .convertBodyTo(byte[].class, "iso-8859-1") .to("bean:myBean") .setProperty(Exchange.CHARSET_NAME, header("someCharsetHeader")) .to("file:outbox"); from("file:inbox?charset=utf-8") .to("file:outbox?charset=iso-8859-1") DEBUG GenericFileConverter - Read file /Users/davsclaus/workspace/camel/camel-core/target/charset/input/input.txt with charset utf-8 DEBUG FileOperations - Using Reader to write file: target/charset/output.txt with charset: iso-8859-1 from("direct:report").to("file:target/reports"); from("direct:report").setHeader(Exchange.FILE_NAME, constant("report.txt")).to( "file:target/reports"); from("direct:report").setHeader("CamelFileName", constant("report.txt")).to( "file:target/reports"); from("direct:report").to("file:target/reports/?fileName=report.txt"); from("file:bar?doneFileName=done"); from("file:bar?doneFileName=USD{file:name}.done"); from("file:bar?doneFileName=ready-USD{file:name}"); .to("file:bar?doneFileName=done"); .to("file:bar?doneFileName=done-USD{file:name}"); .to("file:bar?doneFileName=USD{file:name}.done"); .to("file:bar?doneFileName=USD{file:name.noext}.done"); from("file://inputdir/?delete=true").to("file://outputdir") from("file://inputdir/?delete=true").to("file://outputdir?overruleFile=copy-of-USD{file:name}") from("file://inputdir/?recursive=true&delete=true").to("file://outputdir") inputdir/foo.txt inputdir/sub/bar.txt outputdir/foo.txt outputdir/sub/bar.txt from("file://inputdir/?recursive=true&delete=true").to("file://outputdir?flatten=true") outputdir/foo.txt outputdir/bar.txt from("file://inputdir/?recursive=true&delete=true").to("file://outputdir") inputdir/foo.txt inputdir/sub/bar.txt inputdir/.camel/foo.txt inputdir/sub/.camel/bar.txt outputdir/foo.txt outputdir/sub/bar.txt from("file://inputdir/").process(new Processor() { public void process(Exchange exchange) throws Exception { Object body = exchange.getIn().getBody(); // do some business logic with the input body } }); <route> <from uri="bean:myBean"/> <to uri="file:/rootDirectory"/> </route> Exchange.FILE_NAME = hello.txt => /rootDirectory/hello.txt Exchange.FILE_NAME = foo/bye.txt => /rootDirectory/foo/bye.txt from("direct:start"). to("file:///var/myapp/finalDirectory?tempPrefix=/../filesInProgress/"); from("file://inbox?move=backup/USD{date:now:yyyyMMdd}/USD{file:name}").to("..."); from("file://inbox?idempotent=true").to("..."); <route> <from uri="file://inbox?idempotent=true&amp;idempotentKey=USD{file:name}-USD{file:size}"/> <to uri="bean:processInbox"/> </route> <!-- define our store as a plain spring bean --> <bean id="myStore" class="com.mycompany.MyIdempotentStore"/> <route> <from uri="file://inbox?idempotent=true&amp;idempotentRepository=#myStore"/> <to uri="bean:processInbox"/> </route> DEBUG FileConsumer is idempotent and the file has been consumed before. Will skip this file: target\idempotent\report.txt <persistence-unit name="idempotentDb" transaction-type="RESOURCE_LOCAL"> <class>org.apache.camel.processor.idempotent.jpa.MessageProcessed</class> <properties> <property name="openjpa.ConnectionURL" value="jdbc:derby:target/idempotentTest;create=true"/> <property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.EmbeddedDriver"/> <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/> <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/> <property name="openjpa.Multithreaded" value="true"/> </properties> </persistence-unit> <!-- we define our jpa based idempotent repository we want to use in the file consumer --> <bean id="jpaStore" class="org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository"> <!-- Here we refer to the entityManagerFactory --> <constructor-arg index="0" ref="entityManagerFactory"/> <!-- This 2nd parameter is the name (= a category name). You can have different repositories with different names --> <constructor-arg index="1" value="FileConsumer"/> </bean> <route> <from uri="file://inbox?idempotent=true&amp;idempotentRepository=#jpaStore"/> <to uri="bean:processInbox"/> </route> <!-- define our filter as a plain spring bean --> <bean id="myFilter" class="com.mycompany.MyFileFilter"/> <route> <from uri="file://inbox?filter=#myFilter"/> <to uri="bean:processInbox"/> </route> <!-- define our sorter as a plain spring bean --> <bean id="mySorter" class="com.mycompany.MyFileSorter"/> <route> <from uri="file://inbox?sorter=#mySorter"/> <to uri="bean:processInbox"/> </route> sortBy=group 1;group 2;group 3; sortBy=file:name sortBy=reverse:file:name sortBy=file:length sortBy=ignoreCase:file:name sortBy=reverse:ignoreCase:file:name sortBy=file:modified sortBy=file:modified;file:name sortBy=date:file:yyyyMMdd;file:name sortBy=date:file:yyyyMMdd;reverse:file:name // to handle any IOException being thrown onException(IOException.class) .handled(true) .log("IOException occurred due: USD{exception.message}") .transform().simple("Error USD{exception.message}") .to("mock:error"); // this is the file route that pickup files, notice how we bridge the consumer to use the Camel routing error handler // the exclusiveReadLockStrategy is only configured because this is from an unit test, so we use that to simulate exceptions from("file:target/nospace?bridgeErrorHandler=true") .convertBodyTo(String.class) .to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> fileName="myfile.txt" fileName="backup/USD{date:now:yyyyMMdd}/USD{file:name.noext}.bak" fileName="../backup/USD{date:now:yyyyMMdd}/USD{file:name.noext}.bak" fileName="../backup/USD{date:now:yyyyMMdd}/type-USD{in.header.type}/backup-of-USD{file:name.noext}.bak" fileName="orders/order-USD{in.header.customerId}-USD{date:in.header.orderDate:yyyyMMdd}.xml" fileName="uniquefile-USD{bean:myguidgenerator.generateid}.txt" <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-flink-starter</artifactId> </dependency> flink:dataset?dataset=#myDataSet&dataSetCallback=#dataSetCallback flink:datastream?datastream=#myDataStream&dataStreamCallback=#dataStreamCallback flink:endpointType @Bean public DataSetCallback<Long> dataSetCallback() { return new DataSetCallback<Long>() { public Long onDataSet(DataSet dataSet, Object... objects) { try { dataSet.print(); return new Long(0); } catch (Exception e) { return new Long(-1); } } }; } @Bean public VoidDataStreamCallback dataStreamCallback() { return new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream dataStream, Object... objects) throws Exception { dataStream.flatMap(new Splitter()).print(); environment.execute("data stream test"); } }; } CamelContext camelContext = new SpringCamelContext(context); String pattern = "foo"; try { ProducerTemplate template = camelContext.createProducerTemplate(); camelContext.start(); Long count = template.requestBody("flink:dataSet?dataSet=#myDataSet&dataSetCallback=#countLinesContaining", pattern, Long.class); } finally { camelContext.stop(); } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-ftp-starter</artifactId> </dependency> ftp://[username@]hostname[:port]/directoryname[?options] sftp://[username@]hostname[:port]/directoryname[?options] ftps://[username@]hostname[:port]/directoryname[?options] ftp:host:port/directoryName from("ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000").to("bean:foo"); from("ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000&ftpClientConfig.serverLanguageCode=fr").to("bean:foo"); <bean id="myConfig" class="org.apache.commons.net.ftp.FTPClientConfig"> <property name="lenientFutureDates" value="true"/> <property name="serverLanguageCode" value="fr"/> </bean> from("ftp://foo@myserver?password=secret&ftpClientConfig=#myConfig").to("bean:foo"); ftp://someone@someftpserver.com/public/upload/images/holiday2008?password=secret&binary=true ftp://someoneelse@someotherftpserver.co.uk:12049/reports/2008/password=secret&binary=false ftp://publicftpserver.com/download from("ftp://someone@someserver.com?password=secret&localWorkDirectory=/tmp").to("file://inbox"); / /one /one/two /one/two/sub-a /one/two/sub-b TYPE A 200 Type set to A PWD 257 "/" is current directory. CWD one 250 CWD successful. "/one" is current directory. CWD two 250 CWD successful. "/one/two" is current directory. SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,17,94 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CWD sub-a 250 CWD successful. "/one/two/sub-a" is current directory. PORT 127,0,0,1,17,95 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. "/one/two" is current directory. CWD sub-b 250 CWD successful. "/one/two/sub-b" is current directory. PORT 127,0,0,1,17,96 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. "/one/two" is current directory. CWD / 250 CWD successful. "/" is current directory. PWD 257 "/" is current directory. CWD one 250 CWD successful. "/one" is current directory. CWD two 250 CWD successful. "/one/two" is current directory. PORT 127,0,0,1,17,97 200 Port command successful RETR foo.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. "/" is current directory. PWD 257 "/" is current directory. CWD one 250 CWD successful. "/one" is current directory. CWD two 250 CWD successful. "/one/two" is current directory. CWD sub-a 250 CWD successful. "/one/two/sub-a" is current directory. PORT 127,0,0,1,17,98 200 Port command successful RETR a.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. "/" is current directory. PWD 257 "/" is current directory. CWD one 250 CWD successful. "/one" is current directory. CWD two 250 CWD successful. "/one/two" is current directory. CWD sub-b 250 CWD successful. "/one/two/sub-b" is current directory. PORT 127,0,0,1,17,99 200 Port command successful RETR b.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. "/" is current directory. QUIT 221 Goodbye disconnected. 230 Logged on TYPE A 200 Type set to A SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,4,122 200 Port command successful LIST one/two 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,123 200 Port command successful LIST one/two/sub-a 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,124 200 Port command successful LIST one/two/sub-b 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,125 200 Port command successful RETR one/two/foo.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,126 200 Port command successful RETR one/two/sub-a/a.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,127 200 Port command successful RETR one/two/sub-b/b.txt 150 Opening data channel for file transfer. 226 Transfer OK QUIT 221 Goodbye disconnected. <route> <from uri="ftp://scott@localhost/public/reports?password=tiger&amp;binary=true&amp;delay=60000"/> <to uri="file://target/test-reports"/> </route> from("ftps://admin@localhost:2222/public/camel?password=admin&securityProtocol=SSL&implicit=true &ftpClient.keyStore.file=./src/test/resources/server.jks &ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password") .to("bean:foo"); from("ftps://admin@localhost:2222/public/camel?password=admin&ftpClient.trustStore.file=./src/test/resources/server.jks&ftpClient.trustStore.password=password") .to("bean:foo"); <!-- define our sorter as a plain spring bean --> <bean id="myFilter" class="com.mycompany.MyFileFilter"/> <route> <from uri="ftp://someuser@someftpserver.com?password=secret&amp;filter=#myFilter"/> <to uri="bean:processInbox"/> </route> <!-- define our sorter as a plain spring bean --> <bean id="proxy" class="com.jcraft.jsch.ProxyHTTP"> <constructor-arg value="localhost"/> <constructor-arg value="7777"/> </bean> <route> <from uri="sftp://localhost:9999/root?username=admin&password=admin&proxy=#proxy"/> <to uri="bean:processFile"/> </route> from("sftp://localhost:9999/root?username=admin&password=admin&preferredAuthentications=publickey,password"). to("bean:processFile"); from("ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true") .to("activemq:queue:report"); String data = template.retrieveBodyNoWait("ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true", String.class); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-google-bigquery-starter</artifactId> </dependency> String endpoint = "google-bigquery://project-id:datasetId[:tableId]?serviceAccountKey=/home/user/Downloads/my-key.json"; String endpoint = "google-bigquery://project-id:datasetId[:tableId]?serviceAccountKey=base64:<base64 encoded>"; export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" google-bigquery://project-id:datasetId[:tableId]?[options] google-bigquery:projectId:datasetId:tableId from("direct:start") .header(GoogleBigQueryConstants.TABLE_SUFFIX, "_USD{date:now:yyyyMMdd}") .to("google-bigquery:sampleDataset:sampleTable") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-google-pubsub-starter</artifactId> </dependency> google-pubsub://project-id:destinationName?[options] google-pubsub:projectId:destinationName <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-google-secret-manager-starter</artifactId> </dependency> String endpoint = "google-secret-manager://myCamelFunction?serviceAccountKey=/home/user/Downloads/my-key.json"; export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" google-secret-manager://functionName[?options] `?options=value&option2=value&... ` from("google-secret-manager://myProject?serviceAccountKey=/home/user/Downloads/my-key.json&operation=createSecret") .to("direct:test"); google-secret-manager:project export USDCAMEL_VAULT_GCP_SERVICE_ACCOUNT_KEY=file://path/to/service.accountkey export USDCAMEL_VAULT_GCP_PROJECT_ID=projectId camel.vault.gcp.serviceAccountKey = serviceAccountKey camel.vault.gcp.projectId = projectId export USDCAMEL_VAULT_GCP_USE_DEFAULT_INSTANCE=true export USDCAMEL_VAULT_GCP_PROJECT_ID=projectId camel.vault.gcp.useDefaultInstance = true camel.vault.gcp.projectId = region <camelContext> <route> <from uri="direct:start"/> <to uri="{{gcp:route}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{gcp:route:default}}"/> </route> </camelContext> { "username": "admin", "password": "password123", "engine": "postgres", "host": "127.0.0.1", "port": "3128", "dbname": "db" } <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{gcp:database/username}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{gcp:database/username:admin}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{gcp:route@1}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{gcp:route:default@1}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{gcp:database/username:admin@1}}"/> </route> </camelContext> export USDCAMEL_VAULT_GCP_USE_DEFAULT_INSTANCE=true export USDCAMEL_VAULT_GCP_PROJECT_ID=projectId camel.vault.gcp.useDefaultInstance = true camel.vault.gcp.projectId = projectId camel.vault.gcp.projectId= projectId camel.vault.gcp.refreshEnabled=true camel.vault.gcp.refreshPeriod=60000 camel.vault.gcp.secrets=hello* camel.vault.gcp.subscriptionName=subscriptionName camel.main.context-reload-enabled = true gcloud auth login gcloud projects create <projectId> --name="GCP Secret Manager Refresh" gcloud beta services identity create --service "secretmanager.googleapis.com" --project <project_id> export SM_SERVICE_ACCOUNT="service-...." gcloud pubsub topics create "projects/<project_id>/topics/pubsub-gcp-sec-refresh" gcloud pubsub topics add-iam-policy-binding pubsub-gcp-sec-refresh --member "serviceAccount:USD{SM_SERVICE_ACCOUNT}" --role "roles/pubsub.publisher" --project <project_id> gcloud pubsub subscriptions create "projects/<project_id>/subscriptions/sub-gcp-sec-refresh" --topic "projects/<project_id>/topics/pubsub-gcp-sec-refresh" gcloud iam service-accounts create gcp-sec-refresh-sa --description="GCP Sec Refresh SA" --project <project_id> gcloud projects add-iam-policy-binding <project_id> --member="serviceAccount:gcp-sec-refresh-sa@<project_id>.iam.gserviceaccount.com" --role="roles/owner" gcloud iam service-accounts keys create <project_id>.json --iam-account=gcp-sec-refresh-sa@<project_id>.iam.gserviceaccount.com gcloud services enable secretmanager.googleapis.com --project <project_id> gcloud services enable pubsub.googleapis.com --project <project_id> gcloud secrets create <secret_name> --topics=projects/<project_id>/topics/pubsub-gcp-sec-refresh --project=<project_id> gcloud secrets versions add <secret_name> --data-file=<json_secret> --project=<project_id> from("direct:start") .setHeader("GoogleSecretManagerConstants.SECRET_ID, constant("test")) .setBody(constant("hello")) .to("google-functions://myProject?serviceAccountKey=/home/user/Downloads/my-key.json&operation=createSecret") .log("body:USD{body}") from("direct:start") .setHeader("GoogleSecretManagerConstants.SECRET_ID, constant("test")) .to("google-functions://myProject?serviceAccountKey=/home/user/Downloads/my-key.json&operation=getSecretVersion") .log("body:USD{body}") from("direct:start") .setHeader("GoogleSecretManagerConstants.SECRET_ID, constant("test")) .to("google-functions://myProject?serviceAccountKey=/home/user/Downloads/my-key.json&operation=deleteSecret") from("direct:start") .setHeader("GoogleSecretManagerConstants.SECRET_ID, constant("test")) .to("google-functions://myProject?serviceAccountKey=/home/user/Downloads/my-key.json&operation=listSecrets") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-groovy-starter</artifactId> </dependency> groovy("someGroovyExpression") from("queue:foo") .filter(groovy("request.lineItems.any { i -> i.value > 100 }")) .to("queue:bar") <route> <from uri="queue:foo"/> <filter> <groovy>request.lineItems.any { i -> i.value > 100 }</groovy> <to uri="queue:bar"/> </filter> </route> bar = "baz"; some other statements camel take the result value as the script evaluation result result = body * 2 + 1 public class CustomGroovyShellFactory implements GroovyShellFactory { public GroovyShell createGroovyShell(Exchange exchange) { ImportCustomizer importCustomizer = new ImportCustomizer(); importCustomizer.addStaticStars("com.example.Utils"); CompilerConfiguration configuration = new CompilerConfiguration(); configuration.addCompilationCustomizers(importCustomizer); return new GroovyShell(configuration); } } `"resource:scheme:location"`, .setHeader("myHeader").groovy("resource:classpath:mygroovy.groovy") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-grpc-starter</artifactId> </dependency> grpc:host:port/service[?options] grpc:host:port/service from("direct:grpc-sync") .to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=sendPing&synchronous=true"); <route> <from uri="direct:grpc-sync" /> <to uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=sendPing&synchronous=true"/> </route> from("direct:grpc-async") .to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=pingAsyncResponse"); from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?consumerStrategy=PROPAGATION") .to("direct:grpc-service"); from("direct:grpc-request-stream") .to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=PingAsyncAsync&producerStrategy=STREAMING&streamRepliesTo=direct:grpc-response-stream"); from("direct:grpc-response-stream") .log("Response received: USD{body}"); from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?consumerStrategy=PROPAGATION&negotiationType=TLS&keyCertChainResource=file:src/test/resources/certs/server.pem&keyResource=file:src/test/resources/certs/server.key&trustCertCollectionResource=file:src/test/resources/certs/ca.pem") .to("direct:tls-enable") from("direct:grpc-jwt") .to("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?method=pingSyncSync&synchronous=true&authenticationType=JWT&jwtSecret=supersecuredsecret"); <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.7.1</version> </extension> </extensions> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.6.1</version> <configuration> <protocArtifact>com.google.protobuf:protoc:USD{protobuf-version}:exe:USD{os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:USD{grpc-version}:exe:USD{os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> <goal>test-compile</goal> <goal>test-compile-custom</goal> </goals> </execution> </executions> </plugin> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> <route> <from uri="direct:a" /> <recipientList> <header>myHeader</header> </recipientList> </route> from("direct:a").recipientList(header("myHeader")); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-hl7-starter</artifactId> </dependency> <endpoint id="hl7MinaListener" uri="mina:tcp://localhost:8888?sync=true&amp;codec=#hl7codec"/> <bean id="hl7codec" class="org.apache.camel.component.hl7.HL7MLLPCodec"> <property name="charset" value="iso-8859-1"/> </bean> from("hl7MinaListener") .bean("patientLookupService"); <bean id="patientLookupService" class="com.mycompany.healthcare.service.PatientLookupService"/> import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.model.v24.segment.QRD; public class PatientLookupService { public Message lookupPatient(Message input) throws HL7Exception { QRD qrd = (QRD)input.get("QRD"); String patientId = qrd.getWhoSubjectFilter(0).getIDNumber().getValue(); // find patient data based on the patient id and create a HL7 model object with the response Message response = ... create and set response data return response } <endpoint id="hl7NettyListener" uri="netty:tcp://localhost:8888?sync=true&amp;encoders=#hl7encoder&amp;decoders=#hl7decoder"/> <bean id="hl7decoder" class="org.apache.camel.component.hl7.HL7MLLPNettyDecoderFactory"/> <bean id="hl7encoder" class="org.apache.camel.component.hl7.HL7MLLPNettyEncoderFactory"/> from("hl7NettyListener") .bean("patientLookupService"); MSH|^~\\&|MYSENDER|MYRECEIVER|MYAPPLICATION||200612211200||QRY^A19|1234|P|2.4 QRD|200612211200|R|I|GetPatient|||1^RD|0101701234|DEM|| Message msg = exchange.getIn().getBody(Message.class); QRD qrd = (QRD)msg.get("QRD"); String patientId = qrd.getWhoSubjectFilter(0).getIDNumber().getValue(); // 0101701234 QRY_A19 msg = exchange.getIn().getBody(QRY_A19.class); String patientId = msg.getQRD().getWhoSubjectFilter(0).getIDNumber().getValue(); DataFormat hl7 = new HL7DataFormat(); from("direct:hl7in") .marshal(hl7) .to("jms:queue:hl7out"); DataFormat hl7 = new HL7DataFormat(); from("jms:queue:hl7out") .unmarshal(hl7) .to("patientLookupService"); from("direct:hl7in") .marshal().hl7() .to("jms:queue:hl7out"); from("jms:queue:hl7out") .unmarshal().hl7() .to("patientLookupService"); <dependency> <groupId>ca.uhn.hapi</groupId> <artifactId>hapi-structures-v24</artifactId> <version>2.2</version> <!-- use the same version as your hapi-base version --> </dependency> <dependency> <groupId>ca.uhn.hapi</groupId> <artifactId>hapi-structures-v25</artifactId> <version>2.2</version> <!-- use the same version as your hapi-base version --> </dependency> <dependency> <groupId>ca.uhn.hapi</groupId> <artifactId>hapi-osgi-base</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-http-starter</artifactId> </dependency> http:hostname[:port][/resourceUri][?options] http://httpUri HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class); HttpServletResponse response = exchange.getIn().getBody(HttpServletResponse.class); from("direct:start") .to("http://oldhost"); <camelContext xmlns="http://activemq.apache.org/camel/schema/spring"> <route> <from uri="direct:start"/> <to uri="http://oldhost"/> </route> </camelContext> from("direct:start") .setHeader(Exchange.HTTP_URI, constant("http://newhost")) .to("http://oldhost"); from("direct:start") .to("http://oldhost?order=123&detail=short"); from("direct:start") .setHeader(Exchange.HTTP_QUERY, constant("order=123&detail=short")) .to("http://oldhost"); from("direct:start") .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http.HttpMethods.POST)) .to("http://www.google.com") .to("mock:results"); .setHeader("CamelHttpMethod", constant("POST")) <camelContext xmlns="http://activemq.apache.org/camel/schema/spring"> <route> <from uri="direct:start"/> <setHeader name="CamelHttpMethod"> <constant>POST</constant> </setHeader> <to uri="http://www.google.com"/> <to uri="mock:results"/> </route> </camelContext> from("direct:start") .to("http://oldhost?proxyAuthHost=www.myproxy.com&proxyAuthPort=80"); context.getGlobalOptions().put("http.proxyHost", "172.168.18.9"); context.getGlobalOptions().put("http.proxyPort", "8080"); <camelContext> <properties> <property key="http.proxyHost" value="172.168.18.9"/> <property key="http.proxyPort" value="8080"/> </properties> </camelContext> exchange.setProperty(Exchange.CHARSET_NAME, "ISO-8859-1"); from("timer://foo?fixedRate=true&delay=0&period=10000") .to("http://www.google.com") .setHeader(FileComponent.HEADER_FILE_NAME, "message.html") .to("file:target/google"); // we query for Camel at the Google page template.sendBody("http://www.google.com/search?q=Camel", null); Map headers = new HashMap(); headers.put(Exchange.HTTP_QUERY, "q=Camel&lr=lang_en"); // we query for Camel and English language at Google template.sendBody("http://www.google.com/search", null, headers); Exchange exchange = template.send("http://www.google.com/search", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(Exchange.HTTP_QUERY, constant("hl=en&q=activemq")); } }); Message out = exchange.getOut(); int responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class); httpClient.cookieSpec=ignore KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("file:/users/home/server/keystore.jks"); ksp.setPassword("keystorePassword"); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword("keyPassword"); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); HttpComponent httpComponent = getContext().getComponent("https", HttpComponent.class); httpComponent.setSslContextParameters(scp); <camel:sslContextParameters id="sslContextParameters"> <camel:keyManagers keyPassword="keyPassword"> <camel:keyStore resource="file:/users/home/server/keystore.jks" password="keystorePassword"/> </camel:keyManagers> </camel:sslContextParameters> <to uri="https://127.0.0.1/mail/?sslContextParameters=#sslContextParameters"/> KeyStore keystore = ...; KeyStore truststore = ...; SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, new SSLSocketFactory(keystore, "mypassword", truststore))); HttpComponent httpComponent = getContext().getComponent("http", HttpComponent.class); httpComponent.setHttpClientConfigurer(new MyHttpClientConfigurer()); <bean id="myHttpClientConfigurer" class="my.https.HttpClientConfigurer"> </bean> <to uri="https://myhostname.com:443/myURL?httpClientConfigurer=myHttpClientConfigurer"/> public class HttpContextFactory { private String httpHost = "localhost"; private String httpPort = 9001; private BasicHttpContext httpContext = new BasicHttpContext(); private BasicAuthCache authCache = new BasicAuthCache(); private BasicScheme basicAuth = new BasicScheme(); public HttpContext getObject() { authCache.put(new HttpHost(httpHost, httpPort), basicAuth); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); return httpContext; } // getter and setter } <bean id="myHttpContext" factory-bean="httpContextFactory" factory-method="getObject"/> <to uri="https://myhostname.com:443/myURL?httpContext=myHttpContext"/> <bean id="http-foo" class="org.apache.camel.component.http.HttpComponent"> <property name="sslContextParameters" ref="sslContextParams1"/> <property name="x509HostnameVerifier" ref="hostnameVerifier"/> </bean> <bean id="http-bar" class="org.apache.camel.component.http.HttpComponent"> <property name="sslContextParameters" ref="sslContextParams2"/> <property name="x509HostnameVerifier" ref="hostnameVerifier"/> </bean> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-hashicorp-vault-starter</artifactId> </dependency> hashicorp-vault:secretsEngine export USDCAMEL_VAULT_HASHICORP_TOKEN=token export USDCAMEL_VAULT_HASHICORP_HOST=host export USDCAMEL_VAULT_HASHICORP_PORT=port export USDCAMEL_VAULT_HASHICORP_SCHEME=http/https camel.vault.hashicorp.token = token camel.vault.hashicorp.host = host camel.vault.hashicorp.port = port camel.vault.hashicorp.scheme = scheme <camelContext> <route> <from uri="direct:start"/> <to uri="{{hashicorp:secret:route}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{hashicorp:secret:route:default}}"/> </route> </camelContext> { "username": "admin", "password": "password123", "engine": "postgres", "host": "127.0.0.1", "port": "3128", "dbname": "db" } <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{hashicorp:secret:database/username}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{hashicorp:secret:database/username:admin}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{hashicorp:secret:route@2}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <to uri="{{hashicorp:route:default@2}}"/> </route> </camelContext> <camelContext> <route> <from uri="direct:start"/> <log message="Username is {{hashicorp:secret:database/username:admin@2}}"/> </route> </camelContext> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-infinispan-starter</artifactId> </dependency> infinispan://cacheName?[options] infinispan:cacheName from("direct:start") .setHeader(InfinispanConstants.OPERATION).constant(InfinispanOperation.PUT) (1) .setHeader(InfinispanConstants.KEY).constant("123") (2) .to("infinispan:myCacheName&cacheContainer=#cacheContainer"); (3) from("direct:start") .setHeader(InfinispanConstants.OPERATION).constant(InfinispanOperation.GET) .setHeader(InfinispanConstants.KEY).constant("123") .setHeader(InfinispanConstants.LIFESPAN_TIME).constant(100L) (1) .setHeader(InfinispanConstants.LIFESPAN_TIME_UNIT.constant(TimeUnit.MILLISECONDS.toString()) (2) .to("infinispan:myCacheName"); from("direct:start") .setHeader(InfinispanConstants.OPERATION, InfinispanConstants.QUERY) .setHeader(InfinispanConstants.QUERY_BUILDER, new InfinispanQueryBuilder() { @Override public Query build(QueryFactory<Query> qf) { return qf.from(User.class).having("name").like("%abc%").build(); } }) .to("infinispan:myCacheName?cacheContainer=#cacheManager") ; from("infinispan://?cacheContainer=#cacheManager&customListener=#myCustomListener") .to("mock:result"); InfinispanRemoteConfiguration conf = new InfinispanRemoteConfiguration(); (1) conf.setHosts("localhost:1122") InfinispanRemoteIdempotentRepository repo = new InfinispanRemoteIdempotentRepository("idempotent"); (2) repo.setConfiguration(conf); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start") .idempotentConsumer(header("MessageID"), repo) (3) .to("mock:result"); } }); <bean id="infinispanRepo" class="org.apache.camel.component.infinispan.remote.InfinispanRemoteIdempotentRepository" destroy-method="stop"> <constructor-arg value="idempotent"/> (1) <property name="configuration"> (2) <bean class="org.apache.camel.component.infinispan.remote.InfinispanRemoteConfiguration"> <property name="hosts" value="localhost:11222"/> </bean> </property> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start" /> <idempotentConsumer messageIdRepositoryRef="infinispanRepo"> (3) <header>MessageID</header> <to uri="mock:result" /> </idempotentConsumer> </route> </camelContext> InfinispanRemoteConfiguration conf = new InfinispanRemoteConfiguration(); (1) conf.setHosts("localhost:1122") InfinispanRemoteAggregationRepository repo = new InfinispanRemoteAggregationRepository(); (2) repo.setCacheName("aggregation"); repo.setConfiguration(conf); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start") .aggregate(header("MessageID")) .completionSize(3) .aggregationRepository(repo) (3) .aggregationStrategyRef("myStrategy") .to("mock:result"); } }); <bean id="infinispanRepo" class="org.apache.camel.component.infinispan.remote.InfinispanRemoteAggregationRepository" destroy-method="stop"> <constructor-arg value="aggregation"/> (1) <property name="configuration"> (2) <bean class="org.apache.camel.component.infinispan.remote.InfinispanRemoteConfiguration"> <property name="hosts" value="localhost:11222"/> </bean> </property> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start" /> <aggregate strategyRef="myStrategy" completionSize="3" aggregationRepositoryRef="infinispanRepo"> (3) <correlationExpression> <header>MessageID</header> </correlationExpression> <to uri="mock:result"/> </aggregate> </route> </camelContext> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-infinispan-embedded-starter</artifactId> <version>x.x.x</version> <!-- use the same version as your Camel core version --> </dependency> infinispan-embedded://cacheName?[options] infinispan-embedded:cacheName from("direct:start") .setHeader(InfinispanConstants.OPERATION).constant(InfinispanOperation.PUT) (1) .setHeader(InfinispanConstants.KEY).constant("123") (2) .to("infinispan:myCacheName&cacheContainer=#cacheContainer"); (3) from("direct:start") .setHeader(InfinispanConstants.OPERATION).constant(InfinispanOperation.GET) .setHeader(InfinispanConstants.KEY).constant("123") .setHeader(InfinispanConstants.LIFESPAN_TIME).constant(100L) (1) .setHeader(InfinispanConstants.LIFESPAN_TIME_UNIT.constant(TimeUnit.MILLISECONDS.toString()) (2) .to("infinispan:myCacheName"); from("direct:start") .setHeader(InfinispanConstants.OPERATION, InfinispanConstants.QUERY) .setHeader(InfinispanConstants.QUERY_BUILDER, new InfinispanQueryBuilder() { @Override public Query build(QueryFactory<Query> qf) { return qf.from(User.class).having("name").like("%abc%").build(); } }) .to("infinispan:myCacheName?cacheContainer=#cacheManager") ; from("infinispan://?cacheContainer=#cacheManager&customListener=#myCustomListener") .to("mock:result"); InfinispanEmbeddedConfiguration conf = new InfinispanEmbeddedConfiguration(); (1) conf.setConfigurationUri("classpath:infinispan.xml") InfinispanEmbeddedIdempotentRepository repo = new InfinispanEmbeddedIdempotentRepository("idempotent"); (2) repo.setConfiguration(conf); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start") .idempotentConsumer(header("MessageID"), repo) (3) .to("mock:result"); } }); <bean id="infinispanRepo" class="org.apache.camel.component.infinispan.embedded.InfinispanEmbeddedIdempotentRepository" destroy-method="stop"> <constructor-arg value="idempotent"/> (1) <property name="configuration"> (2) <bean class="org.apache.camel.component.infinispan.embedded.InfinispanEmbeddedConfiguration"> <property name="configurationUrl" value="classpath:infinispan.xml"/> </bean> </property> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start" /> <idempotentConsumer idempotentRepository="infinispanRepo"> (3) <header>MessageID</header> <to uri="mock:result" /> </idempotentConsumer> </route> </camelContext> InfinispanEmbeddedConfiguration conf = new InfinispanEmbeddedConfiguration(); (1) conf.setConfigurationUri("classpath:infinispan.xml") InfinispanEmbeddedAggregationRepository repo = new InfinispanEmbeddedAggregationRepository("aggregation"); (2) repo.setConfiguration(conf); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start") .aggregate(header("MessageID")) .completionSize(3) .aggregationRepository(repo) (3) .aggregationStrategy("myStrategy") .to("mock:result"); } }); <bean id="infinispanRepo" class="org.apache.camel.component.infinispan.embedded.InfinispanEmbeddedAggregationRepository" destroy-method="stop"> <constructor-arg value="aggregation"/> (1) <property name="configuration"> (2) <bean class="org.apache.camel.component.infinispan.embedded.InfinispanEmbeddedConfiguration"> <property name="configurationUrl" value="classpath:infinispan.xml"/> </bean> </property> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start" /> <aggregate aggregationStrategy="myStrategy" completionSize="3" aggregationRepository="infinispanRepo"> (3) <correlationExpression> <header>MessageID</header> </correlationExpression> <to uri="mock:result"/> </aggregate> </route> </camelContext> from("activemq:My.Queue"). unmarshal().jacksonxml(). to("mqseries:Another.Queue"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jacksonxml-starter</artifactId> </dependency> <dataFormats> <!-- here we define a Xml data format with the id jack and that it should use the TestPojo as the class type when doing unmarshal. The unmarshalType is optional, if not provided Camel will use a Map as the type --> <jacksonxml id="jack" unmarshalType="org.apache.camel.component.jacksonxml.TestPojo"/> </dataFormats> <route> <from uri="direct:back"/> <unmarshal><custom ref="jack"/></unmarshal> <to uri="mock:reverse"/> </route> <pojo age="30" weight="70"/> JacksonXMLDataFormat ageViewFormat = new JacksonXMLDataFormat(TestPojoView.class, Views.Age.class); from("direct:inPojoAgeView"). marshal(ageViewFormat); from("direct:inPojoAgeView"). marshal().jacksonxml(TestPojoView.class, Views.Age.class); <from uri="direct:inPojoAgeView"/> <marshal> <jacksonxml unmarshalType="org.apache.camel.component.jacksonxml.TestPojoView" jsonView="org.apache.camel.component.jacksonxml.ViewsUSDAge"/> </marshal> @JsonInclude(Include.NON_NULL) public class MyPojo { } JacksonXMLDataFormat format = new JacksonXMLDataFormat(); format.setInclude("NON_NULL"); <dataFormats> <jacksonxml id="jacksonxml" include="NON_NULL"/> </dataFormats> For JMS end users there is the JMSType header from the JMS spec that indicates that also. To enable support for JMSType you would need to turn that on, on the jackson data format as shown: JacksonDataFormat format = new JacksonDataFormat(); format.setAllowJmsType(true); <dataFormats> <jacksonxml id="jacksonxml" allowJmsType="true"/> </dataFormats> JacksonXMLDataFormat format = new ListJacksonXMLDataFormat(); // or JacksonXMLDataFormat format = new JacksonXMLDataFormat(); format.useList(); // and you can specify the pojo class type also format.setUnmarshalType(MyPojo.class); <dataFormats> <jacksonxml id="jack" useList="true"/> </dataFormats> <dataFormats> <jacksonxml id="jack" useList="true" unmarshalType="com.foo.MyPojo"/> </dataFormats> <dataFormats> <jacksonxml id="jack" useList="true" unmarshalType="com.foo.MyPojo" moduleClassNames="com.foo.MyModule,com.foo.MyOtherModule"/> </dataFormats> <bean id="myJacksonModule" class="com.foo.MyModule"> ... // configure the module as you want </bean> <dataFormats> <jacksonxml id="jacksonxml" useList="true" unmarshalType="com.foo.MyPojo" moduleRefs="myJacksonModule"/> </dataFormats> Multiple modules can be specified separated by comma, such as moduleRefs="myJacksonModule,myOtherModule" <dataFormats> <jacksonxml id="jacksonxml" unmarshalType="com.foo.MyPojo" disableFeatures="FAIL_ON_UNKNOWN_PROPERTIES"/> </dataFormats> JacksonDataFormat df = new JacksonDataFormat(MyPojo.class); df.disableFeature(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); df.disableFeature(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES); Map<String, Object> invoiceData = new HashMap<String, Object>(); invoiceData.put("netValue", 500); producerTemplate.sendBody("direct:mapToInvoice", invoiceData); // Later in the processor Invoice invoice = exchange.getIn().getBody(Invoice.class); <dataFormats> <jacksonxml id="jack" prettyPrint="true"/> </dataFormats> from("direct:inPretty").marshal().jacksonxml(true); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jaxb-starter</artifactId> </dependency> DataFormat jaxb = new JaxbDataFormat("com.acme.model"); from("activemq:My.Queue"). unmarshal(jaxb). to("mqseries:Another.Queue"); from("activemq:My.Queue"). unmarshal("myJaxbDataType"). to("mqseries:Another.Queue"); <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <bean id="myJaxb" class="org.apache.camel.converter.jaxb.JaxbDataFormat"> <property name="contextPath" value="org.apache.camel.example"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start"/> <marshal><custom ref="myJaxb"/></marshal> <to uri="direct:marshalled"/> </route> <route> <from uri="direct:marshalled"/> <unmarshal><custom ref="myJaxb"/></unmarshal> <to uri="mock:result"/> </route> </camelContext> </beans> .setHeader(JaxbConstants.JAXB_PART_NAMESPACE, constant("{http://www.camel.apache.org/jaxb/example/address/1}address")); JaxbDataFormat customWriterFormat = new JaxbDataFormat("org.apache.camel.foo.bar"); customWriterFormat.setXmlStreamWriterWrapper(new TestXmlStreamWriter()); <bean id="testXmlStreamWriterWrapper" class="org.apache.camel.jaxb.TestXmlStreamWriter"/> <jaxb filterNonXmlChars="true" contextPath="org.apache.camel.foo.bar" xmlStreamWriterWrapper="#testXmlStreamWriterWrapper" /> <util:map id="myMap"> <entry key="http://www.w3.org/2003/05/soap-envelope" value="soap"/> <!-- we don't want any prefix for our namespace --> <entry key="http://www.mycompany.com/foo/2" value=""/> </util:map> <marshal> <soap version="1.2" contextPath="com.mycompany.foo" namespacePrefixRef="myMap"/> </marshal> JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(); jaxbDataFormat.setContextPath(Person.class.getPackage().getName()); jaxbDataFormat.setSchema("classpath:person.xsd,classpath:address.xsd"); jaxbDataFormat.setAccessExternalSchemaProtocols("file"); <marshal> <jaxb id="jaxb" schema="classpath:person.xsd,classpath:address.xsd" accessExternalSchemaProtocols="file"/> </marshal> JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(); jaxbDataFormat.setContextPath(Person.class.getPackage().getName()); jaxbDataFormat.setSchemaLocation("schema/person.xsd"); <marshal> <jaxb id="jaxb" schemaLocation="schema/person.xsd"/> </marshal> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jasypt-starter</artifactId> </dependency> Apache Camel Jasypt takes the following options -h or -help = Displays the help screen -c or -command <command> = Command either encrypt or decrypt -p or -password <password> = Password to use -i or -input <input> = Text to encrypt or decrypt -a or -algorithm <algorithm> = Optional algorithm to use -rsga or -algorithm <algorithm> = Optional random salt generator algorithm to use -riga or -algorithm <algorithm> = Optional random iv generator algorithm to use jbang org.apache.camel:camel-jasypt:<camel version here> -c encrypt -p secret -i tiger Encrypted text: qaEEacuW7BUti8LcMgyjKw== jbang org.apache.camel:camel-jasypt:<camel version here> -c decrypt -p secret -i qaEEacuW7BUti8LcMgyjKw== Decrypted text: tiger Encrypted value for 'tiger' my.secret = ENC(qaEEacuW7BUti8LcMgyjKw==) export CAMEL_ENCRYPTION_PASSWORD=secret unset CAMEL_ENCRYPTION_PASSWORD password=sysenv:CAMEL_ENCRYPTION_PASSWORD jasyptPropertiesParser.setPassword("sysenv:CAMEL_ENCRYPTION_PASSWORD"); // create the jasypt properties parser JasyptPropertiesParser jasypt = new JasyptPropertiesParser(); // set the master password (see above for how to do this in a secure way) jasypt.setPassword("secret"); // create the properties' component PropertiesComponent pc = new PropertiesComponent(); pc.setLocation("classpath:org/apache/camel/component/jasypt/secret.properties"); // and use the jasypt properties parser, so we can decrypt values pc.setPropertiesParser(jasypt); // end enable nested placeholder support pc.setNestedPlaceholder(true); // add properties component to camel context context.setPropertiesComponent(pc); JasyptPropertiesParser jasyptPropertiesParser = new JasyptPropertiesParser(); jasyptPropertiesParser.setAlgorithm("PBEWithHmacSHA256AndAES_256"); jasyptPropertiesParser.setRandomSaltGeneratorAlgorithm("PKCS11"); jasyptPropertiesParser.setRandomIvGeneratorAlgorithm("PKCS11"); my.secret.password=ENC(bsW9uV37gQ0QHFu7KO03Ww==) <!-- define the jasypt properties parser with the given password to be used --> <bean id="jasypt" class="org.apache.camel.component.jasypt.JasyptPropertiesParser"> <property name="password" value="secret"/> </bean> <!-- define the camel properties component --> <bean id="properties" class="org.apache.camel.component.properties.PropertiesComponent"> <!-- the properties file is in the classpath --> <property name="location" value="classpath:org/apache/camel/component/jasypt/secret.properties"/> <!-- and let it leverage the jasypt parser --> <property name="propertiesParser" ref="jasypt"/> <!-- end enable nested placeholder --> <property name="nestedPlaceholder" value="true"/> </bean> <!-- define the jasypt properties parser with the given password to be used --> <bean id="jasypt" class="org.apache.camel.component.jasypt.JasyptPropertiesParser"> <!-- password is mandatory, you can prefix it with sysenv: or sys: to indicate it should use an OS environment or JVM system property value, so you dont have the master password defined here --> <property name="password" value="secret"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring"> <!-- define the camel properties placeholder, and let it leverage jasypt --> <propertyPlaceholder id="properties" location="classpath:org/apache/camel/component/jasypt/myproperties.properties" nestedPlaceholder="true" propertiesParserRef="jasypt"/> <route> <from uri="direct:start"/> <to uri="{{cool.result}}"/> </route> </camelContext> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jdbc-starter</artifactId> </dependency> jdbc:dataSourceName[?options] jdbc:dataSourceName from("direct:projects") .setHeader(":?lic", constant("ASF")) .setHeader(":?min", constant(123)) .setBody(simple("select * from projects where license = :?lic and id > :?min order by id")) .to("jdbc:myDataSource?useHeadersAsParameters=true") EmbeddedDatabase db = new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.DERBY).addScript("sql/init.sql").build(); CamelContext context = context.getRegistry().bind("testdb", db); from("direct:hello") .to("jdbc:testdb"); Endpoint endpoint = context.getEndpoint("direct:hello"); Exchange exchange = endpoint.createExchange(); // then we set the SQL on the in body exchange.getMessage().setBody("select * from customer order by ID"); // now we send the exchange to the endpoint, and receives the response from Camel Exchange out = template.send(endpoint, exchange); from("direct:hello") // here we split the data from the testdb into new messages one by one // so the mock endpoint will receive a message per row in the table // the StreamList option allows to stream the result of the query without creating a List of rows // and notice we also enable streaming mode on the splitter .to("jdbc:testdb?outputType=StreamList") .split(body()).streaming() .to("mock:result"); from("timer://foo?period=60000") .setBody(constant("select * from customer")) .to("jdbc:testdb") .to("activemq:queue:customers"); from("timer://MoveNewCustomersEveryHour?period=3600000") .setBody(constant("select * from customer where create_time > (sysdate-1/24)")) .to("jdbc:testdb") .split(body()) .process(new MyCustomerProcessor()) //filter/transform results as needed .setBody(simple("insert into processed_customer values('USD{body[ID]}','USD{body[NAME]}')")) .to("jdbc:testdb"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jira-starter</artifactId> </dependency> jira://type[?options] jira:type jira://[type]?[required options]&jql=project=[project key] jira://[type]?[required options]&jql=RAW(project=[project key] AND status in (Open, \"Coding In Progress\") AND \"Number of comments\">0)" <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jms-starter</artifactId> </dependency> jms:[queue:|topic:]destinationName[?options] jms:FOO.BAR jms:queue:FOO.BAR jms:topic:Stocks.Prices jms:destinationType:destinationName from("jms:queue:foo"). to("bean:myBusinessLogic"); from("jms:topic:OrdersTopic"). filter().method("myBean", "isGoldCustomer"). to("jms:queue:BigSpendersQueue"); from("file://orders"). convertBodyTo(String.class). to("jms:topic:OrdersTopic"); <route> <from uri="jms:topic:OrdersTopic"/> <filter> <method ref="myBean" method="isGoldCustomer"/> <to uri="jms:queue:BigSpendersQueue"/> </filter> </route> // setup error handler to use JMS as queue and store the entire Exchange errorHandler(deadLetterChannel("jms:queue:dead?transferExchange=true")); from("jms:queue:dead").to("bean:myErrorAnalyzer"); // and in our bean String body = exchange.getIn().getBody(); Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); // the cause message is String problem = cause.getMessage(); // we sent it to a seda dead queue first errorHandler(deadLetterChannel("seda:dead")); // and on the seda dead queue we can do the custom transformation before its sent to the JMS queue from("seda:dead").transform(exceptionMessage()).to("jms:queue:dead"); from("file://inbox/order").to("jms:queue:order?messageConverter=#myMessageConverter"); from("file://inbox/order").to("jms:queue:order?jmsMessageType=Text"); from("file://inbox/order").setHeader("CamelJmsMessageType", JmsMessageType.Text).to("jms:queue:order"); 2008-07-09 06:43:04,046 [main ] DEBUG JmsBinding - Ignoring non primitive header: order of class: org.apache.camel.component.jms.issues.DummyOrder with value: DummyOrder{orderId=333, itemId=4444, quantity=2} from("activemq:queue:in") .to("bean:validateOrder") .to(ExchangePattern.InOnly, "activemq:topic:order") .to("bean:handleOrder"); from("file://inbox") .to("bean:computeDestination") .to("activemq:queue:dummy"); public void setJmsHeader(Exchange exchange) { String id = . exchange.getIn().setHeader("CamelJmsDestinationName", "order:" + id"); } <bean id="weblogic" class="org.apache.camel.component.jms.JmsComponent"> <property name="connectionFactory" ref="myConnectionFactory"/> </bean> <jee:jndi-lookup id="myConnectionFactory" jndi-name="jms/connectionFactory"/> from("jms:SomeQueue?concurrentConsumers=20"). bean(MyClass.class); from("jms:SomeQueue?concurrentConsumers=20&asyncConsumer=true"). bean(MyClass.class); from(xxx) .inOut().to("activemq:queue:foo?replyToConcurrentConsumers=5") .to(yyy) .to(zzz); from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar") .to(yyy) from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar&receiveTimeout=250") .to(yyy) from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar&replyToType=Exclusive") .to(yyy) from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar&replyToType=Exclusive") .to(yyy) from(aaa) .inOut().to("activemq:queue:order?replyTo=order.reply&replyToType=Exclusive") .to(bbb) from("direct:someWhere") .to("jms:queue:foo?replyTo=bar&requestTimeout=30s") .to("bean:processReply"); from("direct:someWhere") .setHeader("CamelJmsRequestTimeout", method(ServiceBean.class, "whatIsTheTimeout")) .to("jms:queue:foo?replyTo=bar&requestTimeout=30s") .to("bean:processReply"); Destination replyDestination = exchange.getIn().getHeader(JmsConstants.JMS_REPLY_DESTINATION, Destination.class); // we need to pass in the JMS component, and in this sample we use ActiveMQ JmsEndpoint endpoint = JmsEndpoint.newInstance(replyDestination, activeMQComponent); // now we have the endpoint we can use regular Camel API to send a message to it template.sendBody(endpoint, "Here is the late reply."); // we pretend to send it to some non existing dummy queue template.send("activemq:queue:dummy, new Processor() { public void process(Exchange exchange) throws Exception { // and here we override the destination with the ReplyTo destination object so the message is sent to there instead of dummy exchange.getIn().setHeader(JmsConstants.JMS_DESTINATION, replyDestination); exchange.getIn().setBody("Here is the late reply."); } } template.send("activemq:queue:foo?preserveMessageQos=true", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("World"); exchange.getIn().setHeader("JMSReplyTo", "bar"); } }); // .setHeader("CamelJmsDestinationName", constant("queue:///MY_QUEUE?targetClient=1")) .to("wmq:queue:MY_QUEUE?useMessageIDAsCorrelationID=true"); com.ibm.msg.client.jms.DetailedJMSException: JMSCC0005: The specified value 'MY_QUEUE?targetClient=1' is not allowed for 'XMSC_DESTINATION_NAME' JmsComponent wmq = new JmsComponent(connectionFactory); wmq.setDestinationResolver(new DestinationResolver() { public Destination resolveDestinationName(Session session, String destinationName, boolean pubSubDomain) throws JMSException { MQQueueSession wmqSession = (MQQueueSession) session; return wmqSession.createQueue("queue:///" + destinationName + "?targetClient=1"); } }); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jolokia-starter</artifactId> </dependency> public class MyRestrictor extends CamelRestrictor { //getDefaultDomains() contains default domains, if you want to add some domain to the existing list @Override protected List<String> getAllowedDomains() { final List<String> newDomains = new ArrayList<>(getDefaultDomains()); newDomains.add("my.domain"); return newDomains; } } @Bean("camelConfigHolder") public SpringJolokiaConfigHolder myConfigHolder() { final SpringJolokiaConfigHolder myConfig = new SpringJolokiaConfigHolder(); myConfig.setConfig(Map.of("threadNr", "5", "executor", "fixed")); return myConfig; } @Bean @ConditionalOnMissingBean(name = "camelLogHandlerHolder") public SpringJolokiaLogHandlerHolder myLogHandlerHolder() { final SpringJolokiaLogHandlerHolder stdoutHandlerHolder = new SpringJolokiaLogHandlerHolder(); stdoutHandlerHolder.setType("stdout"); return stdoutHandlerHolder; } logging.level.org.apache.camel.component.jolokia = TRACE logging.level.org.jolokia = TRACE <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jpa-starter</artifactId> </dependency> jpa:entityClassName[?options] jpa:entityType <bean id="jpa" class="org.apache.camel.component.jpa.JpaComponent"> <property name="entityManagerFactory" ref="myEMFactory"/> </bean> <bean id="jpa" class="org.apache.camel.component.jpa.JpaComponent"> <property name="entityManagerFactory" ref="myEMFactory"/> <property name="transactionManager" ref="myTransactionManager"/> </bean> @Entity @NamedQuery(name = "step1", query = "select x from MultiSteps x where x.step = 1") public class MultiSteps { } from("jpa://org.apache.camel.examples.MultiSteps?namedQuery=step1") .to("bean:myBusinessLogic"); from("jpa://org.apache.camel.examples.MultiSteps?query=select o from org.apache.camel.examples.MultiSteps o where o.step = 1") .to("bean:myBusinessLogic"); from("jpa://org.apache.camel.examples.MultiSteps?nativeQuery=select * from MultiSteps where step = 1") .to("bean:myBusinessLogic"); @Entity @NamedQuery(name = "step1", query = "select x from MultiSteps x where x.step = 1") public class MultiSteps { } from("direct:namedQuery") .to("jpa://org.apache.camel.examples.MultiSteps?namedQuery=step1"); from("direct:query") .to("jpa://org.apache.camel.examples.MultiSteps?query=select o from org.apache.camel.examples.MultiSteps o where o.step = 1"); from("direct:nativeQuery") .to("jpa://org.apache.camel.examples.MultiSteps?resultClass=org.apache.camel.examples.MultiSteps&nativeQuery=select * from MultiSteps where step = 1"); <camelContext xmlns="http://camel.apache.org/schema/spring"> <route id="JpaMessageIdRepositoryTest"> <from uri="direct:start" /> <idempotentConsumer idempotentRepository="jpaStore"> <header>messageId</header> <to uri="mock:result" /> </idempotentConsumer> </route> </camelContext> org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is <openjpa-2.2.1-r422266:1396819 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "org.apache.camel.examples.SendEmail". at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:127) at org.apache.camel.processor.jpa.JpaRouteTest.cleanupRepository(JpaRouteTest.java:96) at org.apache.camel.processor.jpa.JpaRouteTest.createCamelContext(JpaRouteTest.java:67) at org.apache.camel.test.junit5.CamelTestSupport.doSetUp(CamelTestSupport.java:238) at org.apache.camel.test.junit5.CamelTestSupport.setUp(CamelTestSupport.java:208) -javaagent:<path_to_your_local_m2_cache>/org/apache/openjpa/openjpa/2.2.1/openjpa-2.2.1.jar <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jq-starter</artifactId> </dependency> from("queue:books.new") .choice() .when().jq(".store.book.price < 10)") .to("jms:queue:book.cheap") .when().jq(".store.book.price < 30)") .to("jms:queue:book.average") .otherwise() .to("jms:queue:book.expensive"); from("direct:start") .setHeader("numberOfBooks") .jq(".store.books | length", int.class, "books") .to("mock:result"); from("direct:start") .transform() .jq(".foo = header(\"MyHeader\")") .to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jslt-starter</artifactId> </dependency> jslt:specName[?options] jslt:resourceUri { "type": USDheaders.type, "instance": USDexchange.properties.instance } from("activemq:My.Queue"). to("jslt:com/acme/MyResponse.json"); from("activemq:My.Queue"). to("jslt:file://myfolder/MyResponse.json?contentCache=true"). to("activemq:Another.Queue"); from("direct:in"). setHeader("CamelJsltResourceUri").constant("path/to/my/spec.json"). to("jslt:dummy?allowTemplateFromHeader=true"); from("direct:in"). setHeader("CamelJsltString").constant(".published"). to("jslt:dummy?allowTemplateFromHeader=true"); from("direct:in"). to("jslt:com/acme/MyResponse.json?allowContextMapAll=true"); from("activemq:My.Queue"). marshal().json(JsonLibrary.Gson). to("mqseries:Another.Queue"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-gson-starter</artifactId> </dependency> from("activemq:My.Queue"). marshal().json(JsonLibrary.Jackson). to("mqseries:Another.Queue"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jackson-starter</artifactId> </dependency> @Bean CamelContextConfiguration contextConfiguration() { return new CamelContextConfiguration() { @Override public void beforeApplicationStart(CamelContext context) { // Enable Jackson JSON type converter. context.getGlobalOptions().put(JacksonConstants.ENABLE_TYPE_CONVERTER, "true"); // Allow Jackson JSON to convert to pojo types also // (by default Jackson only converts to String and other simple types) getContext().getGlobalOptions().put(JacksonConstants.TYPE_CONVERTER_TO_POJO, "true"); } @Override public void afterApplicationStart(CamelContext camelContext) { } }; } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jsonpath-starter</artifactId> </dependency> from("queue:books.new") .choice() .when().jsonpath("USD.store.book[?(@.price < 10)]") .to("jms:queue:book.cheap") .when().jsonpath("USD.store.book[?(@.price < 30)]") .to("jms:queue:book.average") .otherwise() .to("jms:queue:book.expensive"); <route> <from uri="direct:start"/> <choice> <when> <jsonpath>USD.store.book[?(@.price &lt; 10)]</jsonpath> <to uri="mock:cheap"/> </when> <when> <jsonpath>USD.store.book[?(@.price &lt; 30)]</jsonpath> <to uri="mock:average"/> </when> <otherwise> <to uri="mock:expensive"/> </otherwise> </choice> </route> USD.store.book[?(@.price < 20)] store.book.price < 20 price < 20 left OP right store.book.price < USD{header.limit} from("direct:start") .choice() // use true to suppress exceptions .when().jsonpath("person.middlename", true) .to("mock:middle") .otherwise() .to("mock:other"); <route> <from uri="direct:start"/> <choice> <when> <jsonpath suppressExceptions="true">person.middlename</jsonpath> <to uri="mock:middle"/> </when> <otherwise> <to uri="mock:other"/> </otherwise> </choice> </route> from("direct:start") .choice() .when().jsonpath("USD.store.book[?(@.price < USD{header.cheap})]") .to("mock:cheap") .when().jsonpath("USD.store.book[?(@.price < USD{header.average})]") .to("mock:average") .otherwise() .to("mock:expensive"); <route> <from uri="direct:start"/> <choice> <when> <jsonpath>USD.store.book[?(@.price &lt; USD{header.cheap})]</jsonpath> <to uri="mock:cheap"/> </when> <when> <jsonpath>USD.store.book[?(@.price &lt; USD{header.average})]</jsonpath> <to uri="mock:average"/> </when> <otherwise> <to uri="mock:expensive"/> </otherwise> </choice> </route> .when().jsonpath("USD.store.book[?(@.price < 10)]", false, false) <jsonpath allowSimple="false">USD.store.book[?(@.price &lt; 10)]</jsonpath> public class Foo { @Consume("activemq:queue:books.new") public void doSomething(@JsonPath("USD.store.book[*].author") String author, @Body String json) { // process the inbound message here } } from("direct:start") .split().jsonpath("USD.store.book[*]") .to("log:book"); from("direct:start") .split().jsonpathWriteAsString("USD.store.book[*]") .to("log:book"); from("direct:start") .setHeader("numberOfBooks") .jsonpath("USD..store.book.length()", false, int.class, "books") .to("mock:result"); <route> <from uri="direct:start"/> <setHeader name="numberOfBooks"> <jsonpath headerName="books" resultType="int">USD..store.book.length()</jsonpath> </setHeader> <to uri="mock:result"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kafka-starter</artifactId> </dependency> kafka:topic[?options] kafka:topic KafkaComponent kafka = new KafkaComponent(); kafka.setBreakOnFirstError(true); camelContext.addComponent("kafka", kafka); KafkaIdempotentRepository kafkaIdempotentRepository = new KafkaIdempotentRepository("idempotent-db-inserts", "localhost:9091"); SimpleRegistry registry = new SimpleRegistry(); registry.put("insertDbIdemRepo", kafkaIdempotentRepository); // must be registered in the registry, to enable access to the CamelContext CamelContext context = new CamelContext(registry); // later in RouteBuilder from("direct:performInsert") .idempotentConsumer(header("id")).messageIdRepositoryRef("insertDbIdemRepo") // once-only insert into database .end() <!-- simple --> <bean id="insertDbIdemRepo" class="org.apache.camel.processor.idempotent.kafka.KafkaIdempotentRepository"> <property name="topic" value="idempotent-db-inserts"/> <property name="bootstrapServers" value="localhost:9091"/> </bean> <!-- complex --> <bean id="insertDbIdemRepo" class="org.apache.camel.processor.idempotent.kafka.KafkaIdempotentRepository"> <property name="topic" value="idempotent-db-inserts"/> <property name="maxCacheSize" value="10000"/> <property name="consumerConfig"> <props> <prop key="bootstrap.servers">localhost:9091</prop> </props> </property> <property name="producerConfig"> <props> <prop key="bootstrap.servers">localhost:9091</prop> </props> </property> </bean> from("direct:performInsert") .idempotentConsumer(numericHeader("id")).messageIdRepositoryRef("insertDbIdemRepo") // once-only insert into database .end() public class CustomHeaderDeserializer extends DefaultKafkaHeaderDeserializer { private static final Logger LOG = LoggerFactory.getLogger(CustomHeaderDeserializer.class); @Override public Object deserialize(String key, byte[] value) { if (key.equals("id")) { BigInteger bi = new BigInteger(value); return String.valueOf(bi.longValue()); } else { return super.deserialize(key, value); } } } from(from).routeId("foo") .process(exchange -> { byte[] id = exchange.getIn().getHeader("id", byte[].class); BigInteger bi = new BigInteger(id); exchange.getIn().setHeader("id", String.valueOf(bi.longValue())); }) .idempotentConsumer(header("id")) .messageIdRepositoryRef("kafkaIdempotentRepository") .to(to); KafkaComponent kafka = new KafkaComponent(); kafka.setAllowManualCommit(true); camelContext.addComponent("kafka", kafka); public void process(Exchange exchange) { KafkaManualCommit manual = exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); manual.commit(); } KafkaComponent kafka = new KafkaComponent(); kafka.setAutoCommitEnable(false); kafka.setAllowManualCommit(true); kafka.setBreakOnFirstError(true); kafka.setKafkaManualCommitFactory(new DefaultKafkaManualCommitFactory()); camelContext.addComponent("kafka", kafka); from("kafka:topic") .pausable(new KafkaConsumerListener(), () -> canContinue()) // the pausable check gets called if the exchange fails to be processed .routeId("pausable-route") .process(this::process) // Kafka consumer will be paused if this one throws an exception .to("some:destination"); // or this one from("kafka:my_topic?headerDeserializer=#myDeserializer") .to("kafka:my_topic?headerSerializer=#mySerializer") from("kafka:my_topic?headerFilterStrategy=#myStrategy") .to("kafka:my_topic?headerFilterStrategy=#myStrategy") from("direct:transaction") .to("kafka:my_topic?additional-properties[transactional.id]=1234&additional-properties[enable.idempotence]=true&additional-properties[retries]=5"); static { KafkaComponent.setKerberosConfigLocation("path/to/config/file"); } public void configure() { from("kafka:topic?groupId=myGroup&pollTimeoutMs=1000&batching=true&maxPollRecords=10&autoOffsetReset=earliest").process(e -> { // The received records are stored as exchanges in a list. This gets the list of those exchanges final List<?> exchanges = e.getMessage().getBody(List.class); // Ensure we are actually receiving what we are asking for if (exchanges == null || exchanges.isEmpty()) { return; } // The records from the batch are stored in a list of exchanges in the original exchange. To process, we iterate over that list for (Object obj : exchanges) { if (obj instanceof Exchange exchange) { LOG.info("Processing exchange with body {}", exchange.getMessage().getBody(String.class)); } } }).to(KafkaTestUtil.MOCK_RESULT); } public void configure() { /* We want to use continued here, so that Camel auto-commits the batch even though part of it has failed. In a production scenario, applications should probably send these records to a separate topic or fix the condition that lead to the failure */ onException(IllegalArgumentException.class).process(exchange -> { LOG.warn("Failed to process batch {}", exchange.getMessage().getBody()); LOG.warn("Failed to process due to {}", exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class).getMessage()); }).continued(true); from("kafka:topic?groupId=myGroup&pollTimeoutMs=1000&batching=true&maxPollRecords=10&autoOffsetReset=earliest").process(e -> { // The received records are stored as exchanges in a list. This gets the list of those exchanges final List<?> exchanges = e.getMessage().getBody(List.class); // Ensure we are actually receiving what we are asking for if (exchanges == null || exchanges.isEmpty()) { return; } // The records from the batch are stored in a list of exchanges in the original exchange. int i = 0; for (Object o : exchanges) { if (o instanceof Exchange exchange) { i++; LOG.info("Processing exchange with body {}", exchange.getMessage().getBody(String.class)); if (i == 4) { throw new IllegalArgumentException("Failed to process record"); } } } }).to(KafkaTestUtil.MOCK_RESULT); } public void configure() { from("kafka:topic?batching=true&allowManualCommit=true&maxPollRecords=100&kafkaManualCommitFactory=#class:org.apache.camel.component.kafka.consumer.DefaultKafkaManualCommitFactory") .process(e -> { // The received records are stored as exchanges in a list. This gets the list of those exchanges final List<?> exchanges = e.getMessage().getBody(List.class); // Ensure we are actually receiving what we are asking for if (exchanges == null || exchanges.isEmpty()) { return; } /* Every exchange in that list should contain a reference to the manual commit object. We use the reference for the last exchange in the list to commit the whole batch */ final Object tmp = exchanges.getLast(); if (tmp instanceof Exchange exchange) { KafkaManualCommit manual = exchange.getMessage().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); LOG.debug("Performing manual commit"); manual.commit(); LOG.debug("Done performing manual commit"); } }); } public void configure() { // Note that this can be configured in other ways getCamelContext().getShutdownStrategy().setTimeout(10000); // route setup } public class CustomSubscribeAdapter implements SubscribeAdapter { @Override public void subscribe(Consumer<?, ?> consumer, ConsumerRebalanceListener reBalanceListener, TopicInfo topicInfo) { if (topicInfo.isPattern()) { consumer.subscribe(topicInfo.getPattern(), reBalanceListener); } else { consumer.subscribe(topicInfo.getTopics(), reBalanceListener); } } } context.getRegistry().bind(KafkaConstants.KAFKA_SUBSCRIBE_ADAPTER, new CustomSubscribeAdapter()); from("kafka:topic?headerDeserializer=#class:org.apache.camel.component.kafka.consumer.support.interop.JMSDeserializer") .to("..."); from("kafka:test?brokers=localhost:9092") .log("Message received from Kafka : USD{body}") .log(" on the topic USD{headers[kafka.TOPIC]}") .log(" on the partition USD{headers[kafka.PARTITION]}") .log(" with the offset USD{headers[kafka.OFFSET]}") .log(" with the key USD{headers[kafka.KEY]}") from("kafka:test,test1,test2?brokers=localhost:9092") .log("Message received from Kafka : USD{body}") .log(" on the topic USD{headers[kafka.TOPIC]}") .log(" on the partition USD{headers[kafka.PARTITION]}") .log(" with the offset USD{headers[kafka.OFFSET]}") .log(" with the key USD{headers[kafka.KEY]}") from("kafka:test*?brokers=localhost:9092&topicIsPattern=true") .log("Message received from Kafka : USD{body}") .log(" on the topic USD{headers[kafka.TOPIC]}") .log(" on the partition USD{headers[kafka.PARTITION]}") .log(" with the offset USD{headers[kafka.OFFSET]}") .log(" with the key USD{headers[kafka.KEY]}") // Create the repository in which the Kafka offsets will be persisted FileStateRepository repository = FileStateRepository.fileStateRepository(new File("/path/to/repo.dat")); // Bind this repository into the Camel registry Registry registry = createCamelRegistry(); registry.bind("offsetRepo", repository); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("kafka:" + TOPIC + "?brokers=localhost:{{kafkaPort}}" + // Setup the topic and broker address "&groupId=A" + // The consumer processor group ID "&autoOffsetReset=earliest" + // Ask to start from the beginning if we have unknown offset "&offsetRepository=#offsetRepo") // Keep the offsets in the previously configured repository .to("mock:result"); } }); from("direct:start") .setBody(constant("Message from Camel")) // Message to send .setHeader(KafkaConstants.KEY, constant("Camel")) // Key of the message .to("kafka:test?brokers=localhost:9092"); from("kafka:" + TOPIC + "?brokers=localhost:{{kafkaPort}}" + "&groupId=A" + "&sslKeystoreLocation=/path/to/keystore.jks" + "&sslKeystorePassword=changeit" + "&sslKeyPassword=changeit" + "&securityProtocol=SSL") .to("mock:result"); // Configure the SSLContextParameters object KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("/path/to/keystore.jks"); ksp.setPassword("changeit"); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword("changeit"); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); // Bind this SSLContextParameters into the Camel registry Registry registry = createCamelRegistry(); registry.bind("ssl", scp); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("kafka:" + TOPIC + "?brokers=localhost:{{kafkaPort}}" + // Setup the topic and broker address "&groupId=A" + // The consumer processor group ID "&sslContextParameters=#ssl" + // The security protocol "&securityProtocol=SSL) // Reference the SSL configuration .to("mock:result"); } }); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kamelet-starter</artifactId> </dependency> kamelet:templateId/routeId[?options] kamelet:templateId/routeId routeTemplate("setMyBody") .templateParameter("bodyValue") .from("kamelet:source") .setBody().constant("{{bodyValue}}"); from("direct:setMyBody") .to("kamelet:setMyBody?bodyValue=myKamelet"); routeTemplate("setMyBody") .templateParameter("bodyValue") .from("direct:{{foo}}") .setBody().constant("{{bodyValue}}"); TemplatedRouteBuilder.builder(context, "setMyBody") .parameter("foo", "bar") .parameter("bodyValue", "myKamelet") .add(); from("direct:template") .to("direct:bar"); camel.component.kamelet.location = classpath:/kamelets,github:apache:camel-kamelets/kamelets camel.component.rest.consumerComponentName = platform-http camel.component.rest.producerComponentName = vertx-http - route: from: "kamelet:earthquake-source" steps: - unmarshal: json: {} - log: "Earthquake with magnitude USD{body[properties][mag]} at USD{body[properties][place]}" <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> from("direct:createPod") .toF("kubernetes-pods://%s?oauthToken=%s&operation=createPod", host, authToken); from("direct:createPod") .toF("kubernetes-pods://%s?oauthToken=%s&operation=deletePod", host, authToken); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-config-maps:masterUrl from("direct:list"). to("kubernetes-config-maps:///?kubernetesClient=#kubernetesClient&operation=listConfigMaps"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_CONFIGMAPS_LABELS, labels); } }); to("kubernetes-config-maps:///?kubernetesClient=#kubernetesClient&operation=listConfigMapsByLabels"). to("mock:result"); fromF("kubernetes-config-maps://%s?oauthToken=%s", host, authToken) .setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, constant("default")) .setHeader(KubernetesConstants.KUBERNETES_CONFIGMAP_NAME, constant("test")) .process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); ConfigMap cm = exchange.getIn().getBody(ConfigMap.class); log.info("Got event with configmap name: " + cm.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-custom-resources:masterUrl <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-deployments:masterUrl from("direct:list"). toF("kubernetes-deployments:///?kubernetesClient=#kubernetesClient&operation=listDeployments"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_DEPLOYMENTS_LABELS, labels); } }); toF("kubernetes-deployments:///?kubernetesClient=#kubernetesClient&operation=listDeploymentsByLabels"). to("mock:result"); fromF("kubernetes-deployments://%s?oauthToken=%s&namespace=default&resourceName=test", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Deployment dp = exchange.getIn().getBody(Deployment.class); log.info("Got event with configmap name: " + dp.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-events:masterUrl from("direct:list"). to("kubernetes-events:///?kubernetesClient=#kubernetesClient&operation=listEvents"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENTS_LABELS, labels); } }); to("kubernetes-events:///?kubernetesClient=#kubernetesClient&operation=listEventsByLabels"). to("mock:result"); from("direct:get").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "test"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_NAME, "event1"); } }); to("kubernetes-events:///?kubernetesClient=#kubernetesClient&operation=getEvent"). to("mock:result"); from("direct:get").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "default"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_NAME, "test1"); Map<String, String> labels = new HashMap<>(); labels.put("this", "rocks"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENTS_LABELS, labels); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION_PRODUCER, "Some Action"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_TYPE, "Normal"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_REASON, "Some Reason"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_REPORTING_CONTROLLER, "Some-Reporting-Controller"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_REPORTING_INSTANCE, "Some-Reporting-Instance"); } }); to("kubernetes-events:///?kubernetesClient=#kubernetesClient&operation=createEvent"). to("mock:result"); from("direct:get").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "default"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_EVENT_NAME, "test1"); } }); to("kubernetes-events:///?kubernetesClient=#kubernetesClient&operation=deleteEvent"). to("mock:result"); fromF("kubernetes-events://%s?oauthToken=%s", host, authToken) .setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, constant("default")) .setHeader(KubernetesConstants.KUBERNETES_EVENT_NAME, constant("test")) .process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Event cm = exchange.getIn().getBody(Event.class); log.info("Got event with event name: " + cm.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-hpa:masterUrl from("direct:list"). toF("kubernetes-hpa:///?kubernetesClient=#kubernetesClient&operation=listHPA"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_HPA_LABELS, labels); } }); toF("kubernetes-hpa:///?kubernetesClient=#kubernetesClient&operation=listHPAByLabels"). to("mock:result"); fromF("kubernetes-hpa://%s?oauthToken=%s&namespace=default&resourceName=test", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); HorizontalPodAutoscaler hpa = exchange.getIn().getBody(HorizontalPodAutoscaler.class); log.info("Got event with hpa name: " + hpa.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-job:masterUrl from("direct:list"). toF("kubernetes-job:///?kubernetesClient=#kubernetesClient&operation=listJob"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_JOB_LABELS, labels); } }); toF("kubernetes-job:///?kubernetesClient=#kubernetesClient&operation=listJobByLabels"). to("mock:result"); import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.apache.camel.Endpoint; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.cdi.Uri; import org.apache.camel.component.kubernetes.KubernetesConstants; import org.apache.camel.component.kubernetes.KubernetesOperations; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.PodSpec; import io.fabric8.kubernetes.api.model.PodTemplateSpec; import io.fabric8.kubernetes.api.model.batch.JobSpec; public class KubernetesCreateJob extends RouteBuilder { @Inject @Uri("timer:foo?delay=1000&repeatCount=1") private Endpoint inputEndpoint; @Inject @Uri("log:output") private Endpoint resultEndpoint; @Override public void configure() { // you can configure the route rule with Java DSL here from(inputEndpoint) .routeId("kubernetes-jobcreate-client") .process(exchange -> { exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_JOB_NAME, "camel-job"); //DNS-1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*') exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "default"); Map<String, String> joblabels = new HashMap<String, String>(); joblabels.put("jobLabelKey1", "value1"); joblabels.put("jobLabelKey2", "value2"); joblabels.put("app", "jobFromCamelApp"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_JOB_LABELS, joblabels); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_JOB_SPEC, generateJobSpec()); }) .toF("kubernetes-job:///{{kubernetes-master-url}}?oauthToken={{kubernetes-oauth-token:}}&operation=" + KubernetesOperations.CREATE_JOB_OPERATION) .log("Job created:") .process(exchange -> { System.out.println(exchange.getIn().getBody()); }) .to(resultEndpoint); } private JobSpec generateJobSpec() { JobSpec js = new JobSpec(); PodTemplateSpec pts = new PodTemplateSpec(); PodSpec ps = new PodSpec(); ps.setRestartPolicy("Never"); ps.setContainers(generateContainers()); pts.setSpec(ps); ObjectMeta metadata = new ObjectMeta(); Map<String, String> annotations = new HashMap<String, String>(); annotations.put("jobMetadataAnnotation1", "random value"); metadata.setAnnotations(annotations); Map<String, String> podlabels = new HashMap<String, String>(); podlabels.put("podLabelKey1", "value1"); podlabels.put("podLabelKey2", "value2"); podlabels.put("app", "podFromCamelApp"); metadata.setLabels(podlabels); pts.setMetadata(metadata); js.setTemplate(pts); return js; } private List<Container> generateContainers() { Container container = new Container(); container.setName("pi"); container.setImage("perl"); List<String> command = new ArrayList<String>(); command.add("echo"); command.add("Job created from Apache Camel code at " + (new Date())); container.setCommand(command); List<Container> containers = new ArrayList<Container>(); containers.add(container); return containers; } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-namespaces:masterUrl from("direct:list"). toF("kubernetes-deployments:///?kubernetesClient=#kubernetesClient&operation=listNamespaces"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACES_LABELS, labels); } }); toF("kubernetes-deployments:///?kubernetesClient=#kubernetesClient&operation=listNamespacesByLabels"). to("mock:result"); fromF("kubernetes-namespaces://%s?oauthToken=%s&namespace=default", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Namespace ns = exchange.getIn().getBody(Namespace.class); log.info("Got event with configmap name: " + ns.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-nodes:masterUrl from("direct:list"). toF("kubernetes-nodes:///?kubernetesClient=#kubernetesClient&operation=listNodes"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NODES_LABELS, labels); } }); toF("kubernetes-deployments:///?kubernetesClient=#kubernetesClient&operation=listNodesByLabels"). to("mock:result"); fromF("kubernetes-nodes://%s?oauthToken=%s&resourceName=test", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Node node = exchange.getIn().getBody(Node.class); log.info("Got event with configmap name: " + node.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-persistent-volumes:masterUrl from("direct:list"). toF("kubernetes-persistent-volumes:///?kubernetesClient=#kubernetesClient&operation=listPersistentVolumes"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_PERSISTENT_VOLUMES_LABELS, labels); } }); toF("kubernetes-persistent-volumes:///?kubernetesClient=#kubernetesClient&operation=listPersistentVolumesByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-persistent-volumes-claims:masterUrl from("direct:list"). toF("kubernetes-persistent-volumes-claims:///?kubernetesClient=#kubernetesClient&operation=listPersistentVolumesClaims"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_PERSISTENT_VOLUMES_CLAIMS_LABELS, labels); } }); toF("kubernetes-persistent-volumes-claims:///?kubernetesClient=#kubernetesClient&operation=listPersistentVolumesClaimsByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-pods:masterUrl from("direct:list"). toF("kubernetes-pods:///?kubernetesClient=#kubernetesClient&operation=listPods"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_PODS_LABELS, labels); } }); toF("kubernetes-pods:///?kubernetesClient=#kubernetesClient&operation=listPodsByLabels"). to("mock:result"); fromF("kubernetes-pods://%s?oauthToken=%s&namespace=default&resourceName=test", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Pod pod = exchange.getIn().getBody(Pod.class); log.info("Got event with configmap name: " + pod.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-replication-controllers:masterUrl from("direct:list"). toF("kubernetes-replication-controllers:///?kubernetesClient=#kubernetesClient&operation=listReplicationControllers"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_REPLICATION_CONTROLLERS_LABELS, labels); } }); toF("kubernetes-replication-controllers:///?kubernetesClient=#kubernetesClient&operation=listReplicationControllersByLabels"). to("mock:result"); fromF("kubernetes-replication-controllers://%s?oauthToken=%s&namespace=default&resourceName=test", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); ReplicationController rc = exchange.getIn().getBody(ReplicationController.class); log.info("Got event with configmap name: " + rc.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-resources-quota:masterUrl from("direct:list"). toF("kubernetes-resources-quota:///?kubernetesClient=#kubernetesClient&operation=listResourcesQuota"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_RESOURCES_QUOTA_LABELS, labels); } }); toF("kubernetes-resources-quota:///?kubernetesClient=#kubernetesClient&operation=listResourcesQuotaByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-secrets:masterUrl from("direct:list"). toF("kubernetes-secrets:///?kubernetesClient=#kubernetesClient&operation=listSecrets"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_SECRETS_LABELS, labels); } }); toF("kubernetes-secrets:///?kubernetesClient=#kubernetesClient&operation=listSecretsByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-service-accounts:masterUrl from("direct:list"). toF("kubernetes-service-accounts:///?kubernetesClient=#kubernetesClient&operation=listServiceAccounts"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_SERVICE_ACCOUNTS_LABELS, labels); } }); toF("kubernetes-service-accounts:///?kubernetesClient=#kubernetesClient&operation=listServiceAccountsByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> kubernetes-services:masterUrl from("direct:list"). toF("kubernetes-services:///?kubernetesClient=#kubernetesClient&operation=listServices"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_SERVICE_LABELS, labels); } }); toF("kubernetes-services:///?kubernetesClient=#kubernetesClient&operation=listServicesByLabels"). to("mock:result"); fromF("kubernetes-services://%s?oauthToken=%s&namespace=default&resourceName=test", host, authToken).process(new KubernertesProcessor()).to("mock:result"); public class KubernertesProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); Service sv = exchange.getIn().getBody(Service.class); log.info("Got event with configmap name: " + sv.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> openshift-builds:masterUrl from("direct:list"). toF("openshift-builds:///?kubernetesClient=#kubernetesClient&operation=listBuilds"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_BUILDS_LABELS, labels); } }); toF("openshift-builds:///?kubernetesClient=#kubernetesClient&operation=listBuildsByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> openshift-build-configs:masterUrl from("direct:list"). toF("openshift-build-configs:///?kubernetesClient=#kubernetesClient&operation=listBuildConfigs"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_BUILD_CONFIGS_LABELS, labels); } }); toF("openshift-build-configs:///?kubernetesClient=#kubernetesClient&operation=listBuildConfigsByLabels"). to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kubernetes-starter</artifactId> </dependency> openshift-deploymentconfigs:masterUrl from("direct:list"). toF("openshift-deploymentconfigs:///?kubernetesClient=#kubernetesClient&operation=listDeploymentConfigs"). to("mock:result"); from("direct:listByLabels").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Map<String, String> labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_DEPLOYMENTS_LABELS, labels); } }); toF("openshift-deploymentconfigs:///?kubernetesClient=#kubernetesClient&operation=listDeploymentConfigsByLabels"). to("mock:result"); fromF("openshift-deploymentconfigs://%s?oauthToken=%s&namespace=default&resourceName=test", host, authToken).process(new OpenshiftProcessor()).to("mock:result"); public class OpenshiftProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); DeploymentConfig dp = exchange.getIn().getBody(DeploymentConfig.class); log.info("Got event with configmap name: " + dp.getMetadata().getName() + " and action " + in.getHeader(KubernetesConstants.KUBERNETES_EVENT_ACTION)); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-kudu-starter</artifactId> </dependency> kudu:host:port/tableName <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-language-starter</artifactId> </dependency> language://languageName[:script][?options] language://languageName:resource:scheme:location][?options] language:languageName:resourceUri Object out = producer.requestBodyAndHeader("language:xpath", "<foo>Hello World</foo>", Exchange.LANGUAGE_SCRIPT, "/foo/text()"); assertEquals("Hello World", out); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-ldap-starter</artifactId> </dependency> ldap:ldapServerBean[?options] ldap:dirContextName <bean id="ldapserver" class="javax.naming.directory.InitialDirContext" scope="prototype"> <constructor-arg> <props> <prop key="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</prop> <prop key="java.naming.provider.url">ldap://localhost:10389</prop> <prop key="java.naming.security.authentication">none</prop> </props> </constructor-arg> </bean> ProducerTemplate template = exchange.getContext().createProducerTemplate(); Collection<SearchResult> results = template.requestBody( "ldap:ldapserver?base=ou=mygroup,ou=groups,ou=system", "(member=uid=huntc,ou=users,ou=system)", Collection.class); if (results.size() > 0) { // Extract what we need from the device's profile Iterator resultIter = results.iterator(); SearchResult searchResult = (SearchResult) resultIter.next(); Attributes attributes = searchResult.getAttributes(); Attribute deviceCNAttr = attributes.get("cn"); String deviceCN = (String) deviceCNAttr.get(); // } (cn=*) Properties props = new Properties(); props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.setProperty(Context.PROVIDER_URL, "ldap://localhost:389"); props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url"); props.setProperty(Context.REFERRAL, "ignore"); props.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); props.setProperty(Context.SECURITY_PRINCIPAL, "cn=Manager"); props.setProperty(Context.SECURITY_CREDENTIALS, "secret"); DefaultRegistry reg = new DefaultRegistry(); reg.bind("myldap", new InitialLdapContext(props, null)); CamelContext context = new DefaultCamelContext(reg); context.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("ldap:myldap?base=ou=test"); } } ); context.start(); ProducerTemplate template = context.createProducerTemplate(); Endpoint endpoint = context.getEndpoint("direct:start"); Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody("(uid=test)"); Exchange out = template.send(endpoint, exchange); Collection<SearchResult> data = out.getMessage().getBody(Collection.class); assert data != null; assert !data.isEmpty(); System.out.println(out.getMessage().getBody()); context.stop(); <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <sslContextParameters xmlns="http://camel.apache.org/schema/spring" id="sslContextParameters" > <keyManagers keyPassword="{{keystore.pwd}}"> <keyStore resource="{{keystore.url}}" password="{{keystore.pwd}}"/> </keyManagers> </sslContextParameters> <bean id="customSocketFactory" class="com.example.ldap.CustomSocketFactory"> <constructor-arg index="0" ref="sslContextParameters"/> </bean> <bean id="ldapserver" class="javax.naming.directory.InitialDirContext" scope="prototype"> <constructor-arg> <props> <prop key="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</prop> <prop key="java.naming.provider.url">ldaps://127.0.0.1:10636</prop> <prop key="java.naming.security.protocol">ssl</prop> <prop key="java.naming.security.authentication">none</prop> <prop key="java.naming.ldap.factory.socket">com.example.ldap.CustomSocketFactory</prop> </props> </constructor-arg> </bean> </beans> package com.example.ldap; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.KeyStore; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import org.apache.camel.support.jsse.SSLContextParameters; /** * The CustomSocketFactory. Loads the KeyStore and creates an instance of SSLSocketFactory */ public class CustomSocketFactory extends SSLSocketFactory { private static SSLSocketFactory socketFactory; /** * Called by the getDefault() method. */ public CustomSocketFactory() { } /** * Called by Spring Boot DI to initialize an instance of SocketFactory */ public CustomSocketFactory(SSLContextParameters sslContextParameters) { try { KeyStore keyStore = sslContextParameters.getKeyManagers().getKeyStore().createKeyStore(); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(keyStore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, tmf.getTrustManagers(), null); socketFactory = ctx.getSocketFactory(); } catch (Exception ex) { ex.printStackTrace(System.err); } } /** * Getter for the SocketFactory */ public static SocketFactory getDefault() { return new CustomSocketFactory(); } @Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); } @Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException { return socketFactory.createSocket(socket, string, i, bln); } @Override public Socket createSocket(String string, int i) throws IOException { return socketFactory.createSocket(string, i); } @Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException { return socketFactory.createSocket(string, i, ia, i1); } @Override public Socket createSocket(InetAddress ia, int i) throws IOException { return socketFactory.createSocket(ia, i); } @Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException { return socketFactory.createSocket(ia, i, ia1, i1); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-log-starter</artifactId> </dependency> log:loggingCategory[?options] log:org.apache.camel.example?level=DEBUG log:loggerName from("activemq:orders").to("log:com.mycompany.order?level=DEBUG").to("bean:processOrder"); <route> <from uri="activemq:orders"/> <to uri="log:com.mycompany.order?level=DEBUG"/> <to uri="bean:processOrder"/> </route> from("activemq:orders"). to("log:com.mycompany.order?showAll=true&multiline=true").to("bean:processOrder"); from("activemq:orders"). to("log:com.mycompany.order?level=DEBUG&groupSize=10").to("bean:processOrder"); from("activemq:orders"). to("log:com.mycompany.order?level=DEBUG&groupInterval=10000&groupDelay=60000&groupActiveOnly=false").to("bean:processOrder"); "Received: 1000 new messages, with total 2000 so far. Last group took: 10000 millis which is: 100 messages per second. average: 100" camelContext.setLogMask(true); <camelContext logMask="true"> from("direct:start").to("log:foo?logMask=true"); <route> <from uri="direct:foo"/> <to uri="log:foo?logMask=true"/> </route> Exchange[Id:ID-machine-local-50656-1234567901234-1-2, ExchangePattern:InOut, Properties:{CamelToEndpoint=log://org.apache.camel.component.log.TEST?showAll=true, CamelCreatedTimestamp=Thu Mar 28 00:00:00 WET 2013}, Headers:{breadcrumbId=ID-machine-local-50656-1234567901234-1-1}, BodyType:String, Body:Hello World, Out: null] <bean name="log" class="org.apache.camel.component.log.LogComponent"> <property name="exchangeFormatter" ref="myCustomFormatter" /> </bean> <bean name="logFormatter" class="com.xyz.MyCustomExchangeFormatter" /> <bean name="logFormatter" class="com.xyz.MyCustomExchangeFormatter" scope="prototype"/> <to uri="log:foo?param1=foo&amp;param2=100"/> <to uri="log:bar?param1=bar&amp;param2=200"/> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-lra-starter</artifactId> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mail-starter</artifactId> </dependency> smtp://[username@]host[:port][?options] pop3://[username@]host[:port][?options] imap://[username@]host[:port][?options] smtps://[username@]host[:port][?options] pop3s://[username@]host[:port][?options] imaps://[username@]host[:port][?options] imap:host:port smtp://[username@]host[:port][?password=somepwd] smtp://host[:port]?password=somepwd&username=someuser smtp://mycompany.mailserver:30?password=tiger&username=scott KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("/users/home/server/truststore.jks"); ksp.setPassword("keystorePassword"); TrustManagersParameters tmp = new TrustManagersParameters(); tmp.setKeyStore(ksp); SSLContextParameters scp = new SSLContextParameters(); scp.setTrustManagers(tmp); Registry registry = registry.bind("sslContextParameters", scp); from(...) .to("smtps://smtp.google.com?username=user@gmail.com&password=password&sslContextParameters=#sslContextParameters"); <camel:sslContextParameters id="sslContextParameters"> <camel:trustManagers> <camel:keyStore resource="/users/home/server/truststore.jks" password="keystorePassword"/> </camel:trustManagers> </camel:sslContextParameters> <to uri="smtps://smtp.google.com?username=user@gmail.com&password=password&sslContextParameters=#sslContextParameters"/> Map<String, Object> headers = new HashMap<String, Object>(); headers.put("to", "davsclaus@apache.org"); template.sendBodyAndHeaders("smtp://admin@localhost?to=info@mycompany.com", "Hello World", headers); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("to", "davsclaus@apache.org ; jstrachan@apache.org ; ningjiang@apache.org"); Map headers = new HashMap(); map.put("To", "Claus Ibsen <davsclaus@apache.org>"); map.put("From", "James Strachan <jstrachan@apache.org>"); map.put("Subject", "Camel is cool"); from("jms://queue:subscription").to("smtp://admin@mymailserver.com?password=secret"); from("imap://admin@mymailserver.com?password=secret&unseen=true&delay=60000") .to("seda://mails"); from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD" + "&delete=false&unseen=true&delay=60000").to("log:newmail"); 2008-05-08 06:32:09,640 DEBUG MailConsumer - Connecting to MailStore imaps//imap.gmail.com:993 (SSL enabled), folder=INBOX 2008-05-08 06:32:11,203 DEBUG MailConsumer - Polling mailfolder: imaps//imap.gmail.com:993 (SSL enabled), folder=INBOX 2008-05-08 06:32:11,640 DEBUG MailConsumer - Fetching 1 messages. Total 1 messages. 2008-05-08 06:32:12,171 DEBUG MailConsumer - Processing message: messageNumber=[332], from=[James Bond <007@mi5.co.uk>], to=YOUR_USERNAME@gmail.com], subject=[ 2008-05-08 06:32:12,187 INFO newmail - Exchange[MailMessage: messageNumber=[332], from=[James Bond <007@mi5.co.uk>], to=YOUR_USERNAME@gmail.com], subject=[ from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD" + "&delete=false&unseen=true&delay=60000").process(new MyMailProcessor()); public void process(Exchange exchange) throws Exception { // the API is a bit clunky so we need to loop AttachmentMessage attachmentMessage = exchange.getMessage(AttachmentMessage.class); Map<String, DataHandler> attachments = attachmentMessage.getAttachments(); if (attachments.size() > 0) { for (String name : attachments.keySet()) { DataHandler dh = attachments.get(name); // get the file name String filename = dh.getName(); // get the content and convert it to byte[] byte[] data = exchange.getContext().getTypeConverter() .convertTo(byte[].class, dh.getInputStream()); // write the data to a file FileOutputStream out = new FileOutputStream(filename); out.write(data); out.flush(); out.close(); } } } <split> <method beanType="org.apache.camel.component.mail.SplitAttachmentsExpression"/> <to uri="mock:split"/> </split> SplitAttachmentsExpression split = SplitAttachmentsExpression(true); <route> <from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm.subjectOrBody=Camel"/> <to uri="bean:myBean"/> </route> <route> <from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm.fromSentDate=now-24h"/> <to uri="bean:myBean"/> </route> <route> <from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm.subject=Camel&searchTerm.fromSentDate=now-24h"/> <to uri="bean:myBean"/> </route> <bean id="mySearchTerm" class="org.apache.camel.component.mail.SimpleSearchTerm"> <property name="subject" value="Order"/> <property name="to" value="acme-order@acme.com"/> <property name="fromSentDate" value="now"/> </bean> <route> <from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm=#mySearchTerm"/> <to uri="bean:myBean"/> </route> // we just want the unseen mails which is not spam SearchTermBuilder builder = new SearchTermBuilder(); builder.unseen().body(Op.not, "Spam").subject(Op.not, "Spam") // which was sent from either foo or bar .from("foo@somewhere.com").from(Op.or, "bar@somewhere.com"); // .. and we could continue building the terms SearchTerm term = builder.build(); .setHeader("from", constant("reply2me@foo.com")); .setHeader("java.smtp.from", method(UUID.class, "randomUUID")); .to("smtp://mymailserver:1234"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mail-microsoft-oauth</artifactId> </dependency> @BindToRegistry("auth") public MicrosoftExchangeOnlineOAuth2MailAuthenticator exchangeAuthenticator(){ return new MicrosoftExchangeOnlineOAuth2MailAuthenticator(tenantId, clientId, clientSecret, "jon@doe.com"); } from("imaps://outlook.office365.com:993" + "?authenticator=#auth" + "&mail.imaps.auth.mechanisms=XOAUTH2" + "&debugMode=true" + "&delete=false") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mapstruct-starter</artifactId> </dependency> mapstruct:className[?options] mapstruct:className MapstructComponent mc = context.getComponent("mapstruct", MapstructComponent.class); mc.setMapperPackageName("com.foo.mapper,com.bar.mapper"); camel.component.mapstruct.mapper-package-name = com.foo.mapper,com.bar.mapper from("direct:foo") .convertBodyTo(MyFooDto.class); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-master-starter</artifactId> </dependency> from("master:cheese:jms:foo").to("activemq:wine"); master:namespace:endpoint[?options] master:namespace:delegateUri // the file endpoint we want to consume from String url = "file:target/inbox?delete=true"; // use the camel master component in the clustered group named myGroup // to run a master/slave mode in the following Camel url from("master:myGroup:" + url) .log(name + " - Received file: USD{file:name}") .delay(delay) .log(name + " - Done file: USD{file:name}") .to("file:target/outbox"); ZooKeeperClusterService service = new ZooKeeperClusterService(); service.setId("camel-node-1"); service.setNodes("myzk:2181"); service.setBasePath("/camel/cluster"); context.addService(service) <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <bean id="cluster" class="org.apache.camel.component.zookeeper.cluster.ZooKeeperClusterService"> <property name="id" value="camel-node-1"/> <property name="basePath" value="/camel/cluster"/> <property name="nodes" value="myzk:2181"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/spring" autoStartup="false"> </camelContext> </beans> camel.component.zookeeper.cluster.service.enabled = true camel.component.zookeeper.cluster.service.id = camel-node-1 camel.component.zookeeper.cluster.service.base-path = /camel/cluster camel.component.zookeeper.cluster.service.nodes = myzk:2181 <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-micrometer</artifactId> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>com.redhat.camel.springboot.platform</groupId> <artifactId>camel-spring-boot-bom</artifactId> <version>USD{camel-spring-boot-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> micrometer:[ counter | summary | timer ]:metricname[?options] micrometer:metricsType:metricsName @Configuration public static class MyConfig extends SingleRouteCamelConfiguration { @Bean @Override public RouteBuilder route() { return new RouteBuilder() { @Override public void configure() throws Exception { // define Camel routes here } }; } @Bean(name = MicrometerConstants.METRICS_REGISTRY_NAME) public MeterRegistry getMeterRegistry() { CompositeMeterRegistry registry = ...; registry.add(...); // return registry; } } @Override public void configure() { from("...") // Register the 'my-meter' meter in the MetricRegistry below .to("micrometer:meter:my-meter"); } @Produces // If multiple MetricRegistry beans // @Named(MicrometerConstants.METRICS_REGISTRY_NAME) MetricRegistry registry() { CompositeMeterRegistry registry = ...; registry.add(...); // return registry; } } from("direct:in") .setHeader(MicrometerConstants.HEADER_METRIC_NAME, constant("new.name")) .setHeader(MicrometerConstants.HEADER_METRIC_TAGS, constant(Tags.of("dynamic-key", "dynamic-value"))) .to("micrometer:counter:name.not.used?tags=key=value") .to("direct:out"); micrometer:counter:name[?options] // update counter simple.counter by 7 from("direct:in") .to("micrometer:counter:simple.counter?increment=7") .to("direct:out"); // increment counter simple.counter by 1 from("direct:in") .to("micrometer:counter:simple.counter") .to("direct:out"); // decrement counter simple.counter by 3 from("direct:in") .to("micrometer:counter:simple.counter?decrement=USD{header.X}") .to("direct:out"); from("direct:in") .setHeader(MicrometerConstants.HEADER_COUNTER_INCREMENT, constant(417.0D)) .to("micrometer:counter:simple.counter?increment=7") .to("direct:out"); from("direct:in") .setHeader(MicrometerConstants.HEADER_COUNTER_INCREMENT, simple("USD{body.length}")) .to("micrometer:counter:body.length") .to("direct:out"); micrometer:summary:metricname[?options] // adds value 9923 to simple.histogram from("direct:in") .to("micrometer:summary:simple.histogram?value=9923") .to("direct:out"); // nothing is added to simple.histogram; warning is logged from("direct:in") .to("micrometer:summary:simple.histogram") .to("direct:out"); from("direct:in") .to("micrometer:summary:simple.histogram?value=USD{header.X}") .to("direct:out"); // adds value 992.0 to simple.histogram from("direct:in") .setHeader(MicrometerConstants.HEADER_HISTOGRAM_VALUE, constant(992.0D)) .to("micrometer:summary:simple.histogram?value=700") .to("direct:out") micrometer:timer:metricname[?options] // measure time spent in route "direct:calculate" from("direct:in") .to("micrometer:timer:simple.timer?action=start") .to("direct:calculate") .to("micrometer:timer:simple.timer?action=stop"); // sets timer action using header from("direct:in") .setHeader(MicrometerConstants.HEADER_TIMER_ACTION, MicrometerTimerAction.start) .to("micrometer:timer:simple.timer") .to("direct:out"); context.addRoutePolicyFactory(new MicrometerRoutePolicyFactory()); <!-- use camel-micrometer route policy to gather metrics for all routes --> <bean id="metricsRoutePolicyFactory" class="org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyFactory"/> context.setMessageHistoryFactory(new MicrometerMessageHistoryFactory()); <!-- use camel-micrometer message history to gather metrics for all messages being routed --> <bean id="metricsMessageHistoryFactory" class="org.apache.camel.component.micrometer.messagehistory.MicrometerMessageHistoryFactory"/> MicrometerMessageHistoryService service = context.hasService(MicrometerMessageHistoryService.class); String json = service.dumpStatisticsAsJson(); camelContext.getManagementStrategy().addEventNotifier(new MicrometerExchangeEventNotifier()) MicrometerEventNotifierService service = context.hasService(MicrometerEventNotifierService.class); String json = service.dumpStatisticsAsJson(); <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-jmx</artifactId> <version>USD{micrometer-version}</version> </dependency> @Bean(name = MicrometerConstants.METRICS_REGISTRY_NAME) public MeterRegistry getMeterRegistry() { CompositeMeterRegistry meterRegistry = new CompositeMeterRegistry(); meterRegistry.add(...); meterRegistry.add(new JmxMeterRegistry( CamelJmxConfig.DEFAULT, Clock.SYSTEM, HierarchicalNameMapper.DEFAULT)); return meterRegistry; } } <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-minio-starter</artifactId> </dependency> minio://bucketName[?options] ?options=value&option2=value&... from("minio://helloBucket?accessKey=yourAccessKey&secretKey=yourSecretKey&prefix=hello.txt") .to("file:/var/downloaded"); minio:bucketName from("minio://MyBucket?minioClient=#client&delay=5000&maxMessagesPerPoll=5") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(MinioConstants.DESTINATION_BUCKET_NAME, "camelDestinationBucket"); exchange.getIn().setHeader(MinioConstants.OBJECT_NAME, "camelKey"); exchange.getIn().setHeader(MinioConstants.DESTINATION_OBJECT_NAME, "camelDestinationKey"); } }) .to("minio://mycamelbucket?minioClient=#minioClient&operation=copyObject") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(MinioConstants.OBJECT_NAME, "camelKey"); } }) .to("minio://mycamelbucket?minioClient=#minioClient&operation=deleteObject") .to("mock:result"); from("direct:start") .to("minio://mycamelbucket?minioClient=#minioClient&operation=listBuckets") .to("mock:result"); from("direct:start") .to("minio://mycamelbucket?minioClient=#minioClient&operation=deleteBucket") .to("mock:result"); from("direct:start") .to("minio://mycamelbucket?minioClient=#minioClient&operation=listObjects") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(MinioConstants.OBJECT_NAME, "camelKey"); } }) .to("minio://mycamelbucket?minioClient=#minioClient&operation=getObject") .to("mock:result"); from("direct:start").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(MinioConstants.OBJECT_NAME, "camelKey"); exchange.getIn().setHeader(MinioConstants.OFFSET, "0"); exchange.getIn().setHeader(MinioConstants.LENGTH, "9"); } }) .to("minio://mycamelbucket?minioClient=#minioClient&operation=getObjectRange") .to("mock:result"); from("minio://mycamelbucket?minioClient=#minioClient&moveAfterRead=true&destinationBucketName=myothercamelbucket") .to("mock:result"); from("direct:minio") .setBody(ListObjectsArgs.builder() .bucket(bucketName) .recursive(getConfiguration().isRecursive()))) .to("minio://test?minioClient=#minioClient&operation=listObjects&pojoRequest=true") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mllp-starter</artifactId> </dependency> mllp:hostname:port <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mock-starter</artifactId> </dependency> mock:someName[?options] mock:name MockEndpoint resultEndpoint = context.getEndpoint("mock:foo", MockEndpoint.class); // set expectations resultEndpoint.expectedMessageCount(2); // send some messages // now lets assert that the mock:foo endpoint received 2 messages resultEndpoint.assertIsSatisfied(); MockEndpoint resultEndpoint = context.getEndpoint("mock:foo", MockEndpoint.class); resultEndpoint.setAssertPeriod(5000); resultEndpoint.expectedMessageCount(2); // send some messages // now lets assert that the mock:foo endpoint received 2 messages resultEndpoint.assertIsSatisfied(); resultEndpoint.expectedBodiesReceived("firstMessageBody", "secondMessageBody", "thirdMessageBody"); resultEndpoint.message(0).header("foo").isEqualTo("bar"); @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId("start") .to("direct:foo").to("log:foo").to("mock:result"); from("direct:foo").routeId("foo") .transform(constant("Bye World")); } }; } @Test public void testAdvisedMockEndpoints() throws Exception { // advice the start route using the inlined AdviceWith lambda style route builder // which has extended capabilities than the regular route builder AdviceWith.adviceWith(context, "start", a -> // mock all endpoints a.mockEndpoints()); getMockEndpoint("mock:direct:start").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:direct:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // additional test to ensure correct endpoints in registry assertNotNull(context.hasEndpoint("direct:start")); assertNotNull(context.hasEndpoint("direct:foo")); assertNotNull(context.hasEndpoint("log:foo")); assertNotNull(context.hasEndpoint("mock:result")); // all the endpoints was mocked assertNotNull(context.hasEndpoint("mock:direct:start")); assertNotNull(context.hasEndpoint("mock:direct:foo")); assertNotNull(context.hasEndpoint("mock:log:foo")); } INFO Adviced endpoint [direct://foo] with mock endpoint [mock:direct:foo] @Test public void testAdvisedMockEndpointsWithPattern() throws Exception { // advice the start route using the inlined AdviceWith lambda style route builder // which has extended capabilities than the regular route builder AdviceWith.adviceWith(context, "start", a -> // mock only log endpoints a.mockEndpoints("log*")); // now we can refer to log:foo as a mock and set our expectations getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // additional test to ensure correct endpoints in registry assertNotNull(context.hasEndpoint("direct:start")); assertNotNull(context.hasEndpoint("direct:foo")); assertNotNull(context.hasEndpoint("log:foo")); assertNotNull(context.hasEndpoint("mock:result")); // only the log:foo endpoint was mocked assertNotNull(context.hasEndpoint("mock:log:foo")); assertNull(context.hasEndpoint("mock:direct:start")); assertNull(context.hasEndpoint("mock:direct:foo")); } public class IsMockEndpointsJUnit4Test extends CamelTestSupport { @Override public String isMockEndpoints() { // override this method and return the pattern for which endpoints to mock. // use * to indicate all return "*"; } @Test public void testMockAllEndpoints() throws Exception { // notice we have automatic mocked all endpoints and the name of the endpoints is "mock:uri" getMockEndpoint("mock:direct:start").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:direct:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // additional test to ensure correct endpoints in registry assertNotNull(context.hasEndpoint("direct:start")); assertNotNull(context.hasEndpoint("direct:foo")); assertNotNull(context.hasEndpoint("log:foo")); assertNotNull(context.hasEndpoint("mock:result")); // all the endpoints was mocked assertNotNull(context.hasEndpoint("mock:direct:start")); assertNotNull(context.hasEndpoint("mock:direct:foo")); assertNotNull(context.hasEndpoint("mock:log:foo")); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("direct:foo").to("log:foo").to("mock:result"); from("direct:foo").transform(constant("Bye World")); } }; } } <!-- this camel route is in the camel-route.xml file --> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start"/> <to uri="direct:foo"/> <to uri="log:foo"/> <to uri="mock:result"/> </route> <route> <from uri="direct:foo"/> <transform> <constant>Bye World</constant> </transform> </route> </camelContext> <!-- the Camel route is defined in another XML file --> <import resource="camel-route.xml"/> <!-- bean which enables mocking all endpoints --> <bean id="mockAllEndpoints" class="org.apache.camel.component.mock.InterceptSendToMockEndpointStrategy"/> <bean id="mockAllEndpoints" class="org.apache.camel.impl.InterceptSendToMockEndpointStrategy"> <constructor-arg index="0" value="log*"/> </bean> @Test public void testAdvisedMockEndpointsWithSkip() throws Exception { // advice the first route using the inlined AdviceWith route builder // which has extended capabilities than the regular route builder AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { // mock sending to direct:foo and direct:bar and skip send to it mockEndpointsAndSkip("direct:foo", "direct:bar"); } }); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:direct:foo").expectedMessageCount(1); getMockEndpoint("mock:direct:bar").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the message was not send to the direct:foo route and thus not sent to // the seda endpoint SedaEndpoint seda = context.getEndpoint("seda:foo", SedaEndpoint.class); assertEquals(0, seda.getCurrentQueueSize()); } public class IsMockEndpointsAndSkipJUnit4Test extends CamelTestSupport { @Override public String isMockEndpointsAndSkip() { // override this method and return the pattern for which endpoints to mock, // and skip sending to the original endpoint. return "direct:foo"; } @Test public void testMockEndpointAndSkip() throws Exception { // notice we have automatic mocked the direct:foo endpoints and the name of the endpoints is "mock:uri" getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:direct:foo").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the message was not send to the direct:foo route and thus not sent to the seda endpoint SedaEndpoint seda = context.getEndpoint("seda:foo", SedaEndpoint.class); assertEquals(0, seda.getCurrentQueueSize()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("direct:foo").to("mock:result"); from("direct:foo").transform(constant("Bye World")).to("seda:foo"); } }; } } MockEndpoint mock = getMockEndpoint("mock:data"); mock.setRetainFirst(5); mock.setRetainLast(5); mock.expectedMessageCount(2000); mock.assertIsSatisfied(); Date time = exchange.getProperty(Exchange.RECEIVED_TIMESTAMP, Date.class); mock.message(0).arrives().noLaterThan(2).seconds().beforeNext(); mock.message(1).arrives().noLaterThan(2).seconds().afterPrevious(); mock.message(1).arrives().between(1, 4).seconds().afterPrevious(); mock.allMessages().arrives().noLaterThan(1).seconds().beforeNext(); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mongodb-starter</artifactId> </dependency> mongodb:connectionBean?database=databaseName&collection=collectionName&operation=operationName[&moreOptions...] mongodb:connectionBean <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <mongo:mongo-client id="mongoBean" host="USD{mongo.url}" port="USD{mongo.port}" credentials="USD{mongo.user}:USD{mongo.pass}@USD{mongo.dbname}"> <mongo:client-options write-concern="NORMAL" /> </mongo:mongo-client> </beans> <route> <from uri="direct:start" /> <!-- using bean 'mongoBean' defined above --> <to uri="mongodb:mongoBean?database=USD{mongodb.database}&amp;collection=USD{mongodb.collection}&amp;operation=getDbStats" /> <to uri="direct:result" /> </route> from("direct:findById") .to("mongodb:myDb?database=flights&collection=tickets&operation=findById") .to("mock:resultFindById"); from("direct:findById") .convertBodyTo(ObjectId.class) .to("mongodb:myDb?database=flights&collection=tickets&operation=findById") .to("mock:resultFindById"); from("direct:findOneByQuery") .to("mongodb:myDb?database=flights&collection=tickets&operation=findOneByQuery") .to("mock:resultFindOneByQuery"); from("direct:findOneByQuery") .setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("name", "Raul Kripalani"))) .to("mongodb:myDb?database=flights&collection=tickets&operation=findOneByQuery") .to("mock:resultFindOneByQuery"); from("direct:findAll") .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll") .to("mock:resultFindAll"); from("direct:findAll") .setHeader(MongoDbConstants.CRITERIA, Filters.eq("name", "Raul Kripalani")) .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll") .to("mock:resultFindAll"); from("direct:findAll") .setHeader(MongoDbConstants.BATCH_SIZE).constant(10) .setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("name", "Raul Kripalani"))) .to("mongodb:myDb?database=flights&collection=tickets&operation=findAll&outputType=MongoIterable") .to("mock:resultFindAll"); // from("direct:count").to("mongodb:myDb?database=tickets&collection=flights&operation=count&dynamicity=true"); Long result = template.requestBodyAndHeader("direct:count", "irrelevantBody", MongoDbConstants.COLLECTION, "dynamicCollectionName"); assertTrue("Result is not of type Long", result instanceof Long); Document query = Long count = template.requestBodyAndHeader("direct:count", query, MongoDbConstants.COLLECTION, "dynamicCollectionName"); // route: from("direct:findAll").to("mongodb:myDb?database=flights&collection=tickets&operation=findAll") Bson fieldProjection = Projection.exclude("_id", "boringField"); Object result = template.requestBodyAndHeader("direct:findAll", ObjectUtils.NULL, MongoDbConstants.FIELDS_PROJECTION, fieldProjection); // route: from("direct:findAll").to("mongodb:myDb?database=flights&collection=tickets&operation=findAll") Bson fieldProjection = Projection.exclude("_id", "boringField"); Object result = template.requestBodyAndHeader("direct:findAll", ObjectUtils.NULL, MongoDbConstants.FIELDS_PROJECTION, fieldProjection); // route: from("direct:findAll").to("mongodb:myDb?database=flights&collection=tickets&operation=findAll") Bson sorts = Sorts.descending("_id"); Object result = template.requestBodyAndHeader("direct:findAll", ObjectUtils.NULL, MongoDbConstants.SORT_BY, sorts); .from("direct:someTriggeringEvent") .setHeader(MongoDbConstants.SORT_BY).constant(Sorts.descending("documentTimestamp")) .setHeader(MongoDbConstants.FIELDS_PROJECTION).constant(Projection.include("documentTimestamp")) .setBody().constant("{}") .to("mongodb:myDb?database=local&collection=myDemoCollection&operation=findOneByQuery") .to("direct:aMyBatisParameterizedSelect"); from("direct:insert") .to("mongodb:myDb?database=flights&collection=tickets&operation=insert"); from("direct:insert") .to("mongodb:myDb?database=flights&collection=tickets&operation=save"); // route: from("direct:insert").to("mongodb:myDb?database=flights&collection=tickets&operation=save"); org.bson.Document docForSave = new org.bson.Document(); docForSave.put("key", "value"); Object result = template.requestBody("direct:insert", docForSave); // route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update"); List<Bson> body = new ArrayList<>(); Bson filterField = Filters.eq("filterField", true); body.add(filterField); BsonDocument updateObj = new BsonDocument().append("USDset", new BsonDocument("scientist", new BsonString("Darwin"))); body.add(updateObj); Object result = template.requestBodyAndHeader("direct:update", body, MongoDbConstants.MULTIUPDATE, true); // route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update"); Maps<String, Object> headers = new HashMap<>(2); headers.add(MongoDbConstants.MULTIUPDATE, true); headers.add(MongoDbConstants.FIELDS_FILTER, Filters.eq("filterField", true)); String updateObj = Updates.set("scientist", "Darwin");; Object result = template.requestBodyAndHeaders("direct:update", updateObj, headers); // route: from("direct:update").to("mongodb:myDb?database=science&collection=notableScientists&operation=update"); String updateObj = "[{\"filterField\": true}, {\"USDset\", {\"scientist\", \"Darwin\"}}]"; Object result = template.requestBodyAndHeader("direct:update", updateObj, MongoDbConstants.MULTIUPDATE, true); // route: from("direct:remove").to("mongodb:myDb?database=science&collection=notableScientists&operation=remove"); Bson conditionField = Filters.eq("conditionField", true); Object result = template.requestBody("direct:remove", conditionField); // route: from("direct:bulkWrite").to("mongodb:myDb?database=science&collection=notableScientists&operation=bulkWrite"); List<WriteModel<Document>> bulkOperations = Arrays.asList( new InsertOneModel<>(new Document("scientist", "Pierre Curie")), new UpdateOneModel<>(new Document("_id", "5"), new Document("USDset", new Document("scientist", "Marie Curie"))), new DeleteOneModel<>(new Document("_id", "3"))); BulkWriteResult result = template.requestBody("direct:bulkWrite", bulkOperations, BulkWriteResult.class); // route: from("direct:aggregate").to("mongodb:myDb?database=science&collection=notableScientists&operation=aggregate"); List<Bson> aggregate = Arrays.asList(match(or(eq("scientist", "Darwin"), eq("scientist", group("USDscientist", sum("count", 1))); from("direct:aggregate") .setBody().constant(aggregate) .to("mongodb:myDb?database=science&collection=notableScientists&operation=aggregate") .to("mock:resultAggregate"); List<Bson> aggregate = Arrays.asList(match(or(eq("scientist", "Darwin"), eq("scientist", group("USDscientist", sum("count", 1))); from("direct:aggregate") .setHeader(MongoDbConstants.BATCH_SIZE).constant(10) .setBody().constant(aggregate) .to("mongodb:myDb?database=science&collection=notableScientists&operation=aggregate&outputType=MongoIterable") .split(body()) .streaming() .to("mock:resultAggregate"); > db.stats(); { "db" : "test", "collections" : 7, "objects" : 719, "avgObjSize" : 59.73296244784423, "dataSize" : 42948, "storageSize" : 1000058880, "numExtents" : 9, "indexes" : 4, "indexSize" : 32704, "fileSize" : 1275068416, "nsSizeMB" : 16, "ok" : 1 } // from("direct:getDbStats").to("mongodb:myDb?database=flights&collection=tickets&operation=getDbStats"); Object result = template.requestBody("direct:getDbStats", "irrelevantBody"); assertTrue("Result is not of type Document", result instanceof Document); > db.camelTest.stats(); { "ns" : "test.camelTest", "count" : 100, "size" : 5792, "avgObjSize" : 57.92, "storageSize" : 20480, "numExtents" : 2, "nindexes" : 1, "lastExtentSize" : 16384, "paddingFactor" : 1, "flags" : 1, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1 } // from("direct:getColStats").to("mongodb:myDb?database=flights&collection=tickets&operation=getColStats"); Object result = template.requestBody("direct:getColStats", "irrelevantBody"); assertTrue("Result is not of type Document", result instanceof Document); // route: from("command").to("mongodb:myDb?database=science&operation=command"); DBObject commandBody = new BasicDBObject("hostInfo", "1"); Object result = template.requestBody("direct:command", commandBody); // from("direct:insert").to("mongodb:myDb?database=flights&collection=tickets&operation=insert"); Object result = template.requestBodyAndHeader("direct:insert", "irrelevantBody", MongoDbConstants.OPERATION_HEADER, "count"); assertTrue("Result is not of type Long", result instanceof Long); from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime") .id("tailableCursorConsumer1") .autoStartup(false) .to("mock:test"); from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime&persistentTailTracking=true" + "&persistentId=cancellationsTracker") .id("tailableCursorConsumer2") .autoStartup(false) .to("mock:test"); from("mongodb:myDb?database=flights&collection=cancellations&tailTrackIncreasingField=departureTime&persistentTailTracking=true" + "&persistentId=cancellationsTracker&tailTrackDb=trackers&tailTrackCollection=camelTrackers" + "&tailTrackField=lastProcessedDepartureTime") .id("tailableCursorConsumer3") .autoStartup(false) .to("mock:test"); <route id="filterConsumer"> <from uri="mongodb:myDb?consumerType=changeStreams&amp;database=flights&amp;collection=tickets&amp;streamFilter={ 'USDmatch':{'USDor':[{'fullDocument.stringValue': 'specificValue'}]} }"/> <to uri="mock:test"/> </route> from("mongodb:myDb?consumerType=changeStreams&database=flights&collection=tickets&streamFilter={ 'USDmatch':{'USDor':[{'fullDocument.stringValue': 'specificValue'}]} }") .to("mock:test"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-mybatis-starter</artifactId> </dependency> mybatis:statementName[?options] mybatis:statement from("activemq:queue:newAccount") .to("mybatis:insertAccount?statementType=Insert"); <!-- Insert example, using the Account parameter class --> <insert id="insertAccount" parameterType="Account"> insert into ACCOUNT ( ACC_ID, ACC_FIRST_NAME, ACC_LAST_NAME, ACC_EMAIL ) values ( #{id}, #{firstName}, #{lastName}, #{emailAddress} ) </insert> <update id="batchUpdateAccount" parameterType="java.util.Map"> update ACCOUNT set ACC_EMAIL = #{emailAddress} where ACC_ID in <foreach item="Account" collection="list" open="(" close=")" separator=","> #{Account.id} </foreach> </update> from("direct:start") .to("mybatis:batchUpdateAccount?statementType=UpdateList") .to("mock:result"); <delete id="batchDeleteAccountById" parameterType="java.util.List"> delete from ACCOUNT where ACC_ID in <foreach item="AccountID" collection="list" open="(" close=")" separator=","> #{AccountID} </foreach> </delete> from("direct:start") .to("mybatis:batchDeleteAccount?statementType=DeleteList") .to("mock:result"); from("mybatis:selectAllAccounts?delay=60000") .to("activemq:queue:allAccounts"); from("timer://pollTheDatabase?delay=30000") .to("mybatis:selectAllAccounts") .to("activemq:queue:allAccounts"); <!-- Select with no parameters using the result map for Account class. --> <select id="selectAllAccounts" resultMap="AccountResult"> select * from ACCOUNT </select> <bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"> <constructor-arg> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="org.postgresql.Driver"/> <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/myDatabase"/> <property name="user" value="myUser"/> <property name="password" value="myPassword"/> </bean> </constructor-arg> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- standard mybatis config file --> <property name="configLocation" value="/META-INF/SqlMapConfig.xml"/> <!-- externalised mappers --> <property name="mapperLocations" value="classpath*:META-INF/mappers/**/*.xml"/> </bean> <bean id="mybatis" class="org.apache.camel.component.mybatis.MyBatisComponent"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <bean id="PROPAGATION_REQUIRED" class="org.apache.camel.spring.spi.SpringTransactionPolicy"> <property name="transactionManager" ref="txManager"/> <property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/> </bean> <camelContext id="my-model-context" xmlns="http://camel.apache.org/schema/spring"> <route id="insertModel"> <from uri="direct:insert"/> <transacted ref="PROPAGATION_REQUIRED"/> <to uri="mybatis:myModel.insert?statementType=Insert"/> </route> </camelContext> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.0</version> </dependency> #application.properties camel.component.mybatis.sql-session-factory=#sqlSessionFactory <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-netty-starter</artifactId> </dependency> netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] netty:protocol://host:port @BindToRegistry("decoder") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from("netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody("Message received); } } } }; RouteBuilder builder = new RouteBuilder() { public void configure() { from("netty:tcp://0.0.0.0:5150") .to("mock:result"); } }; KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("/users/home/server/keystore.jks"); ksp.setPassword("keystorePassword"); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword("keyPassword"); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent("netty", NettyComponent.class); nettyComponent.setSslContextParameters(scp); <camel:sslContextParameters id="sslContextParameters"> <camel:keyManagers keyPassword="keyPassword"> <camel:keyStore resource="/users/home/server/keystore.jks" password="keystorePassword"/> </camel:keyManagers> </camel:sslContextParameters> <to uri="netty:tcp://0.0.0.0:5150?sync=true&ssl=true&sslContextParameters=#sslContextParameters"/> Registry registry = context.getRegistry(); registry.bind("password", "changeit"); registry.bind("ksf", new File("src/test/resources/keystore.jks")); registry.bind("tsf", new File("src/test/resources/keystore.jks")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = "netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password" + "&keyStoreFile=#ksf&trustStoreFile=#tsf"; String return_string = "When You Go Home, Tell Them Of Us And Say," + "For Your Tomorrow, We Gave Our Today."; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind("length-decoder", lengthDecoder); registry.bind("string-decoder", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind("length-encoder", lengthEncoder); registry.bind("string-encoder", stringEncoder); List<ChannelHandler> decoders = new ArrayList<ChannelHandler>(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List<ChannelHandler> encoders = new ArrayList<ChannelHandler>(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind("encoders", encoders); registry.bind("decoders", decoders); <util:list id="decoders" list-class="java.util.LinkedList"> <bean class="org.apache.camel.component.netty.ChannelHandlerFactories" factory-method="newLengthFieldBasedFrameDecoder"> <constructor-arg value="1048576"/> <constructor-arg value="0"/> <constructor-arg value="4"/> <constructor-arg value="0"/> <constructor-arg value="4"/> </bean> <bean class="io.netty.handler.codec.string.StringDecoder"/> </util:list> <util:list id="encoders" list-class="java.util.LinkedList"> <bean class="io.netty.handler.codec.LengthFieldPrepender"> <constructor-arg value="4"/> </bean> <bean class="io.netty.handler.codec.string.StringEncoder"/> </util:list> <bean id="length-encoder" class="io.netty.handler.codec.LengthFieldPrepender"> <constructor-arg value="4"/> </bean> <bean id="string-encoder" class="io.netty.handler.codec.string.StringEncoder"/> <bean id="length-decoder" class="org.apache.camel.component.netty.ChannelHandlerFactories" factory-method="newLengthFieldBasedFrameDecoder"> <constructor-arg value="1048576"/> <constructor-arg value="0"/> <constructor-arg value="4"/> <constructor-arg value="0"/> <constructor-arg value="4"/> </bean> <bean id="string-decoder" class="io.netty.handler.codec.string.StringDecoder"/> from("direct:multiple-codec").to("netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false"); from("netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false").to("mock:multiple-codec"); <camelContext id="multiple-netty-codecs-context" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:multiple-codec"/> <to uri="netty:tcp://0.0.0.0:5150?encoders=#encoders&amp;sync=false"/> </route> <route> <from uri="netty:tcp://0.0.0.0:5150?decoders=#length-decoder,#string-decoder&amp;sync=false"/> <to uri="mock:multiple-codec"/> </route> </camelContext> from("netty:tcp://0.0.0.0:8080").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody("Bye " + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast("handler", new ServerChannelHandler(consumer)); } } Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind("spf", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = "netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf" String return_string = "When You Go Home, Tell Them Of Us And Say," + "For Your Tomorrow, We Gave Our Today."; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); <!-- use the worker pool builder to help create the shared thread pool --> <bean id="poolBuilder" class="org.apache.camel.component.netty.NettyWorkerPoolBuilder"> <property name="workerCount" value="2"/> </bean> <!-- the shared worker thread pool --> <bean id="sharedPool" class="org.jboss.netty.channel.socket.nio.WorkerPool" factory-bean="poolBuilder" factory-method="build" destroy-method="shutdown"> </bean> <route> <from uri="netty:tcp://0.0.0.0:5021?textline=true&amp;sync=true&amp;workerPool=#sharedPool&amp;usingExecutorService=false"/> <to uri="log:result"/> </route> <route> <from uri="netty:tcp://0.0.0.0:5022?textline=true&amp;sync=true&amp;workerPool=#sharedPool&amp;usingExecutorService=false"/> <to uri="log:result"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-netty-http-starter</artifactId> </dependency> netty-http:http://0.0.0.0:8080[?options] netty-http:protocol://host:port/path io.netty.handler.codec.http.HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest(); from("netty-http:http://0.0.0.0:8080/foo") .transform().constant("Bye World"); String out = template.requestBody("netty-http:http://0.0.0.0:8080/foo", "Hello World", String.class); System.out.println(out); from("netty-http:http://0.0.0.0:8123/foo").to("mock:foo"); from("netty-http:http://0.0.0.0:8123/foo?matchOnUriPrefix=true").to("mock:foo"); from("netty-http:http://0.0.0.0:8123?matchOnUriPrefix=true").to("mock:foo"); from("netty-http:http://0.0.0.0:{{port}}/foo") .to("mock:foo") .transform().constant("Bye World"); from("netty-http:http://0.0.0.0:{{port}}/bar") .to("mock:bar") .transform().constant("Bye Camel"); from("netty-http:http://0.0.0.0:{{port}}/foo") .to("mock:foo") .transform().constant("Bye World"); // we cannot have a 2nd route on same port with SSL enabled, when the 1st route is NOT from("netty-http:http://0.0.0.0:{{port}}/bar?ssl=true") .to("mock:bar") .transform().constant("Bye Camel"); <bean id="nettyHttpBootstrapOptions" class="org.apache.camel.component.netty.NettyServerBootstrapConfiguration"> <property name="backlog" value="200"/> <property name="connectionTimeout" value="20000"/> <property name="workerCount" value="16"/> </bean> <route> <from uri="netty-http:http://0.0.0.0:{{port}}/foo?bootstrapConfiguration=#nettyHttpBootstrapOptions"/> </route> <route> <from uri="netty-http:http://0.0.0.0:{{port}}/bar?bootstrapConfiguration=#nettyHttpBootstrapOptions"/> </route> <route> <from uri="netty-http:http://0.0.0.0:{{port}}/beer?bootstrapConfiguration=#nettyHttpBootstrapOptions"/> </route> from("netty-http:proxy://0.0.0.0:8080") .toD("netty-http:" + "USD{headers." + Exchange.HTTP_SCHEME + "}://" + "USD{headers." + Exchange.HTTP_HOST + "}:" + "USD{headers." + Exchange.HTTP_PORT + "}") .process(this::processResponse); void processResponse(final Exchange exchange) { final NettyHttpMessage message = exchange.getIn(NettyHttpMessage.class); final FullHttpResponse response = message.getHttpResponse(); final ByteBuf buf = response.content(); final String string = buf.toString(StandardCharsets.UTF_8); buf.resetWriterIndex(); ByteBufUtil.writeUtf8(buf, string.toUpperCase(Locale.US)); } <route> <from uri="netty-http:http://0.0.0.0:{{port}}/foo?securityConfiguration.realm=karaf"/> </route> <bean id="constraint" class="org.apache.camel.component.netty.http.SecurityConstraintMapping"> <!-- inclusions defines url -> roles restrictions --> <!-- a * should be used for any role accepted (or even no roles) --> <property name="inclusions"> <map> <entry key="/*" value="*"/> <entry key="/admin/*" value="admin"/> <entry key="/guest/*" value="admin,guest"/> </map> </property> <!-- exclusions is used to define public urls, which requires no authentication --> <property name="exclusions"> <set> <value>/public/*</value> </set> </property> </bean> <route> <from uri="netty-http:http://0.0.0.0:{{port}}/foo?matchOnUriPrefix=true&amp;securityConfiguration.realm=karaf&amp;securityConfiguration.securityConstraint=#constraint"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-olingo4-starter</artifactId> </dependency> olingo4://endpoint/<resource-path>?[options] olingo4:apiName/methodName olingo4:apiName/methodName olingo4:DEFAULT/methodName?[parameters] from("direct:...") .setHeader("CamelOlingo4.USDtop", "5"); .to("olingo4://read/People?orderBy=FirstName%20asc"); from("direct:...") .setHeader("CamelOlingo4.keyPredicate", header("id")) .to("olingo4://read/Airports"); from("direct:...") .to("olingo4://create/People"); from("direct:...") .to("olingo4://action/People"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-openapi-java-starter</artifactId> </dependency> public class UserRouteBuilder extends RouteBuilder { @Override public void configure() throws Exception { // configure we want to use servlet as the component for the rest DSL // and we enable json binding mode restConfiguration().component("netty-http").bindingMode(RestBindingMode.json) // and output using pretty print .dataFormatProperty("prettyPrint", "true") // setup context path and port number that netty will use .contextPath("/").port(8080) // add OpenApi api-doc out of the box .apiContextPath("/api-doc") .apiProperty("api.title", "User API").apiProperty("api.version", "1.2.3") // and enable CORS .apiProperty("cors", "true"); // this user REST service is json only rest("/user").description("User rest service") .consumes("application/json").produces("application/json") .get("/{id}").description("Find user by id").outType(User.class) .param().name("id").type(path).description("The id of the user to get").dataType("int").endParam() .to("bean:userService?method=getUser(USD{header.id})") .put().description("Updates or create a user").type(User.class) .param().name("body").type(body).description("The user to update or create").endParam() .to("bean:userService?method=updateUser") .get("/findAll").description("Find all users").outType(User[].class) .to("bean:userService?method=listUsers"); } } rest("/user").tag("dude").description("User rest service") // setup security definitions .securityDefinitions() .oauth2("petstore_auth").authorizationUrl("http://petstore.swagger.io/oauth/dialog").end() .apiKey("api_key").withHeader("myHeader").end() .end() .consumes("application/json").produces("application/json") .get("/{id}/{date}").description("Find user by id and date").outType(User.class) .security("api_key") .put().description("Updates or create a user").type(User.class) .security("petstore_auth", "write:pets,read:pets") restConfiguration().component("netty-http") .useXForwardHeaders(false) .apiProperty("schemes", "https"); .host("localhost") .port(8080); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-opensearch-starter</artifactId> </dependency> opensearch://clusterName[?options] opensearch:clusterName OpensearchComponent opensearchComponent = new OpensearchComponent(); opensearchComponent.setHostAddresses("opensearch-host:9200"); camelContext.addComponent("opensearch", opensearchComponent); OpenSearchComponent opensearchComponent = new OpenSearchComponent(); opensearchComponent.setHostAddresses("opensearch-host:9200"); opensearchComponent.setUser("opensearchuser"); opensearchComponent.setPassword("secure!!"); camelContext.addComponent("opensearch", opensearchComponent); from("direct:index") .to("opensearch://opensearch?operation=Index&indexName=twitter"); <route> <from uri="direct:index"/> <to uri="opensearch://opensearch?operation=Index&amp;indexName=twitter"/> </route> Map<String, String> map = new HashMap<String, String>(); map.put("content", "test"); String indexId = template.requestBody("direct:index", map, String.class); from("direct:search") .to("opensearch://opensearch?operation=Search&indexName=twitter"); <route> <from uri="direct:search"/> <to uri="opensearch://opensearch?operation=Search&amp;indexName=twitter"/> </route> String query = "{\"query\":{\"match\":{\"doc.content\":\"new release of ApacheCamel\"}}}"; HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); Map<String, Object> actualQuery = new HashMap<>(); actualQuery.put("doc.content", "new release of ApacheCamel"); Map<String, Object> match = new HashMap<>(); match.put("match", actualQuery); Map<String, Object> query = new HashMap<>(); query.put("query", match); HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); from("direct:search") .to("opensearch://opensearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"); <route> <from uri="direct:search"/> <to uri="opensearch://opensearch?operation=Search&amp;indexName=twitter&amp;useScroll=true&amp;scrollKeepAliveMs=30000"/> </route> String query = "{\"query\":{\"match\":{\"doc.content\":\"new release of ApacheCamel\"}}}"; try (OpenSearchScrollRequestIterator response = template.requestBody("direct:search", query, OpenSearchScrollRequestIterator.class)) { // do something smart with results } from("direct:search") .to("opensearch://opensearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000") .split() .body() .streaming() .to("mock:output") .end(); from("direct:multiSearch") .to("opensearch://opensearch?operation=MultiSearch"); <route> <from uri="direct:multiSearch"/> <to uri="opensearch://opensearch?operation=MultiSearch"/> </route> MsearchRequest.Builder builder = new MsearchRequest.Builder().index("twitter").searches( new RequestItem.Builder().header(new MultisearchHeader.Builder().build()) .body(new MultisearchBody.Builder().query(b -> b.matchAll(x -> x)).build()).build(), new RequestItem.Builder().header(new MultisearchHeader.Builder().build()) .body(new MultisearchBody.Builder().query(b -> b.matchAll(x -> x)).build()).build()); List<MultiSearchResponseItem<?>> response = template.requestBody("direct:multiSearch", builder, List.class); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-opentelemetry-starter</artifactId> </dependency> import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Tracer; OpenTelemetryTracer otelTracer = new OpenTelemetryTracer(); // By default it uses the DefaultTracer, but you can override it with a specific OpenTelemetry Tracer implementation. otelTracer.setTracer(...); // And then initialize the context otelTracer.init(camelContext); import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Tracer; @Configuration public class CamelOtelConfiguration { public CamelOtelConfiguration(CamelContext camelContext, OpenTelemetryTracer tracer) { var strategy = new OpenTelemetryTracingStrategy(tracer); tracer.setTracingStrategy(strategy); camelContext.getCamelContextExtension().addInterceptStrategy(strategy); } } camel: opentelemetry: exclude-patterns: - ## Set some ID here to filter ## java -javaagent:path/to/opentelemetry-javaagent.jar -jar myapp.jar java -javaagent:path/to/opentelemetry-javaagent.jar -Dotel.service.name=your-service-name -Dotel.traces.exporter=jaeger -jar myapp.jar import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.tracing.SpanAdapter; import org.apache.camel.tracing.decorators.DirectSpanDecorator; public class RouteIDSpanDecorator extends DirectSpanDecorator { @Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { super.pre(span, exchange, endpoint); span.setTag("camel.route.id", exchange.getFromRouteId()); } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-paho-starter</artifactId> </dependency> paho:topic[?options] paho:topic // Receive payload byte[] payload = (byte[]) consumerTemplate.receiveBody("paho:topic"); // Send payload byte[] payload = "message".getBytes(); producerTemplate.sendBody("paho:topic", payload); // Receive payload String payload = consumerTemplate.receiveBody("paho:topic", String.class); // Send payload String payload = "message"; producerTemplate.sendBody("paho:topic", payload); from("paho:some/queue") .to("mock:test"); from("direct:test") .to("paho:some/target/queue"); from("paho:some/queue?brokerUrl=tcp://iot.eclipse.org:1883") .to("mock:test"); from("direct:test") .setHeader(PahoConstants.CAMEL_PAHO_OVERRIDE_TOPIC, simple("USD{header.customerId}")) .to("paho:some/target/queue"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-paho-mqtt5-starter</artifactId> </dependency> paho-mqtt5:topic[?options] paho-mqtt5:topic // Receive payload byte[] payload = (byte[]) consumerTemplate.receiveBody("paho:topic"); // Send payload byte[] payload = "message".getBytes(); producerTemplate.sendBody("paho:topic", payload); // Receive payload String payload = consumerTemplate.receiveBody("paho:topic", String.class); // Send payload String payload = "message"; producerTemplate.sendBody("paho:topic", payload); from("paho:some/queue") .to("mock:test"); from("direct:test") .to("paho:some/target/queue"); from("paho:some/queue?brokerUrl=tcp://iot.eclipse.org:1883") .to("mock:test"); from("direct:test") .setHeader(PahoConstants.CAMEL_PAHO_OVERRIDE_TOPIC, simple("USD{header.customerId}")) .to("paho:some/target/queue"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-platform-http-starter</artifactId> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-platform-http-vertx</artifactId> <version>4.8.3.redhat-00004</version> <!-- use the same version as your Camel core version --> </dependency> platform-http:path from("kafka:topic"). unmarshal().protobuf(ProtobufLibrary.Jackson, JsonNode.class). to("log:info"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jackson-protobuf-starter</artifactId> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-quartz-starter</artifactId> </dependency> quartz://timerName?options quartz://groupName/timerName?options quartz://groupName/timerName?cron=expression quartz://timerName?cron=expression quartz:groupName/triggerName <bean id="quartz" class="org.apache.camel.component.quartz.QuartzComponent"> <property name="propertiesFile" value="com/mycompany/myquartz.properties"/> </bean> <bean id="quartz" class="org.apache.camel.component.quartz.QuartzComponent"> <property name="startDelayedSeconds" value="5"/> </bean> from("quartz://myGroup/myTimerName?cron=0+0/5+12-18+?+*+MON-FRI") .to("activemq:Totally.Rocks"); 0 0/5 12-18 ? * MON-FRI quartz://groupName/timerName?cron=0+0/5+12-18+?+*+MON-FRI&trigger.timeZone=Europe/Stockholm quartz://myGroup/myTimerName?trigger.repeatInterval=2000&trigger.misfireInstruction=4 quartz://myGroup/myTimerName?cron=0/2+*+*+*+*+?&trigger.misfireInstruction=2 from("file:inbox?scheduler=quartz&scheduler.cron=0/2+*+*+*+*+?") .to("bean:process"); from("file:inbox?scheduler=quartz&scheduler.cron=0/2+*+*+*+*+?&scheduler.triggerId=myId&scheduler.triggerGroup=myGroup") .to("bean:process"); from("file:inbox?scheduler=spring&scheduler.cron=0/2+*+*+*+*+?") .to("bean:process"); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-cron</artifactId> <version>{CamelSBVersion}</version> <!-- use the same version as your Camel core version --> </dependency> from("cron://name?schedule=0+0/5+12-18+?+*+MON-FRI") .to("activemq:Totally.Rocks"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-ref-starter</artifactId> </dependency> ref:someName[?options] ref:name // lookup the endpoint String myEndpointRef = "bigspenderOrder"; Endpoint endpoint = context.getEndpoint("ref:" + myEndpointRef); Producer producer = endpoint.createProducer(); Exchange exchange = producer.createExchange(); exchange.getIn().setBody(payloadToSend); // send the exchange producer.process(exchange); <camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring"> <endpoint id="normalOrder" uri="activemq:order.slow"/> <endpoint id="bigspenderOrder" uri="activemq:order.high"/> </camelContext> <to uri="ref:endpoint2"/> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> <bean id="myExpression" class="com.mycompany.MyCustomExpression"/> <route> <from uri="seda:a"/> <split> <ref>myExpression</ref> <to uri="mock:b"/> </split> </route> from("seda:a").split().ref("myExpression").to("seda:b"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-rest-starter</artifactId> </dependency> rest://method:path[:uriTemplate]?[options] rest:method:path:uriTemplate from("rest:get:hello") .transform().constant("Bye World"); from("rest:get:hello/{me}") .transform().simple("Bye USD{header.me}"); from("rest:get:hello:/{me}") .transform().simple("Hi USD{header.me}"); from("rest:get:hello:/french/{me}") .transform().simple("Bonjour USD{header.me}"); from("direct:start") .to("rest:get:hello/{me}"); template.sendBodyAndHeader("direct:start", null, "me", "Donald Duck"); from("direct:start") .to("rest:get:hello/{me}?host=myserver:8080/foo"); restConfiguration().host("myserver:8080/foo"); from("direct:start") .to("rest:get:hello/{me}"); restConfiguration().host("myserver:8080/foo").producerComponent("http"); from("direct:start") .to("rest:get:hello/{me}"); restConfiguration().component("jetty").host("localhost").port(8080).bindingMode(RestBindingMode.json); from("direct:start") .to("rest:post:user"); UserPojo user = new UserPojo(); user.setId(123); user.setName("Donald Duck"); template.sendBody("direct:start", user); restConfiguration().component("jetty").host("localhost").port(8080).bindingMode(RestBindingMode.json); from("direct:start") .to("rest:post:user?outType=com.foo.MyResponsePojo"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-saga-starter</artifactId> </dependency> saga:action saga:action <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-salesforce-starter</artifactId> </dependency> <plugin> <groupId>org.apache.camel.maven</groupId> <artifactId>camel-salesforce-maven-plugin</artifactId> <version>USD{camel-community.version}</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <clientId>USD{camelSalesforce.clientId}</clientId> <clientSecret>USD{camelSalesforce.clientSecret}</clientSecret> <userName>USD{camelSalesforce.userName}</userName> <password>USD{camelSalesforce.password}</password> <sslContextParameters> <secureSocketProtocol>TLSv1.2</secureSocketProtocol> </sslContextParameters> <includes> <include>Contact</include> </includes> </configuration> </execution> </executions> </plugin> salesforce:operationName:topicName salesforce:topic?options salesforce:operationName?options // in your Camel route set the header before Salesforce endpoint // .setHeader("Sforce-Limit-Info", constant("api-usage")) .to("salesforce:getGlobalObjects") .to(myProcessor); // myProcessor will receive `Sforce-Limit-Info` header on the outbound // message class MyProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String apiLimits = in.getHeader("Sforce-Limit-Info", String.class); } } ...to("salesforce:upsertSObject?sObjectIdName=Name") ...to("salesforce:createBatch").. from("salesforce:CamelTestTopic?notifyForFields=ALL&notifyForOperations=ALL&sObjectName=Merchandise__c&updateTopic=true&sObjectQuery=SELECT Id, Name FROM Merchandise__c") from("salesforce:CamelTestTopic&sObjectName=Merchandise__c") class Order_Event__e extends AbstractDTOBase { @JsonProperty("OrderNumber") private String orderNumber; // ... other properties and getters/setters } from("timer:tick") .process(exchange -> { final Message in = exchange.getIn(); String orderNumber = "ORD" + exchange.getProperty(Exchange.TIMER_COUNTER); Order_Event__e event = new Order_Event__e(); event.setOrderNumber(orderNumber); in.setBody(event); }) .to("salesforce:createSObject"); from("timer:tick") .process(exchange -> { final Message in = exchange.getIn(); String orderNumber = "ORD" + exchange.getProperty(Exchange.TIMER_COUNTER); in.setBody("{\"OrderNumber\":\"" + orderNumber + "\"}"); }) .to("salesforce:createSObject?sObjectName=Order_Event__e"); PlatformEvent event = consumer.receiveBody("salesforce:event/Order_Event__e", PlatformEvent.class); from("salesforce:data/ChangeEvents?replayId=-1").log("being notified of all change events") from("salesforce:data/AccountChangeEvent?replayId=-1").log("being notified of change events for Account records") from("salesforce:data/Employee__ChangeEvent?replayId=-1").log("being notified of change events for Employee__c custom object") public class ContentProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ContentVersion cv = new ContentVersion(); ContentWorkspace cw = getWorkspace(exchange); cv.setFirstPublishLocationId(cw.getId()); cv.setTitle("test document"); cv.setPathOnClient("test_doc.html"); byte[] document = message.getBody(byte[].class); ObjectMapper mapper = new ObjectMapper(); String enc = mapper.convertValue(document, String.class); cv.setVersionDataUrl(enc); message.setBody(cv); } protected ContentWorkspace getWorkSpace(Exchange exchange) { // Look up the content workspace somehow, maybe use enrich() to add it to a // header that can be extracted here ---- } } from("file:///home/camel/library") .to(new ContentProcessor()) // convert bytes from the file into a ContentVersion SObject // for the salesforce component .to("salesforce:createSObject"); from("direct:querySalesforce") .to("salesforce:limits") .choice() .when(spel("#{1.0 * body.dailyApiRequests.remaining / body.dailyApiRequests.max < 0.1}")) .to("salesforce:query?...") .otherwise() .setBody(constant("Used up Salesforce API limits, leaving 10% for critical routes")) .endChoice() from("direct:example1")// .setHeader("approval.ContextId", simple("USD{body['contextId']}")) .setHeader("approval.NextApproverIds", simple("USD{body['nextApproverIds']}")) .to("salesforce:approval?"// + "approval.actionType=Submit"// + "&approval.comments=this is a test"// + "&approval.processDefinitionNameOrId=Test_Account_Process"// + "&approval.skipEntryCriteria=true"); final Map<String, String> body = new HashMap<>(); body.put("contextId", accountIds.iterator().next()); body.put("nextApproverIds", userId); final ApprovalResult result = template.requestBody("direct:example1", body, ApprovalResult.class); from("direct:fetchRecentItems") to("salesforce:recent") .split().body() .log("USD{body.name} at USD{body.attributes.url}"); Account account = Contact president = Contact marketing = Account anotherAccount = Contact sales = Asset someAsset = // build the tree SObjectTree request = new SObjectTree(); request.addObject(account).addChildren(president, marketing); request.addObject(anotherAccount).addChild(sales).addChild(someAsset); final SObjectTree response = template.requestBody("salesforce:composite-tree", tree, SObjectTree.class); final Map<Boolean, List<SObjectNode>> result = response.allNodes() .collect(Collectors.groupingBy(SObjectNode::hasErrors)); final List<SObjectNode> withErrors = result.get(true); final List<SObjectNode> succeeded = result.get(false); final String firstId = succeeded.get(0).getId(); final String acountId = final SObjectBatch batch = new SObjectBatch("38.0"); final Account updates = new Account(); updates.setName("NewName"); batch.addUpdate("Account", accountId, updates); final Account newAccount = new Account(); newAccount.setName("Account created from Composite batch API"); batch.addCreate(newAccount); batch.addGet("Account", accountId, "Name", "BillingPostalCode"); batch.addDelete("Account", accountId); final SObjectBatchResponse response = template.requestBody("salesforce:composite-batch", batch, SObjectBatchResponse.class); boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status final List<SObjectBatchResult> results = response.getResults(); // results of three operations sent in batch final SObjectBatchResult updateResult = results.get(0); // update result final int updateStatus = updateResult.getStatusCode(); // probably 204 final Object updateResultData = updateResult.getResult(); // probably null final SObjectBatchResult createResult = results.get(1); // create result @SuppressWarnings("unchecked") final Map<String, Object> createData = (Map<String, Object>) createResult.getResult(); final String newAccountId = createData.get("id"); // id of the new account, this is for JSON, for XML it would be createData.get("Result").get("id") final SObjectBatchResult retrieveResult = results.get(2); // retrieve result @SuppressWarnings("unchecked") final Map<String, Object> retrieveData = (Map<String, Object>) retrieveResult.getResult(); final String accountName = retrieveData.get("Name"); // Name of the retrieved account, this is for JSON, for XML it would be createData.get("Account").get("Name") final String accountBillingPostalCode = retrieveData.get("BillingPostalCode"); // Name of the retrieved account, this is for JSON, for XML it would be createData.get("Account").get("BillingPostalCode") final SObjectBatchResult deleteResult = results.get(3); // delete result final int updateStatus = deleteResult.getStatusCode(); // probably 204 final Object updateResultData = deleteResult.getResult(); // probably null SObjectComposite composite = new SObjectComposite("38.0", true); // first insert operation via an external id final Account updateAccount = new TestAccount(); updateAccount.setName("Salesforce"); updateAccount.setBillingStreet("Landmark @ 1 Market Street"); updateAccount.setBillingCity("San Francisco"); updateAccount.setBillingState("California"); updateAccount.setIndustry(Account_IndustryEnum.TECHNOLOGY); composite.addUpdate("Account", "001xx000003DIpcAAG", updateAccount, "UpdatedAccount"); final Contact newContact = new TestContact(); newContact.setLastName("John Doe"); newContact.setPhone("1234567890"); composite.addCreate(newContact, "NewContact"); final AccountContactJunction__c junction = new AccountContactJunction__c(); junction.setAccount__c("001xx000003DIpcAAG"); junction.setContactId__c("@{NewContact.id}"); composite.addCreate(junction, "JunctionRecord"); final SObjectCompositeResponse response = template.requestBody("salesforce:composite", composite, SObjectCompositeResponse.class); final List<SObjectCompositeResult> results = response.getCompositeResponse(); final SObjectCompositeResult accountUpdateResult = results.stream().filter(r -> "UpdatedAccount".equals(r.getReferenceId())).findFirst().get() final int statusCode = accountUpdateResult.getHttpStatusCode(); // should be 200 final Map<String, ?> accountUpdateBody = accountUpdateResult.getBody(); final SObjectCompositeResult contactCreationResult = results.stream().filter(r -> "JunctionRecord".equals(r.getReferenceId())).findFirst().get() from("timer:fire?period=2000").setBody(constant("{\n" + " \"allOrNone\" : true,\n" + " \"records\" : [ { \n" + " \"attributes\" : {\"type\" : \"FOO\"},\n" + " \"Name\" : \"123456789\",\n" + " \"FOO\" : \"XXXX\",\n" + " \"ACCOUNT\" : 2100.0\n" + " \"ExternalID\" : \"EXTERNAL\"\n" " }]\n" + "}") .to("salesforce:composite?rawPayload=true") .log("USD{body}"); from("direct:queryExample") .setHeader("q", "SELECT Id, LastName FROM Contact") .to("salesforce:raw?format=JSON&rawMethod=GET&rawQueryParameters=q&rawPath=/services/data/v51.0/query") // deserialize JSON results or handle in some other way from("direct:createAContact") .setBody(constant("<Contact><LastName>TestLast</LastName></Contact>")) .to("salesforce:raw?format=XML&rawMethod=POST&rawPath=/services/data/v51.0/sobjects/Contact") <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Result> <id>0034x00000RnV6zAAF</id> <success>true</success> </Result> accountSObject.getFieldsToNull().add("Site"); String allCustomFieldsQuery = QueryHelper.queryToFetchFilteredFieldsOf(new Account(), SObjectField::isCustom); mvn camel-salesforce:generate -DcamelSalesforce.clientId=<clientid> -DcamelSalesforce.clientSecret=<clientsecret> -DcamelSalesforce.userName=<username> -DcamelSalesforce.password=<password> <dependency> <groupId>org.fusesource</groupId> <artifactId>camel-sap-starter</artifactId> <version>4.8.3.redhat-00004</version> </dependency> sap-srfc-destination: destinationName : rfcName sap-trfc-destination: destinationName : rfcName sap-qrfc-destination: destinationName : queueName : rfcName sap-srfc-server: serverName : rfcName [? options ] sap-trfc-server: serverName : rfcName [? options ] sap-idoc-destination: destinationName : idocType [: idocTypeExtension [: systemRelease [: applicationRelease ]]] sap-idoclist-destination: destinationName : idocType [: idocTypeExtension [: systemRelease [: applicationRelease ]]] sap-qidoc-destination: destinationName : queueName : idocType [: idocTypeExtension [: systemRelease [: applicationRelease ]]] sap-qidoclist-destination: destinationName : queueName : idocType [: idocTypeExtension [: systemRelease [: applicationRelease ]]] sap-idoclist-server: serverName : idocType [: idocTypeExtension [: systemRelease [: applicationRelease ]]][? options ] <?xml version="1.0" encoding="UTF-8"?> <blueprint ... > <!-- Configures the Inbound and Outbound SAP Connections --> <bean id="sap-configuration" class="org.fusesource.camel.component.sap.SapConnectionConfiguration"> <property name="destinationDataStore"> <map> <entry key="quickstartDest" value-ref="quickstartDestinationData" /> </map> </property> <property name="serverDataStore"> <map> <entry key="quickstartServer" value-ref="quickstartServerData" /> </map> </property> </bean> <!-- Configures an Outbound SAP Connection --> <!-- *** Please enter the connection property values for your environment *** --> <bean id="quickstartDestinationData" class="org.fusesource.camel.component.sap.model.rfc.impl.DestinationDataImpl"> <property name="ashost" value="example.com" /> <property name="sysnr" value="00" /> <property name="client" value="000" /> <property name="user" value="username" /> <property name="passwd" value="passowrd" /> <property name="lang" value="en" /> </bean> <!-- Configures an Inbound SAP Connection --> <!-- *** Please enter the connection property values for your environment ** --> <bean id="quickstartServerData" class="org.fusesource.camel.component.sap.model.rfc.impl.ServerDataImpl"> <property name="gwhost" value="example.com" /> <property name="gwserv" value="3300" /> <!-- The following property values should not be changed --> <property name="progid" value="QUICKSTART" /> <property name="repositoryDestination" value="quickstartDest" /> <property name="connectionCount" value="2" /> </bean> </blueprint> <?xml version="1.0" encoding="UTF-8"?> <blueprint ... > <!-- Create interceptor to support tRFC processing --> <bean id="currentProcessorDefinitionInterceptor" class="org.fusesource.camel.component.sap.CurrentProcessorDefinitionInterceptStrategy" /> <!-- Configures the Inbound and Outbound SAP Connections --> <bean id="sap-configuration" class="org.fusesource.camel.component.sap.SapConnectionConfiguration"> <property name="destinationDataStore"> <map> <entry key="quickstartDest" value-ref="quickstartDestinationData" /> </map> </property> </bean> <!-- Configures an Outbound SAP Connection --> <!-- *** Please enter the connection property values for your environment *** --> <bean id="quickstartDestinationData" class="org.fusesource.camel.component.sap.model.rfc.impl.DestinationDataImpl"> <property name="ashost" value="example.com" /> <property name="sysnr" value="00" /> <property name="client" value="000" /> <property name="user" value="username" /> <property name="passwd" value="password" /> <property name="lang" value="en" /> </bean> </blueprint> sap-srfc-destination:quickstartDest:BAPI_FLCUST_GETLIST <?xml version="1.0" encoding="UTF-8"?> <blueprint ... > <!-- Configures the Inbound and Outbound SAP Connections --> <bean id="sap-configuration" class="org.fusesource.camel.component.sap.SapConnectionConfiguration"> <property name="destinationDataStore"> <map> <entry key="quickstartDest" value-ref="quickstartDestinationData" /> </map> </property> <property name="serverDataStore"> <map> <entry key="quickstartServer" value-ref="quickstartServerData" /> </map> </property> </bean> <!-- Configures an Outbound SAP Connection --> <!-- *** Please enter the connection property values for your environment *** --> <bean id="quickstartDestinationData" class="org.fusesource.camel.component.sap.model.rfc.impl.DestinationDataImpl"> <property name="ashost" value="example.com" /> <property name="sysnr" value="00" /> <property name="client" value="000" /> <property name="user" value="username" /> <property name="passwd" value="passowrd" /> <property name="lang" value="en" /> </bean> <!-- Configures an Inbound SAP Connection --> <!-- *** Please enter the connection property values for your environment ** --> <bean id="quickstartServerData" class="org.fusesource.camel.component.sap.model.rfc.impl.ServerDataImpl"> <property name="gwhost" value="example.com" /> <property name="gwserv" value="3300" /> <!-- The following property values should not be changed --> <property name="progid" value="QUICKSTART" /> <property name="repositoryDestination" value="quickstartDest" /> <property name="connectionCount" value="2" /> </bean> </blueprint> sap-srfc-server:quickstartServer:BAPI_FLCUST_GETLIST <?xml version="1.0" encoding="UTF-8"?> <blueprint ... > <!-- Configures the sap-srfc-server component --> <bean id="sap-configuration" class="org.fusesource.camel.component.sap.SapConnectionConfiguration"> <property name="repositoryDataStore"> <map> <entry key="nplServer" value-ref="nplRepositoryData" /> </map> </property> </bean> <!-- Configures a Metadata Repository --> <bean id="nplRepositoryData" class="org.fusesource.camel.component.sap.model.rfc.impl.RepositoryDataImpl"> <property name="functionTemplates"> <map> <entry key="BOOK_FLIGHT" value-ref="bookFlightFunctionTemplate" /> </map> </property> </bean> </blueprint> <bean id="bookFlightFunctionTemplate" class="org.fusesource.camel.component.sap.model.rfc.impl.FunctionTemplateImpl"> <property name="importParameterList"> <list> </list> </property> <property name="changingParameterList"> <list> </list> </property> <property name="exportParameterList"> <list> </list> </property> <property name="tableParameterList"> <list> </list> </property> <property name="exceptionList"> <list> </list> </property> </bean> <bean class="org.fusesource.camel.component.sap.model.rfc.impl.ListFieldMetaDataImpl"> <property name="name" value="TICKET_PRICE" /> <property name="type" value="BCD" /> <property name="byteLength" value="12" /> <property name="unicodeByteLength" value="24" /> <property name="decimals" value="2" /> <property name="optional" value="true" /> </bean> <bean class="org.fusesource.camel.component.sap.model.rfc.impl.ListFieldMetaDataImpl"> <property name="name" value="CONNINFO" /> <property name="type" value="TABLE" /> <property name="recordMetaData" ref="connectionInfo" /> </bean> <bean id="connectionInfo" class="org.fusesource.camel.component.sap.model.rfc.impl.RecordMetaDataImpl"> <property name="name" value="CONNECTION_INFO" /> <property name="recordFieldMetaData"> <list> </list> </property> </bean> <bean class="org.fusesource.camel.component.sap.model.rfc.impl.FieldMetaDataImpl"> <property name="name" value="ARRDATE" /> <property name="type" value="DATE" /> <property name="byteLength" value="8" /> <property name="unicodeByteLength" value="16" /> <property name="byteOffset" value="85" /> <property name="unicodeByteOffset" value="170" /> </bean> <bean class="org.fusesource.camel.component.sap.model.rfc.impl.FieldMetaDataImpl"> <property name="name" value="FLTINFO" /> <property name="type" value="STRUCTURE" /> <property name="byteOffset" value="0" /> <property name="unicodeByteOffset" value="0" /> <property name="recordMetaData" ref="flightInfo" /> </bean> public class SAPEndpoint ... { public Structure getRequest() throws Exception; public Structure getResponse() throws Exception; } public interface Structure extends org.eclipse.emf.ecore.EObject, java.util.Map<String, Object> { <T> T get(Object key, Class<T> type); } public interface Table<S extends Structure> extends org.eclipse.emf.ecore.EObject, java.util.List<S> { /** * Creates and adds a table row at the end of the row list */ S add(); /** * Creates and adds a table row at the index in the row list */ S add(int index); } org.fusesource.camel.component.sap.model.idoc.Document org.fusesource.camel.component.sap.model.idoc.DocumentList org.fusesource.camel.component.sap.model.idoc.Document org.fusesource.camel.component.sap.model.idoc.Segment // Java package org.fusesource.camel.component.sap.model.idoc; public interface Document extends EObject { // Access the field values from the IDoc control record String getArchiveKey(); void setArchiveKey(String value); String getClient(); void setClient(String value); // Access the IDoc document contents Segment getRootSegment(); } // Java package org.fusesource.camel.component.sap.model.idoc; public interface Segment extends EObject, java.util.Map<String, Object> { // Returns the value of the '<em><b>Parent</b></em>' reference. Segment getParent(); // Return an immutable list of all child segments <S extends Segment> EList<S> getChildren(); // Returns a list of child segments of the specified segment type. <S extends Segment> SegmentList<S> getChildren(String segmentType); EList<String> getTypes(); Document getDocument(); String getDescription(); String getType(); String getDefinition(); int getHierarchyLevel(); String getIdocType(); String getIdocTypeExtension(); String getSystemRelease(); String getApplicationRelease(); int getNumFields(); long getMaxOccurrence(); long getMinOccurrence(); boolean isMandatory(); boolean isQualified(); int getRecordLength(); <T> T get(Object key, Class<T> type); } // Java package org.fusesource.camel.component.sap.model.idoc; public interface SegmentList<S extends Segment> extends EObject, EList<S> { S add(); S add(int index); } Segment rootSegment = document.getRootSegment(); Segment E1SCU_CRE_Segment = rootSegment.getChildren("E1SCU_CRE").add(); // Java import org.fusesource.camel.component.sap.model.idoc.Document; import org.fusesource.camel.component.sap.model.idoc.Segment; import org.fusesource.camel.component.sap.util.IDocUtil; import org.fusesource.camel.component.sap.model.idoc.Document; import org.fusesource.camel.component.sap.model.idoc.DocumentList; import org.fusesource.camel.component.sap.model.idoc.IdocFactory; import org.fusesource.camel.component.sap.model.idoc.IdocPackage; import org.fusesource.camel.component.sap.model.idoc.Segment; import org.fusesource.camel.component.sap.model.idoc.SegmentChildren; // // Create a new IDoc instance using the modeling classes // // Get the SAP Endpoint bean from the Camel context. // In this example, it's a 'sap-idoc-destination' endpoint. SapTransactionalIDocDestinationEndpoint endpoint = exchange.getContext().getEndpoint( "bean: SapEndpointBeanID ", SapTransactionalIDocDestinationEndpoint.class ); // The endpoint automatically populates some required control record attributes Document document = endpoint.createDocument() // Initialize additional control record attributes document.setMessageType("FLCUSTOMER_CREATEFROMDATA"); document.setRecipientPartnerNumber("QUICKCLNT"); document.setRecipientPartnerType("LS"); document.setSenderPartnerNumber("QUICKSTART"); document.setSenderPartnerType("LS"); Segment rootSegment = document.getRootSegment(); Segment E1SCU_CRE_Segment = rootSegment.getChildren("E1SCU_CRE").add(); Segment E1BPSCUNEW_Segment = E1SCU_CRE_Segment.getChildren("E1BPSCUNEW").add(); E1BPSCUNEW_Segment.put("CUSTNAME", "Fred Flintstone"); E1BPSCUNEW_Segment.put("FORM", "Mr."); E1BPSCUNEW_Segment.put("STREET", "123 Rubble Lane"); E1BPSCUNEW_Segment.put("POSTCODE", "01234"); E1BPSCUNEW_Segment.put("CITY", "Bedrock"); E1BPSCUNEW_Segment.put("COUNTR", "US"); E1BPSCUNEW_Segment.put("PHONE", "800-555-1212"); E1BPSCUNEW_Segment.put("EMAIL", " fred@bedrock.com "); E1BPSCUNEW_Segment.put("CUSTTYPE", "P"); E1BPSCUNEW_Segment.put("DISCOUNT", "005"); E1BPSCUNEW_Segment.put("LANGU", "E"); // Java document.setIDocType("FLCUSTOMER_CREATEFROMDATA01"); document.setIDocTypeExtension(""); document.setMessageType("FLCUSTOMER_CREATEFROMDATA"); <?xml version="1.0" encoding="ASCII"?> <idoc:Document iDocType="FLCUSTOMER_CREATEFROMDATA01" iDocTypeExtension="" messageType="FLCUSTOMER_CREATEFROMDATA" ... > </idoc:Document> http://sap.fusesource.org/rfc/<Repository Name>/<RFC Name> <?xml version="1.0" encoding="ASCII"?> <BOOK_FLIGHT:Request xmlns:BOOK_FLIGHT="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT"> </BOOK_FLIGHT:Request> <?xml version="1.0" encoding="ASCII"?> <BOOK_FLIGHT:Response xmlns:BOOK_FLIGHT="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT"> </BOOK_FLIGHT:Response> <BOOK_FLIGHT:FLTINFO xmlns:BOOK_FLIGHT="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT"> </BOOK_FLIGHT:FLTINFO> <xs:schema targetNamespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT"> xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="FLTINFO_STRUCTURE"> </xs:complexType> </xs:schema> <BOOK_FLIGHT:CONNINFO xmlns:BOOK_FLIGHT="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT"> <row ... > ... </row> <row ... > ... </row> </BOOK_FLIGHT:CONNINFO> <xs:schema targetNamespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complextType name="CONNECTION_INFO_STRUCTURE_TABLE"> <xs:sequence> <xs:element name="row" minOccures="0" maxOccurs="unbounded" type="CONNECTION_INFO_STRUCTURE"/> <xs:sequence> </xs:sequence> </xs:complexType> <xs:complextType name="CONNECTION_INFO_STRUCTURE"> </xs:complexType> </xs:schema> <?xml version="1.0" encoding="ASCII"?> <BOOK_FLIGHT:Request xmlns:BOOK_FLIGHT="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT" CUSTNAME="James Legrand" PASSFORM="Mr" PASSNAME="Travelin Joe" PASSBIRTH="1990-03-17T00:00:00.000-0500" FLIGHTDATE="2014-03-19T00:00:00.000-0400" TRAVELAGENCYNUMBER="00000110" DESTINATION_FROM="SFO" DESTINATION_TO="FRA"/> yyyy-MM-dd'T'HH:mm:ss.SSSZ DEPDATE="2014-03-19T00:00:00.000-0400" DEPTIME="1970-01-01T16:00:00.000-0500" http://sap.fusesource.org/idoc/ repositoryName / idocType / idocTypeExtension / systemRelease / applicationRelease http://sap.fusesource.org/idoc/MY_REPO/FLCUSTOMER_CREATEFROMDATA01/// <convertBodyTo type="java.lang.String"/> <convertBodyTo type="org.fusesource.camel.component.sap.model.idoc.Document"/> <?xml version="1.0" encoding="ASCII"?> <idoc:Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:FLCUSTOMER_CREATEFROMDATA01---="http://sap.fusesource.org/idoc/XXX/FLCUSTOMER_CREATEFROMDATA01///" xmlns:idoc="http://sap.fusesource.org/idoc" creationDate="2015-01-28T12:39:13.980-0500" creationTime="2015-01-28T12:39:13.980-0500" iDocType="FLCUSTOMER_CREATEFROMDATA01" iDocTypeExtension="" messageType="FLCUSTOMER_CREATEFROMDATA" recipientPartnerNumber="QUICKCLNT" recipientPartnerType="LS" senderPartnerNumber="QUICKSTART" senderPartnerType="LS"> <rootSegment xsi:type="FLCUSTOMER_CREATEFROMDATA01---:ROOT" document="/"> <segmentChildren parent="//@rootSegment"> <E1SCU_CRE parent="//@rootSegment" document="/"> <segmentChildren parent="//@rootSegment/@segmentChildren/@E1SCU_CRE.0"> <E1BPSCUNEW parent="//@rootSegment/@segmentChildren/@E1SCU_CRE.0" document="/" CUSTNAME="Fred Flintstone" FORM="Mr." STREET="123 Rubble Lane" POSTCODE="01234" CITY="Bedrock" COUNTR="US" PHONE="800-555-1212" EMAIL="fred@bedrock.com" CUSTTYPE="P" DISCOUNT="005" LANGU="E"/> </segmentChildren> </E1SCU_CRE> </segmentChildren> </rootSegment> </idoc:Document> from("direct:getFlightCustomerInfo") .to("bean:createFlightCustomerGetListRequest") .to("sap-srfc-destination:nplDest:BAPI_FLCUST_GETLIST") .to("bean:returnFlightCustomerInfo"); <route> <from uri="direct:getFlightCustomerInfo"/> <to uri="bean:createFlightCustomerGetListRequest"/> <to uri="sap-srfc-destination:nplDest:BAPI_FLCUST_GETLIST"/> <to uri="bean:returnFlightCustomerInfo"/> </route> public void create(Exchange exchange) throws Exception { // Get SAP Endpoint to be called from context. SapSynchronousRfcDestinationEndpoint endpoint = exchange.getContext().getEndpoint("sap-srfc-destination:nplDest:BAPI_FLCUST_GETLIST", SapSynchronousRfcDestinationEndpoint.class); // Retrieve bean from message containing Flight Customer name to // look up. BookFlightRequest bookFlightRequest = exchange.getIn().getBody(BookFlightRequest.class); // Create SAP Request object from target endpoint. Structure request = endpoint.getRequest(); // Add Customer Name to request if set if (bookFlightRequest.getCustomerName() != null && bookFlightRequest.getCustomerName().length() > 0) { request.put("CUSTOMER_NAME", bookFlightRequest.getCustomerName()); } } else { throw new Exception("No Customer Name"); } // Put request object into body of exchange message. exchange.getIn().setBody(request); } public void createFlightCustomerInfo(Exchange exchange) throws Exception { // Retrieve SAP response object from body of exchange message. Structure flightCustomerGetListResponse = exchange.getIn().getBody(Structure.class); if (flightCustomerGetListResponse == null) { throw new Exception("No Flight Customer Get List Response"); } // Check BAPI return parameter for errors @SuppressWarnings("unchecked") Table<Structure> bapiReturn = flightCustomerGetListResponse.get("RETURN", Table.class); Structure bapiReturnEntry = bapiReturn.get(0); if (bapiReturnEntry.get("TYPE", String.class) != "S") { String message = bapiReturnEntry.get("MESSAGE", String.class); throw new Exception("BAPI call failed: " + message); } // Get customer list table from response object. @SuppressWarnings("unchecked") Table<? extends Structure> customerList = flightCustomerGetListResponse.get("CUSTOMER_LIST", Table.class); if (customerList == null || customerList.size() == 0) { throw new Exception("No Customer Info."); } // Get Flight Customer data from first row of table. Structure customer = customerList.get(0); // Create bean to hold Flight Customer data. FlightCustomerInfo flightCustomerInfo = new FlightCustomerInfo(); // Get customer id from Flight Customer data and add to bean. String customerId = customer.get("CUSTOMERID", String.class); if (customerId != null) { flightCustomerInfo.setCustomerNumber(customerId); } // Put bean into body of exchange message. exchange.getIn().setHeader("flightCustomerInfo", flightCustomerInfo); } from("direct:createFlightTrip") .to("bean:createFlightTripRequest") .to("sap-srfc-destination:nplDest:BAPI_FLTRIP_CREATE?transacted=true") .to("bean:returnFlightTripResponse"); <route> <from uri="direct:createFlightTrip"/> <to uri="bean:createFlightTripRequest"/> <to uri="sap-srfc-destination:nplDest:BAPI_FLTRIP_CREATE?transacted=true"/> <to uri="bean:returnFlightTripResponse"/> </route> DataFormat jaxb = new JaxbDataFormat("org.fusesource.sap.example.jaxb"); from("sap-srfc-server:nplserver:BOOK_FLIGHT") .unmarshal(jaxb) .multicast() .to("direct:getFlightConnectionInfo", "direct:getFlightCustomerInfo", "direct:getPassengerInfo") .end() .to("direct:createFlightTrip") .marshal(jaxb); <route> <from uri="sap-srfc-server:nplserver:BOOK_FLIGHT"/> <unmarshal> <jaxb contextPath="org.fusesource.sap.example.jaxb"/> </unmarshal> <multicast> <to uri="direct:getFlightConnectionInfo"/> <to uri="direct:getFlightCustomerInfo"/> <to uri="direct:getPassengerInfo"/> </multicast> <to uri="direct:createFlightTrip"/> <marshal> <jaxb contextPath="org.fusesource.sap.example.jaxb"/> </marshal> </route> @XmlRootElement(name="Request", namespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT") @XmlAccessorType(XmlAccessType.FIELD) public class BookFlightRequest { @XmlAttribute(name="CUSTNAME") private String customerName; @XmlAttribute(name="FLIGHTDATE") @XmlJavaTypeAdapter(DateAdapter.class) private Date flightDate; @XmlAttribute(name="TRAVELAGENCYNUMBER") private String travelAgencyNumber; @XmlAttribute(name="DESTINATION_FROM") private String startAirportCode; @XmlAttribute(name="DESTINATION_TO") private String endAirportCode; @XmlAttribute(name="PASSFORM") private String passengerFormOfAddress; @XmlAttribute(name="PASSNAME") private String passengerName; @XmlAttribute(name="PASSBIRTH") @XmlJavaTypeAdapter(DateAdapter.class) private Date passengerDateOfBirth; @XmlAttribute(name="CLASS") private String flightClass; } @XmlRootElement(name="Response", namespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT") @XmlAccessorType(XmlAccessType.FIELD) public class BookFlightResponse { @XmlAttribute(name="TRIPNUMBER") private String tripNumber; @XmlAttribute(name="TICKET_PRICE") private BigDecimal ticketPrice; @XmlAttribute(name="TICKET_TAX") private BigDecimal ticketTax; @XmlAttribute(name="CURRENCY") private String currency; @XmlAttribute(name="PASSFORM") private String passengerFormOfAddress; @XmlAttribute(name="PASSNAME") private String passengerName; @XmlAttribute(name="PASSBIRTH") @XmlJavaTypeAdapter(DateAdapter.class) private Date passengerDateOfBirth; @XmlElement(name="FLTINFO") private FlightInfo flightInfo; @XmlElement(name="CONNINFO") private ConnectionInfoTable connectionInfo; } @XmlRootElement(name="FLTINFO", namespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT") @XmlAccessorType(XmlAccessType.FIELD) public class FlightInfo { @XmlAttribute(name="FLIGHTTIME") private String flightTime; @XmlAttribute(name="CITYFROM") private String cityFrom; @XmlAttribute(name="DEPDATE") @XmlJavaTypeAdapter(DateAdapter.class) private Date departureDate; @XmlAttribute(name="DEPTIME") @XmlJavaTypeAdapter(DateAdapter.class) private Date departureTime; @XmlAttribute(name="CITYTO") private String cityTo; @XmlAttribute(name="ARRDATE") @XmlJavaTypeAdapter(DateAdapter.class) private Date arrivalDate; @XmlAttribute(name="ARRTIME") @XmlJavaTypeAdapter(DateAdapter.class) private Date arrivalTime; } @XmlRootElement(name="CONNINFO_TABLE", namespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT") @XmlAccessorType(XmlAccessType.FIELD) public class ConnectionInfoTable { @XmlElement(name="row") List<ConnectionInfo> rows; } @XmlRootElement(name="CONNINFO", namespace="http://sap.fusesource.org/rfc/nplServer/BOOK_FLIGHT") @XmlAccessorType(XmlAccessType.FIELD) public class ConnectionInfo { @XmlAttribute(name="CONNID") String connectionId; @XmlAttribute(name="AIRLINE") String airline; @XmlAttribute(name="PLANETYPE") String planeType; @XmlAttribute(name="CITYFROM") String cityFrom; @XmlAttribute(name="DEPDATE") @XmlJavaTypeAdapter(DateAdapter.class) Date departureDate; @XmlAttribute(name="DEPTIME") @XmlJavaTypeAdapter(DateAdapter.class) Date departureTime; @XmlAttribute(name="CITYTO") String cityTo; @XmlAttribute(name="ARRDATE") @XmlJavaTypeAdapter(DateAdapter.class) Date arrivalDate; @XmlAttribute(name="ARRTIME") @XmlJavaTypeAdapter(DateAdapter.class) Date arrivalTime; } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-saxon-starter</artifactId> </dependency> from("queue:foo") .filter().xquery("//foo") .to("queue:bar") from("direct:start") .recipientList().xquery("concat('mock:foo.', /person/@city)", String.class); <route> <from uri="direct:start"/> <recipientList> <xquery type="java.lang.String">concat('mock:foo.', /person/@city</xquery> </recipientList> </route> Namespaces ns = new Namespaces("c", "http://acme.com/cheese"); from("direct:start") .filter().xquery("/c:person[@name='James']", ns) .to("mock:result"); /c:person[@name='James'] Namespaces ns = new Namespaces("c", "http://acme.com/cheese") .add("w", "http://acme.com/wine") .add("b", "http://acme.com/beer"); <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:foo="http://example.com/person" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring"> <route> <from uri="activemq:MyQueue"/> <filter> <xquery>/foo:person[@name='James']</xquery> <to uri="mqseries:SomeOtherQueue"/> </filter> </route> </camelContext> </beans> from("direct:start"). transform().xquery("/people/person"); from("direct:start"). transform().xquery("/people/person/text()", String.class); <transform> <xquery> declare variable USDin.headers.foo external; element item {USDin.headers.foo} </xquery> </transform> .setHeader("myHeader").xquery("resource:classpath:myxquery.txt", String.class) <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-scheduler-starter</artifactId> </dependency> scheduler:name[?options] scheduler:name from("scheduler://foo?delay=60000").to("bean:myBean?method=someMethodName"); <route> <from uri="scheduler://foo?delay=60000"/> <to uri="bean:myBean?method=someMethodName"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-seda-starter</artifactId> </dependency> seda:someName[?options] seda:name <bean id="arrayQueue" class="java.util.ArrayBlockingQueue"> <constructor-arg index="0" value="10" ><!-- size --> <constructor-arg index="1" value="true" ><!-- fairness --> </bean> <!-- ... and later --> <from>seda:array?queue=#arrayQueue</from> <bean id="priorityQueueFactory" class="org.apache.camel.component.seda.PriorityBlockingQueueFactory"> <property name="comparator"> <bean class="org.apache.camel.demo.MyExchangeComparator" /> </property> </bean> <!-- ... and later --> <from>seda:priority?queueFactory=#priorityQueueFactory&size=100</from> from("mina:tcp://0.0.0.0:9876?textline=true&sync=true").to("seda:input"); from("seda:input").to("bean:processInput").to("bean:createResponse"); from("seda:stageName?concurrentConsumers=5").process(...) from("seda:stageName").thread(5).process(...) from("direct:stageName").thread(5).process(...) @Test public void testSendAsync() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); // START SNIPPET: e2 Object out = template.requestBody("direct:start", "Hello World"); assertEquals("OK", out); // END SNIPPET: e2 assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { // START SNIPPET: e1 public void configure() throws Exception { from("direct:start") // send it to the seda queue that is async .to("seda:next") // return a constant response .transform(constant("OK")); from("seda:next").to("mock:result"); } // END SNIPPET: e1 }; } @Test public void testSameOptionsProducerStillOkay() throws Exception { getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:bar").expectedBodiesReceived("Hello World"); template.sendBody("seda:foo", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("seda:foo?multipleConsumers=true").routeId("foo").to("mock:foo"); from("seda:foo?multipleConsumers=true").routeId("bar").to("mock:bar"); } }; } SedaEndpoint seda = context.getEndpoint("seda:xxxx"); int size = seda.getExchanges().size(); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-servlet-starter</artifactId> </dependency> servlet://relative_path[?options] servlet:contextPath <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> simple("USD{body.address}") simple("USD{body.address.street}") simple("USD{body.address.zip}") simple("USD{body.address}") simple("USD{body.getAddress.getStreet}") simple("USD{body.address.getZip}") simple("USD{body.doSomething}") simple("USD{body?.address?.street}") simple("USD{body[foo].name}") simple("USD{body['foo bar'].name}") simple("USD{body[foo]}") simple("USD{body[this.is.foo]}") simple("USD{body[foo]?.name}") simple("USD{body.address.lines[0]}") simple("USD{body.address.lines[1]}") simple("USD{body.address.lines[2]}") simple("USD{body.address.lines[last]}") simple("USD{body.address.lines[last-1]}") simple("USD{body.address.lines[last-2]}") simple("USD{body.address.lines.size}") String[] lines = new String[]{"foo", "bar", "cat"}; exchange.getIn().setBody(lines); simple("There are USD{body.length} lines") simple("USD{body.address.zip} > 1000") USD{leftValue} OP rightValue USD{leftValue} OP rightValue && USD{leftValue} OP rightValue USD{leftValue} OP rightValue || USD{leftValue} OP rightValue // exact equals match simple("USD{header.foo} == 'foo'") // ignore case when comparing, so if the header has value FOO this will match simple("USD{header.foo} =~ 'foo'") // here Camel will type convert '100' into the type of header.bar and if it is an Integer '100' will also be converter to an Integer simple("USD{header.bar} == '100'") simple("USD{header.bar} == 100") // 100 will be converter to the type of header.bar so we can do > comparison simple("USD{header.bar} > 100") simple("100 < USD{header.bar}") // testing for null simple("USD{header.baz} == null") // testing for not null simple("USD{header.baz} != null") simple("USD{header.date} == USD{date:now:yyyyMMdd}") simple("USD{header.type} == USD{bean:orderService?method=getOrderType}") simple("USD{header.title} contains 'Camel'") simple("USD{header.number} regex '\\d{4}'") simple("USD{header.type} in 'gold,silver'") simple("USD{header.type} !in 'gold,silver'") simple("USD{header.type} is 'java.lang.String'") simple("USD{header.type} is 'String'") simple("USD{header.number} range 100..199") simple("USD{header.number} range '100..199'") <from uri="seda:orders"> <filter> <simple>USD{header.type} == 'widget'</simple> <to uri="bean:orderService?method=handleWidget"/> </filter> </from> simple("USD{header.title} contains 'Camel' && USD{header.type'} == 'gold'") simple("USD{header.title} contains 'Camel' || USD{header.type'} == 'gold'") <from uri="seda:orders"> <filter> <simple>USD{header.foo}</simple> <to uri="mock:fooOrders"/> </filter> </from> from("seda:orders") .filter().simple("USD{header.foo}") .to("seda:fooOrders"); from("direct:hello") .transform().simple("Hello USD{header.user} how are you?") .to("mock:reply"); from("direct:hello") .transform().simple("The today is USD{date:now:yyyyMMdd} and it is a great day.") .to("mock:reply"); from("direct:order") .transform().simple("OrderId: USD{bean:orderIdGenerator}") .to("mock:reply"); from("direct:order") .transform().simple("OrderId: USD{bean:orderIdGenerator.generateId}") .to("mock:reply"); from("direct:order") .transform().simple("OrderId: USD{bean:orderIdGenerator?method=generateId}") .to("mock:reply"); <transform> <simple>Hello USD{bodyAs(String)} how are you?</simple> </transform> <transform> <simple>The gold value is USD{header.type[gold]}</simple> </transform> <setHeader name="myHeader"> <simple>USD{properties:USD{header.someKey}}</simple> </setHeader> .setHeader("cool", simple("true", Boolean.class)) <setHeader name="cool"> <!-- use resultType to indicate that the type should be a java.lang.Boolean --> <simple resultType="java.lang.Boolean">true</simple> </setHeader> <transform> <simple>The following text\nis on a new line</simple> </transform> <setBody> <simple trim="false">You get some trailing whitespace characters. </simple> </setBody> .setHeader("myHeader").simple("resource:classpath:mysimple.txt") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-slack-starter</artifactId> </dependency> slack:#channel[?options] slack:@userID[?options] slack:channel <bean id="slack" class="org.apache.camel.component.slack.SlackComponent"> <property name="webhookUrl" value="https://hooks.slack.com/services/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"/> <property name="token" value="xoxb-12345678901-1234567890123-xxxxxxxxxxxxxxxxxxxxxxxx"/> </bean> <?xml version="1.0" encoding="UTF-8"?> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" default-activation="lazy"> <bean id="slack" class="org.apache.camel.component.slack.SlackComponent"> <property name="webhookUrl" value="https://hooks.slack.com/services/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"/> </bean> <camelContext xmlns="http://camel.apache.org/schema/blueprint"> <route> <from uri="direct:test"/> <to uri="slack:#channel?iconEmoji=:camel:&amp;username=CamelTest"/> </route> </camelContext> </blueprint> from("direct:test") .to("slack:#random?token=RAW(<YOUR_TOKEN>)"); public void testSlackAPIModelMessage() { Message message = new Message(); message.setBlocks(Collections.singletonList(SectionBlock .builder() .text(MarkdownTextObject .builder() .text("*Hello from Camel!*") .build()) .build())); template.sendBody(test, message); } from("slack://general?token=RAW(<YOUR_TOKEN>)&maxResults=1") .to("mock:result"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-smb-starter</artifactId> </dependency> smb:address[:port]/shareName[?options] smb:hostname:port/shareName private void process(Exchange exchange) throws IOException { final File file = exchange.getMessage().getBody(File.class); try (InputStream inputStream = file.getInputStream()) { LOG.debug("Read exchange: {}, with contents: {}", file.getFileInformation(), new String(inputStream.readAllBytes())); } } public void configure() { fromF("smb:%s/%s?username=%s&password=%s&path=/", service.address(), service.shareName(), service.userName(), service.password()) .process(this::process) .to("mock:result"); } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-snmp-starter</artifactId> </dependency> snmp://hostname[:port][?Options] snmp:host:port 1.3.6.1.2.1.1.3.0 1.3.6.1.2.1.25.3.2.1.5.1 1.3.6.1.2.1.25.3.5.1.1.1 1.3.6.1.2.1.43.5.1.1.11.1 <?xml version="1.0" encoding="UTF-8"?> <snmp> <entry> <oid>1.3.6.1.2.1.1.3.0</oid> <value>6 days, 21:14:28.00</value> </entry> <entry> <oid>1.3.6.1.2.1.25.3.2.1.5.1</oid> <value>2</value> </entry> <entry> <oid>1.3.6.1.2.1.25.3.5.1.1.1</oid> <value>3</value> </entry> <entry> <oid>1.3.6.1.2.1.43.5.1.1.11.1</oid> <value>6</value> </entry> <entry> <oid>1.3.6.1.2.1.1.1.0</oid> <value>My Very Special Printer Of Brand Unknown</value> </entry> </snmp> .1.3.6.1.4.1.6527.3.1.2.21.2.1.50 snmp:192.168.178.23:161?protocol=udp&type=POLL&oids=1.3.6.1.2.1.1.5.0 snmp:127.0.0.1:162?protocol=udp&type=TRAP from("snmp:192.168.178.23:161?protocol=udp&type=POLL&oids=1.3.6.1.2.1.1.5.0"). convertBodyTo(String.class). to("activemq:snmp.states"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-soap-starter</artifactId> </dependency> SoapJaxbDataFormat soap = new SoapJaxbDataFormat("com.example.customerservice", new ServiceInterfaceStrategy(CustomerService.class)); from("direct:start") .marshal(soap) .to("jms:myQueue"); SoapJaxbDataFormat soap = new SoapJaxbDataFormat("com.example.customerservice", new ServiceInterfaceStrategy(CustomerService.class)); soap.setVersion("1.2"); from("direct:start") .marshal(soap) .to("jms:myQueue"); <!-- Defining a ServiceInterfaceStrategy for retrieving the element name when marshalling --> <bean id="myNameStrategy" class="org.apache.camel.dataformat.soap.name.ServiceInterfaceStrategy"> <constructor-arg value="com.example.customerservice.CustomerService"/> <constructor-arg value="true"/> </bean> <route> <from uri="direct:start"/> <marshal> <soapjaxb contentPath="com.example.customerservice" version="1.2" elementNameStrategyRef="myNameStrategy"/> </marshal> <to uri="jms:myQueue"/> </route> ServiceInterfaceStrategy strat = new ServiceInterfaceStrategy(com.example.customerservice.multipart.MultiPartCustomerService.class, true); SoapJaxbDataFormat soapDataFormat = new SoapJaxbDataFormat("com.example.customerservice.multipart", strat); String WS_URI = "cxf://http://myserver/customerservice?serviceClass=com.example.customerservice&dataFormat=RAW"; SoapJaxbDataFormat soapDF = new SoapJaxbDataFormat("com.example.customerservice", new ServiceInterfaceStrategy(CustomerService.class)); from("direct:customerServiceClient") .onException(Exception.class) .handled(true) .unmarshal(soapDF) .end() .marshal(soapDF) .to(WS_URI) .unmarshal(soapDF); import org.apache.camel.Endpoint; import org.apache.camel.component.bean.ProxyHelper; Endpoint startEndpoint = context.getEndpoint("direct:customerServiceClient"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // CustomerService below is the service endpoint interface, *not* the javax.xml.ws.Service subclass CustomerService proxy = ProxyHelper.createProxy(startEndpoint, classLoader, CustomerService.class); GetCustomersByNameResponse response = proxy.getCustomersByName(new GetCustomersByName()); SoapJaxbDataFormat soapDF = new SoapJaxbDataFormat("com.example.customerservice", new ServiceInterfaceStrategy(CustomerService.class)); CustomerService serverBean = new CustomerServiceImpl(); from("jms://queue:customerServiceQueue") .onException(Exception.class) .handled(true) .marshal(soapDF) .end() .unmarshal(soapDF) .bean(serverBean) .marshal(soapDF); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-splunk-starter</artifactId> </dependency> splunk://[endpoint]?[options] splunk:name from("direct:start").convertBodyTo(SplunkEvent.class) .to("splunk://submit?username=user&password=123&index=myindex&sourceType=someSourceType&source=mySource") from("splunk://normal?delay=5000&username=user&password=123&initEarliestTime=-10s&search=search index=myindex sourcetype=someSourcetype") .to("direct:search-result"); from("twitter://search?type=polling&keywords=music&delay=10&consumerKey=abc&consumerSecret=def&accessToken=hij&accessTokenSecret=xxx") .convertBodyTo(SplunkEvent.class) .to("splunk://submit?username=foo&password=bar&index=camel-tweets&sourceType=twitter&source=music-tweets"); @Converter public class Tweet2SplunkEvent { @Converter public static SplunkEvent convertTweet(Status status) { SplunkEvent data = new SplunkEvent("twitter-message", null); //data.addPair("source", status.getSource()); data.addPair("from_user", status.getUser().getScreenName()); data.addPair("in_reply_to", status.getInReplyToScreenName()); data.addPair(SplunkEvent.COMMON_START_TIME, status.getCreatedAt()); data.addPair(SplunkEvent.COMMON_EVENT_ID, status.getId()); data.addPair("text", status.getText()); data.addPair("retweet_count", status.getRetweetCount()); if (status.getPlace() != null) { data.addPair("place_country", status.getPlace().getCountry()); data.addPair("place_name", status.getPlace().getName()); data.addPair("place_street", status.getPlace().getStreetAddress()); } if (status.getGeoLocation() != null) { data.addPair("geo_latitude", status.getGeoLocation().getLatitude()); data.addPair("geo_longitude", status.getGeoLocation().getLongitude()); } return data; } } from("splunk://normal?username=foo&password=bar&initEarliestTime=-2m&search=search index=camel-tweets sourcetype=twitter") .log("USD{body}"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-batch-starter</artifactId> </dependency> spring-batch:jobName[?options] spring-batch:jobName from("direct:startBatch").to("spring-batch:myJob"); from("direct:startBatch").to("spring-batch:myJob?jobLauncherRef=myJobLauncher"); from("direct:startBatch").to("spring-batch:myJob").to("mock:JobExecutions"); MockEndpoint mockEndpoint = ...; JobExecution jobExecution = mockEndpoint.getExchanges().get(0).getIn().getBody(JobExecution.class); BatchStatus currentJobStatus = jobExecution.getStatus(); <bean id="camelReader" class="org.apache.camel.component.spring.batch.support.CamelItemReader"> <constructor-arg ref="consumerTemplate"/> <constructor-arg value="jms:dataQueue"/> </bean> <batch:job id="myJob"> <batch:step id="step"> <batch:tasklet> <batch:chunk reader="camelReader" writer="someWriter" commit-interval="100"/> </batch:tasklet> </batch:step> </batch:job> <bean id="camelwriter" class="org.apache.camel.component.spring.batch.support.CamelItemWriter"> <constructor-arg ref="producerTemplate"/> <constructor-arg value="jms:dataQueue"/> </bean> <batch:job id="myJob"> <batch:step id="step"> <batch:tasklet> <batch:chunk reader="someReader" writer="camelwriter" commit-interval="100"/> </batch:tasklet> </batch:step> </batch:job> <camel:camelContext> <camel:route> <camel:from uri="direct:processor"/> <camel:setExchangePattern pattern="InOut"/> <camel:setBody> <camel:simple>Processed USD{body}</camel:simple> </camel:setBody> </camel:route> </camel:camelContext> <bean id="camelProcessor" class="org.apache.camel.component.spring.batch.support.CamelItemProcessor"> <constructor-arg ref="producerTemplate"/> <constructor-arg value="direct:processor"/> </bean> <batch:job id="myJob"> <batch:step id="step"> <batch:tasklet> <batch:chunk reader="someReader" writer="someWriter" processor="camelProcessor" commit-interval="100"/> </batch:tasklet> </batch:step> </batch:job> <bean id="camelJobExecutionListener" class="org.apache.camel.component.spring.batch.support.CamelJobExecutionListener"> <constructor-arg ref="producerTemplate"/> <constructor-arg value="jms:batchEventsBus"/> </bean> <batch:job id="myJob"> <batch:step id="step"> <batch:tasklet> <batch:chunk reader="someReader" writer="someWriter" commit-interval="100"/> </batch:tasklet> </batch:step> <batch:listeners> <batch:listener ref="camelJobExecutionListener"/> </batch:listeners> </batch:job> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-jdbc-starter</artifactId> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>com.redhat.camel.springboot.platform</groupId> <artifactId>camel-spring-boot-bom</artifactId> <version>USD{camel-spring-boot-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> spring-jdbc:dataSourceName <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-ldap-starter</artifactId> </dependency> spring-ldap:springLdapTemplate[?options] spring-ldap:templateName from("direct:start") .setBody(constant(createMap())) .to("spring-ldap:ldapTemplate?operation=BIND"); private static Map<String, Object> createMap() { BasicAttributes basicAttributes = new BasicAttributes(); basicAttributes.put("cn", "Name Surname"); basicAttributes.put("sn", "Surname"); basicAttributes.put("objectClass", "person"); Map<String, Object> map = new HashMap<>(); map.put(SpringLdapProducer.DN, "cn=LdapDN,dc=example,dc=org"); map.put(SpringLdapProducer.ATTRIBUTES, basicAttributes); return map; } spring.ldap.password=passwordforldapserver spring.ldap.urls=urlForLdapServer spring.ldap.username=usernameForLdapServer <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-rabbitmq-starter</artifactId> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>com.redhat.camel.springboot.platform</groupId> <artifactId>camel-spring-boot-bom</artifactId> <version>USD{camel-spring-boot-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> spring-rabbitmq:exchangeName?[options] spring-rabbitmq:exchangeName <bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory"> <property name="uri" value="amqp://lolcalhost:5672"/> </bean> <camelContext> <route> <from uri="direct:cheese"/> <to uri="spring-rabbitmq:foo?routingKey=cheese"/> </route> </camelContext> to("spring-rabbitmq:default?routingKey=foo") from("direct:start") .to("log:request") .to(ExchangePattern.InOut, "spring-rabbitmq:cheese?routingKey=foo.bar") .to("log:response"); from("spring-rabbitmq:cheese?queues=myqueue&routingKey=foo.bar") .to("log:input") .transform(body().prepend("Hello ")); from("file://inbox") .to("bean:computeDestination") .to("spring-rabbitmq:dummy"); public void setExchangeHeader(Exchange exchange) { String region = . exchange.getIn().setHeader("CamelSpringRabbitmqExchangeOverrideName", "order-" + region); } from("direct:order") .toD("spring-rabbit:order-USD{header.orderType}"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-redis-starter</artifactId> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>com.redhat.camel.springboot.platform</groupId> <artifactId>camel-spring-boot-bom</artifactId> <version>USD{camel-spring-boot-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> spring-redis://host:port[?options] spring-redis:host:port from("direct:start") .setHeader("CamelRedis.Key", constant(key)) .setHeader("CamelRedis.Value", constant(value)) .to("spring-redis://host:port?command=SET&redisTemplate=#redisTemplate"); from("spring-redis://host:port?command=SUBSCRIBE&channels=myChannel") .log("Received message: USD{body}"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-security-starter</artifactId> </dependency> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring-security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased"> <property name="allowIfAllAbstainDecisions" value="true"/> <property name="decisionVoters"> <list> <bean class="org.springframework.security.access.vote.RoleVoter"/> </list> </property> </bean> <spring-security:authentication-manager alias="authenticationManager"> <spring-security:authentication-provider user-service-ref="userDetailsService"/> </spring-security:authentication-manager> <spring-security:user-service id="userDetailsService"> <spring-security:user name="jim" password="jimspassword" authorities="ROLE_USER, ROLE_ADMIN"/> <spring-security:user name="bob" password="bobspassword" authorities="ROLE_USER"/> </spring-security:user-service> </beans> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring-security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://camel.apache.org/schema/spring-security http://camel.apache.org/schema/spring-security/camel-spring-security.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <!-- import the Spring security configuration --> <import resource= "classpath:org/apache/camel/component/spring/security/commonSecurity.xml"/> <authorizationPolicy id="admin" access="ROLE_ADMIN" authenticationManager="authenticationManager" accessDecisionManager="accessDecisionManager" xmlns="http://camel.apache.org/schema/spring-security"/> <camelContext id="myCamelContext" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start"/> <!-- The exchange should be authenticated with the role --> <!-- of ADMIN before it is send to mock:endpoint --> <policy ref="admin"> <to uri="mock:end"/> </policy> </route> </camelContext> </beans> import javax.security.auth.Subject; import org.apache.camel.*; import org.apache.commons.codec.binary.Base64; import org.springframework.security.authentication.*; public class MyAuthService implements Processor { public void process(Exchange exchange) throws Exception { // get the username and password from the HTTP header // http://en.wikipedia.org/wiki/Basic_access_authentication String userpass = new String(Base64.decodeBase64(exchange.getIn().getHeader("Authorization", String.class))); String[] tokens = userpass.split(":"); // create an Authentication object UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(tokens[0], tokens[1]); // wrap it in a Subject Subject subject = new Subject(); subject.getPrincipals().add(authToken); // place the Subject in the In message exchange.getIn().setHeader(Exchange.AUTHENTICATION, subject); // you could also do this if useThreadSecurityContext is set to true // SecurityContextHolder.getContext().setAuthentication(authToken); } } <onException> <exception>org.springframework.security.authentication.AccessDeniedException</exception> <choice> <when> <simple>USD{exception.policyId} == 'user'</simple> <transform> <constant>You do not have ROLE_USER access!</constant> </transform> </when> <when> <simple>USD{exception.policyId} == 'admin'</simple> <transform> <constant>You do not have ROLE_ADMIN access!</constant> </transform> </when> </choice> </onException> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-ws</artifactId> <!-- use the same version as your Camel core version --> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>com.redhat.camel.springboot.platform</groupId> <artifactId>camel-spring-boot-bom</artifactId> <version>USD{camel-spring-boot-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> spring-ws:[mapping-type:]address[?options] spring-ws:type:lookupKey:webServiceEndpointUri from("direct:example").to("spring-ws:http://foo.com/bar") template.requestBody("direct:example", "<foobar xmlns=\"http://foo.com\"><msg>test message</msg></foobar>"); from("direct:example") .to("spring-ws:http://foo.com/bar?soapAction=http://foo.com&wsAddressingAction=http://bar.com") template.requestBodyAndHeader("direct:example", "<foobar xmlns=\"http://foo.com\"><msg>test message</msg></foobar>", SpringWebserviceConstants.SPRING_WS_SOAP_ACTION, "http://baz.com"); String body = String soapHeader = "<h:Header xmlns:h=\"http://www.webserviceX.NET/\"><h:MessageID>1234567890</h:MessageID><h:Nested><h:NestedID>1111</h:NestedID></h:Nested></h:Header>"; exchange.getIn().setBody(body); exchange.getIn().setHeader(SpringWebserviceConstants.SPRING_WS_SOAP_HEADER, soapHeader); exchange.getOut().getHeaders().put("myCustom","myHeaderValue") exchange.getIn().addAttachment("myAttachment", new DataHandler(...)) <bean id="headerTransformationFilter" class="org.apache.camel.component.spring.ws.filter.impl.HeaderTransformationMessageFilter"> <constructor-arg index="0" value="org/apache/camel/component/spring/ws/soap-header-transform.xslt"/> </bean> <route> <from uri="direct:stockQuoteWebserviceHeaderTransformation"/> <to uri="spring-ws:http://localhost?webServiceTemplate=#webServiceTemplate&amp;soapAction=http://www.stockquotes.edu/GetQuote&amp;messageFilter=#headerTransformationFilter"/> </route> <bean id="axiomMessageFactory" class="org.springframework.ws.soap.axiom.AxiomSoapMessageFactory"> <property name="payloadCaching" value="false" /> <property name="attachmentCaching" value="true" /> <property name="attachmentCacheThreshold" value="1024" /> </bean> <dependency> <groupId>org.apache.ws.commons.axiom</groupId> <artifactId>axiom-api</artifactId> <version>1.2.13</version> </dependency> <dependency> <groupId>org.apache.ws.commons.axiom</groupId> <artifactId>axiom-impl</artifactId> <version>1.2.13</version> <scope>runtime</scope> </dependency> private class Attachement implements Processor { public void process(Exchange exchange) throws Exception { exchange.getOut().copyFrom(exchange.getIn()); File file = new File("testAttachment.txt"); exchange.getOut().addAttachment("test", new DataHandler(new FileDataSource(file))); } } from("direct:send") .process(new Attachement()) .to("spring-ws:http://localhost:8089/mySoapService?soapAction=mySoap&messageFactory=axiomMessageFactory"); <bean id="messageFilter" class="your.domain.myMessageFiler" scope="singleton" /> to("spring-ws:http://yourdomain.com?messageFilter=#myEndpointSpecificMessageFilter"); protected void doProcessSoapHeader(Message inOrOut, SoapMessage soapMessage) {your code /*no need to call super*/ } protected void doProcessSoapAttachements(Message inOrOut, SoapMessage response) { your code /*no need to call super*/ } from("direct:example") .to("spring-ws:http://foo.com/bar?messageFactory=#messageFactory&messageSender=#messageSender") <!-- authenticate using HTTP Basic Authentication --> <bean id="messageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender"> <property name="credentials"> <bean class="org.apache.commons.httpclient.UsernamePasswordCredentials"> <constructor-arg index="0" value="admin"/> <constructor-arg index="1" value="secret"/> </bean> </property> </bean> <!-- force use of Sun SAAJ implementation, http://static.springsource.org/spring-ws/sites/1.5/faq.html#saaj-jboss --> <bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"> <property name="messageFactory"> <bean class="com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl"/> </property> </bean> <web-app> <servlet> <servlet-name>spring-ws</servlet-name> <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-ws</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> <bean id="endpointMapping" class="org.apache.camel.component.spring.ws.bean.CamelEndpointMapping" /> <bean id="wsdl" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition"> <property name="schema"> <bean class="org.springframework.xml.xsd.SimpleXsdSchema"> <property name="xsd" value="/WEB-INF/foobar.xsd"/> </bean> </property> <property name="portTypeName" value="FooBar"/> <property name="locationUri" value="/"/> <property name="targetNamespace" value="http://example.com/"/> </bean> from("spring-ws:rootqname:{http://example.com/}GetFoo?endpointMapping=#endpointMapping") .convertBodyTo(String.class).to(mock:example) from("spring-ws:soapaction:http://example.com/GetFoo?endpointMapping=#endpointMapping") .convertBodyTo(String.class).to(mock:example) from("spring-ws:uri:http://example.com/foobar?endpointMapping=#endpointMapping") .convertBodyTo(String.class).to(mock:example) from("spring-ws:xpathresult:abc?expression=//foobar&endpointMapping=#endpointMapping") .convertBodyTo(String.class).to(mock:example) <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="spring-ws:beanname:QuoteEndpointDispatcher" /> <to uri="mock:example" /> </route> </camelContext> <bean id="legacyEndpointMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping"> <property name="mappings"> <props> <prop key="{http://example.com/}GetFuture">FutureEndpointDispatcher</prop> <prop key="{http://example.com/}GetQuote">QuoteEndpointDispatcher</prop> </props> </property> </bean> <bean id="QuoteEndpointDispatcher" class="org.apache.camel.component.spring.ws.bean.CamelEndpointDispatcher" /> <bean id="FutureEndpointDispatcher" class="org.apache.camel.component.spring.ws.bean.CamelEndpointDispatcher" /> JaxbDataFormat jaxb = new JaxbDataFormat(false); jaxb.setContextPath("com.example.model"); from("direct:example").marshal(jaxb).to("spring-ws:http://foo.com/bar").unmarshal(jaxb); from("spring-ws:rootqname:{http://example.com/}GetFoo?endpointMapping=#endpointMapping").unmarshal(jaxb) .to("mock:example").marshal(jaxb); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-sql-starter</artifactId> </dependency> sql:select * from table where id=# order by name[?options] sql:select * from table where id=:#myId order by name[?options] sql:select * from table where id=:#USD{exchangeProperty.myId} order by name[?options] sql:classpath:sql/myquery.sql[?options] -- this is a comment select * from table where id = :#USD{exchangeProperty.myId} order by name sql:query from("jms:order.inbox") .to("sql:select order_seq.nextval from dual?outputHeader=OrderId&outputType=SelectOne") .to("jms:order.booking"); from("direct:withSplitModel") .to("sql:select * from projects order by id?outputType=StreamList&outputClass=org.apache.camel.component.sql.ProjectModel") .to("log:stream") .split(body()).streaming() .to("log:row") .to("mock:result") .end(); sql:select * from table where id=# order by name?dataSource=#myDS from("direct:projects") .setHeader("lic", constant("ASF")) .setHeader("min", constant(123)) .to("sql:select * from projects where license = :#lic and id > :#min order by id") from("direct:projects") .to("sql:select * from projects where license = :#lic and id > :#min order by id") from("direct:projects") .setBody(constant("ASF")) .setProperty("min", constant(123)) .to("sql:select * from projects where license = :#USD{body} and id > :#USD{exchangeProperty.min} order by id") from("sql:select * from projects where id = :#USD{bean:myIdGenerator.nextId}") .to("mock:result"); public static class MyIdGenerator { private int id = 1; public int nextId() { return id++; } -- this is a comment select * from projects where project in (:#in:names) order by id from("direct:query") .to("sql:classpath:sql/selectProjectsIn.sql") .to("log:query") .to("mock:query"); // use an array template.requestBodyAndHeader("direct:query", "Hi there!", "names", new String[]{"Camel", "AMQ"}); // use a list List<String> names = new ArrayList<String>(); names.add("Camel"); names.add("AMQ"); template.requestBodyAndHeader("direct:query", "Hi there!", "names", names); // use a string separated values with comma template.requestBodyAndHeader("direct:query", "Hi there!", "names", "Camel,AMQ"); from("direct:query") .to("sql:select * from projects where project in (:#in:names) order by id") .to("log:query") .to("mock:query"); CREATE TABLE CAMEL_MESSAGEPROCESSED ( processorName VARCHAR(255), messageId VARCHAR(100) ) CREATE TABLE CAMEL_MESSAGEPROCESSED ( processorName VARCHAR(255), messageId VARCHAR(100), createdAt TIMESTAMP ) CREATE TABLE aggregation ( id varchar(255) NOT NULL, exchange blob NOT NULL, version BIGINT NOT NULL, constraint aggregation_pk PRIMARY KEY (id) ); CREATE TABLE aggregation_completed ( id varchar(255) NOT NULL, exchange blob NOT NULL, version BIGINT NOT NULL, constraint aggregation_completed_pk PRIMARY KEY (id) ); CREATE TABLE aggregationRepo3 ( id varchar(255) NOT NULL, exchange blob NOT NULL, version BIGINT NOT NULL, body varchar(1000), companyName varchar(1000), accountName varchar(1000), constraint aggregationRepo3_pk PRIMARY KEY (id) ); CREATE TABLE aggregationRepo3_completed ( id varchar(255) NOT NULL, exchange blob NOT NULL, version BIGINT NOT NULL, body varchar(1000), companyName varchar(1000), accountName varchar(1000), constraint aggregationRepo3_completed_pk PRIMARY KEY (id) ); <bean id="repo3" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"> <property name="repositoryName" value="aggregationRepo3"/> <property name="transactionManager" ref="txManager3"/> <property name="dataSource" ref="dataSource3"/> <!-- configure to store the message body and following headers as text in the repo --> <property name="storeBodyAsText" value="true"/> <property name="headersToStoreAsText"> <list> <value>companyName</value> <value>accountName</value> </list> </property> </bean> <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/> <bean id="repo" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"> <property name="transactionManager" ref="transactionManager"/> <property name="repositoryName" value="aggregation"/> <property name="dataSource" ref="dataSource"/> <!-- Only with Oracle, else use default --> <property name="lobHandler" ref="lobHandler"/> </bean> <bean id="repo" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"> <property name="transactionManager" ref="transactionManager"/> <property name="repositoryName" value="aggregation"/> <property name="dataSource" ref="dataSource"/> <property name="jdbcOptimisticLockingExceptionMapper" ref="myExceptionMapper"/> </bean> <!-- use the default mapper with extraFQN class names from our JDBC driver --> <bean id="myExceptionMapper" class="org.apache.camel.processor.aggregate.jdbc.DefaultJdbcOptimisticLockingExceptionMapper"> <property name="classNames"> <util:set> <value>com.foo.sql.MyViolationExceptoion</value> <value>com.foo.sql.MyOtherViolationExceptoion</value> </util:set> </property> </bean> <bean id="repo" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"> <property name="propagationBehaviorName" value="PROPAGATION_NESTED" /> </bean> INSERT INTO aggregation (id, exchange) values (?, ?) ON CONFLICT DO NOTHING Example for a mysql datasource spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-sql-starter</artifactId> <version>USD{camel.version}</version> <!-- use the same version as your Camel core version --> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>USD{spring-boot-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-sql-starter</artifactId> </dependency> sql-stored:template[?options] sql-stored:classpath:sql/myprocedure.sql[?options] SUBNUMBERS( INTEGER USD{headers.num1}, INTEGER USD{headers.num2}, INOUT INTEGER USD{headers.num3} out1, OUT INTEGER out2 ) sql-stored:template <to uri="sql-stored:STOREDSAMPLE(INTEGER USD{headers.num1},INTEGER USD{headers.num2},INOUT INTEGER USD{headers.num3} result1,OUT INTEGER result2)"/> CREATE PROCEDURE STOREDSAMPLE(VALUE1 INTEGER, VALUE2 INTEGER, INOUT RESULT1 INTEGER, OUT RESULT2 INTEGER) <to uri="sql-stored:MYFUNC('param1' org.example.Types.INTEGER(10) USD{header.srcValue})"/> <to uri="sql-stored:MYFUNC('param1' 100 'mytypename' USD{header.srcValue})"/> <to uri="sql-stored:MYFUNC(OUT org.example.Types.DECIMAL(10) outheader1)"/> <to uri="sql-stored:MYFUNC(OUT org.example.Types.NUMERIC(10) 'mytype' outheader1)"/> <to uri="sql-stored:MYFUNC(INOUT DECIMAL(10) USD{headers.inheader} outheader)"/> <to uri="sql-stored:MYFUNC(INOUT DECIMAL(10) USD{headers.inheader} outheader)?template.queryTimeout=5000"/> Example for a mysql datasource spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-sql-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>USD{spring-boot-version}</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-ssh-starter</artifactId> </dependency> ssh:[username[:password]@]host[:port][?options] ssh:host:port <route id="camel-example-ssh-producer"> <from uri="direct:exampleSshProducer"/> <setBody> <constant>features:list&#10;</constant> </setBody> <to uri="ssh://karaf:karaf@localhost:8101"/> <log message="USD{body}"/> </route> <route> <from uri="ssh://scott@localhost:8101?certResource=classpath:test_rsa&amp;useFixedDelay=true&amp;delay=5000&amp;pollCommand=features:list%0A"/> <log message="USD{body}"/> </route> from("ssh://scott@localhost:8101?certResource=classpath:test_rsa&useFixedDelay=true&delay=5000&pollCommand=features:list%0A") .log("USD{body}"); <dependency> <groupId>org.apache.sshd</groupId> <artifactId>sshd-core</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpg-jdk18on</artifactId> <version>1.71</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk18on</artifactId> <version>1.71</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-stub-starter</artifactId> </dependency> stub:someUri stub:name stub:smtp://somehost.foo.com?user=whatnot&something=else stub:http://somehost.bar.com/something <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-telegram-starter</artifactId> </dependency> telegram:type[?options] telegram:type from("direct:start").to("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"); <route> <from uri="direct:start"/> <to uri="telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"/> <route> from("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere") .bean(ProcessorBean.class) <route> <from uri="telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"/> <bean ref="myBean" /> <route> <bean id="myBean" class="com.example.MyBean"/> public class MyBean { public void process(String message) { // or Exchange, or org.apache.camel.component.telegram.model.IncomingMessage (or both) // do process } } from("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere") .bean(ChatBotLogic.class) .to("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"); <route> <from uri="telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"/> <bean ref="chatBotLogic" /> <to uri="telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"/> <route> <bean id="chatBotLogic" class="com.example.ChatBotLogic"/> public class ChatBotLogic { public String chatBotProcess(String message) { if( "do-not-reply".equals(message) ) { return null; // no response in the chat } return "echo from the bot: " + message; // echoes the message } } from("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere") .to("log:INFO?showHeaders=true"); from("timer:tick") .setBody().constant("Hello") to("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere&chatId=123456") from("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere") .process(exchange -> { OutgoingTextMessage msg = new OutgoingTextMessage(); msg.setText("Choose one option!"); InlineKeyboardButton buttonOptionOneI = InlineKeyboardButton.builder() .text("Option One - I").build(); InlineKeyboardButton buttonOptionOneII = InlineKeyboardButton.builder() .text("Option One - II").build(); InlineKeyboardButton buttonOptionTwoI = InlineKeyboardButton.builder() .text("Option Two - I").build(); ReplyKeyboardMarkup replyMarkup = ReplyKeyboardMarkup.builder() .keyboard() .addRow(Arrays.asList(buttonOptionOneI, buttonOptionOneII)) .addRow(Arrays.asList(buttonOptionTwoI)) .close() .oneTimeKeyboard(true) .build(); msg.setReplyMarkup(replyMarkup); exchange.getIn().setBody(msg); }) .to("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"); from("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere") .process(exchange -> { OutgoingTextMessage msg = new OutgoingTextMessage(); msg.setText("Your answer was accepted!"); ReplyKeyboardMarkup replyMarkup = ReplyKeyboardMarkup.builder() .removeKeyboard(true) .build(); msg.setReplyKeyboardMarkup(replyMarkup); exchange.getIn().setBody(msg); }) .to("telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere"); <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-netty-http</artifactId> <version>{CamelSBVersion}</version> <!-- use the same version as your Camel core version --> </dependency> from("webhook:telegram:bots?authorizationToken=123456789:insertYourAuthorizationTokenHere").to("log:info"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-timer-starter</artifactId> </dependency> timer:name[?options] timer:timerName from("timer://foo?fixedRate=true&period=60000").to("bean:myBean?method=someMethodName"); <route> <from uri="timer://foo?fixedRate=true&amp;period=60000"/> <to uri="bean:myBean?method=someMethodName"/> </route> <route> <from uri="timer://foo?delay=-1"/> <to uri="bean:myBean?method=someMethodName"/> </route> <route> <from uri="timer://foo?repeatCount=1"/> <to uri="bean:myBean?method=someMethodName"/> </route> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency> <route> <from uri="direct:a"/> <split> <tokenize token="\n"/> <to uri="direct:b"/> </split> </route> from("direct:a") .split(body().tokenize("\n")) .to("direct:b"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-validator-starter</artifactId> </dependency> validator:someLocalOrRemoteResource validator:resourceUri <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-velocity-starter</artifactId> </dependency> velocity:templateName[?options] velocity:resourceUri USDin.setHeader("fruit", "Apple") VelocityContext velocityContext = new VelocityContext(variableMap); exchange.getIn().setHeader("CamelVelocityContext", velocityContext); from("activemq:My.Queue"). to("velocity:com/acme/MyResponse.vm"); from("activemq:My.Queue"). to("velocity:com/acme/MyResponse.vm"). to("activemq:Another.Queue"); from("activemq:My.Queue"). to("velocity:com/acme/MyResponse.vm?contentCache=true"). to("activemq:Another.Queue"); from("activemq:My.Queue"). to("velocity:file://myfolder/MyResponse.vm?contentCache=true"). to("activemq:Another.Queue"); from("direct:in"). setHeader("CamelVelocityResourceUri").constant("path/to/my/template.vm"). to("velocity:dummy?allowTemplateFromHeader=true""); from("direct:in"). setHeader("CamelVelocityTemplate").constant("Hi this is a velocity template that can do templating USD{body}"). to("velocity:dummy?allowTemplateFromHeader=true""); Dear USD{headers.lastName}, USD{headers.firstName} Thanks for the order of USD{headers.item}. Regards Camel Riders Bookstore USD{body} private Exchange createLetter() { Exchange exchange = context.getEndpoint("direct:a").createExchange(); Message msg = exchange.getIn(); msg.setHeader("firstName", "Claus"); msg.setHeader("lastName", "Ibsen"); msg.setHeader("item", "Camel in Action"); msg.setBody("PS: Next beer is on me, James"); return exchange; } @Test public void testVelocityLetter() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).body(String.class).contains("Thanks for the order of Camel in Action"); template.send("direct:a", createLetter()); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:a") .to("velocity:org/apache/camel/component/velocity/letter.vm") .to("mock:result"); } }; } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-vertx-http-starter</artifactId> </dependency> vertx-http:hostname[:port][/resourceUri][?options] vertx-http:httpUri from("direct:start") .to("vertx-http:https://camel.apache.org"); WebClientOptions options = new WebClientOptions().setMaxRedirects(5) .setIdleTimeout(10) .setConnectTimeout(3); camelContext.getRegistry.bind("clientOptions", options); from("direct:start") .to("vertx-http:http://localhost:8080?webClientOptions=#clientOptions") <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-vertx-websocket-starter</artifactId> </dependency> vertx-websocket://hostname[:port][/resourceUri][?options] vertx-websocket:host:port/path from("vertx-websocket:localhost:8080/echo") .transform().simple("Echo: USD{body}") .to("vertx-websocket:localhost:8080/echo"); from("vertx-websocket:my.websocket.com:8080/chat?consumeAsClient=true") .log("Got WebSocket message USD{body}"); from("vertx-websocket:localhost:8080/chat/{user}") .log("New message from USD{header.user} >>> USD{body}") from("direct:sendChatMessage") .to("vertx-websocket:localhost:8080/chat/camel?role=admin"); from("vertx-websocket:localhost:8080/chat/{user}") .log("New message from USD{header.user} (USD{header.role}) >>> USD{body}") from("vertx-websocket:localhost:8080/chat") .log("Got WebSocket message USD{body}"); from("direct:broadcastMessage") .setBody().constant("This is a broadcast message!") .to("vertx-websocket:localhost:8080/chat?sendToAll=true"); from("vertx-websocket:localhost:8080/chat") .log("Got WebSocket message USD{body}"); from("direct:broadcastMessage") .setBody().constant("This is a broadcast message!") .setHeader(VertxWebsocketConstants.CONNECTION_KEY).constant("key-1,key-2,key-3") .to("vertx-websocket:localhost:8080/chat"); <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-webhook-starter</artifactId> </dependency> webhook:endpoint[?options] webhook:endpointUri <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-xj-starter</artifactId> </dependency> xj:templateName?transformDirection=XML2JSON|JSON2XML[&options] xj:resourceUri from("direct:start"). to("xj:identity?transformDirection=JSON2XML"); { "firstname": "camel", "lastname": "apache", "personalnumber": 42, "active": true, "ranking": 3.1415926, "roles": [ "a", { "x": null } ], "state": { "needsWater": true } } <?xml version="1.0" encoding="UTF-8"?> <object xmlns:xj="http://camel.apache.org/component/xj" xj:type="object"> <object xj:name="firstname" xj:type="string">camel</object> <object xj:name="lastname" xj:type="string">apache</object> <object xj:name="personalnumber" xj:type="int">42</object> <object xj:name="active" xj:type="boolean">true</object> <object xj:name="ranking" xj:type="float">3.1415926</object> <object xj:name="roles" xj:type="array"> <object xj:type="string">a</object> <object xj:type="object"> <object xj:name="x" xj:type="null">null</object> </object> </object> <object xj:name="state" xj:type="object"> <object xj:name="needsWater" xj:type="boolean">true</object> </object> </object> <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xj="http://camel.apache.org/component/xj" exclude-result-prefixes="xj"> <xsl:output omit-xml-declaration="no" encoding="UTF-8" method="xml" indent="yes"/> <xsl:template match="/"> <person> <xsl:apply-templates select="//object"/> </person> </xsl:template> <xsl:template match="object[@xj:type != 'object' and @xj:type != 'array' and string-length(@xj:name) > 0]"> <xsl:variable name="name" select="@xj:name"/> <xsl:element name="{USDname}"> <xsl:value-of select="text()"/> </xsl:element> </xsl:template> <xsl:template match="@*|node()"/> </xsl:stylesheet> from("direct:start"). to("xj:com/example/json2xml.xsl?transformDirection=JSON2XML"); <?xml version="1.0" encoding="UTF-8"?> <person> <firstname>camel</firstname> <lastname>apache</lastname> <personalnumber>42</personalnumber> <active>true</active> <ranking>3.1415926</ranking> <x>null</x> <needsWater>true</needsWater> </person> from("direct:start"). to("xj:identity?transformDirection=XML2JSON"); <?xml version="1.0" encoding="UTF-8"?> <person> <firstname>camel</firstname> <lastname>apache</lastname> <personalnumber>42</personalnumber> <active>true</active> <ranking>3.1415926</ranking> <roles> <entry>a</entry> <entry> <x>null</x> </entry> </roles> <state> <needsWater>true</needsWater> </state> </person> { "firstname": "camel", "lastname": "apache", "personalnumber": "42", "active": "true", "ranking": "3.1415926", "roles": [ "a", { "x": "null" } ], "state": { "needsWater": "true" } } <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xj="http://camel.apache.org/component/xj" exclude-result-prefixes="xj"> <xsl:output omit-xml-declaration="no" encoding="UTF-8" method="xml" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="personalnumber"> <xsl:element name="{local-name()}"> <xsl:attribute name="xj:type"> <xsl:value-of select="'int'"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="active|needsWater"> <xsl:element name="{local-name()}"> <xsl:attribute name="xj:type"> <xsl:value-of select="'boolean'"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="ranking"> <xsl:element name="{local-name()}"> <xsl:attribute name="xj:type"> <xsl:value-of select="'float'"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="roles"> <xsl:element name="{local-name()}"> <xsl:attribute name="xj:type"> <xsl:value-of select="'array'"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="*[normalize-space(text()) = 'null']"> <xsl:element name="{local-name()}"> <xsl:attribute name="xj:type"> <xsl:value-of select="'null'"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> from("direct:start"). to("xj:com/example/xml2json.xsl?transformDirection=XML2JSON"); { "firstname": "camel", "lastname": "apache", "personalnumber": 42, "active": true, "ranking": 3.1415926, "roles": [ "a", { "x": null } ], "state": { "needsWater": true } } <?xml version="1.0" encoding="UTF-8"?> <person> <firstname>camel</firstname> <lastname>apache</lastname> <personalnumber xmlns:xj="http://camel.apache.org/component/xj" xj:type="int">42</personalnumber> <active xmlns:xj="http://camel.apache.org/component/xj" xj:type="boolean">true</active> <ranking xmlns:xj="http://camel.apache.org/component/xj" xj:type="float">3.1415926</ranking> <roles xmlns:xj="http://camel.apache.org/component/xj" xj:type="array"> <entry>a</entry> <entry> <x xj:type="null">null</x> </entry> </roles> <state> <needsWater xmlns:xj="http://camel.apache.org/component/xj" xj:type="boolean">true</needsWater> </state> </person> <?xml version="1.0" encoding="UTF-8"?> <object xmlns:xj="http://camel.apache.org/component/xj" xj:type="object"> <object xj:name="firstname" xj:type="string">camel</object> <object xj:name="lastname" xj:type="string">apache</object> <object xj:name="personalnumber" xj:type="int">42</object> <object xj:name="active" xj:type="boolean">true</object> <object xj:name="ranking" xj:type="float">3.1415926</object> <object xj:name="roles" xj:type="array"> <object xj:type="string">a</object> <object xj:type="object"> <object xj:name="x" xj:type="null">null</object> </object> </object> <object xj:name="state" xj:type="object"> <object xj:name="needsWater" xj:type="boolean">true</object> </object> </object> { "firstname": "camel", "lastname": "apache", "personalnumber": 42, "active": true, "ranking": 3.1415926, "roles": [ "a", { "x": null } ], "state": { "needsWater": true } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-xml-jaxp-starter</artifactId> </dependency> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>4.4.1</version> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-stax-starter</artifactId> </dependency> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-xpath-starter</artifactId> </dependency> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring" xmlns:foo="http://example.com/person"> <route> <from uri="activemq:MyQueue"/> <filter> <xpath>/foo:person[@name='James']</xpath> <to uri="mqseries:SomeOtherQueue"/> </filter> </route> </camelContext> </beans> from("queue:foo"). filter().xpath("//foo")). to("queue:bar") from("queue:foo"). choice().xpath("//foo")).to("queue:bar"). otherwise().to("queue:others"); xpath("/foo:person/@id", String.class) <xpath resultType="java.lang.String">/foo:person/@id</xpath> @XPath(value = "concat('foo-',//order/name/)", resultType = String.class) String name) <xpath headerName="invoiceDetails">/invoice/@orderType = 'premium'</xpath> xpath("/invoice/@orderType = 'premium'", "invoiceDetails") from("direct:start") .filter().xpath("/person[@name='James']") .to("mock:result"); <route> <from uri="direct:start"/> <filter> <xpath>/person[@name='James']</xpath> <to uri="mock:result"/> </filter> </route> Namespaces ns = new Namespaces("c", "http://acme.com/cheese"); from("direct:start") .filter(xpath("/c:person[@name='James']", ns)) .to("mock:result"); /c:person[@name='James'] Namespaces ns = new Namespaces("c", "http://acme.com/cheese") .add("w", "http://acme.com/wine") .add("b", "http://acme.com/beer"); <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:foo="http://example.com/person" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd "> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:start"/> <filter> <xpath logNamespaces="true">/foo:person[@name='James']</xpath> <to uri="mock:result"/> </filter> </route> </camelContext> </beans> public class Foo { @Consume(uri = "activemq:my.queue") public void doSomething(@XPath("/person/@name") String name, String xml) { // process the inbound message here } } boolean matches = XPathBuilder.xpath("/foo/bar/@xyz").matches(context, "<foo><bar xyz='cheese'/></foo>")); String name = XPathBuilder.xpath("foo/bar").evaluate(context, "<foo><bar>cheese</bar></foo>", String.class); Integer number = XPathBuilder.xpath("foo/bar").evaluate(context, "<foo><bar>123</bar></foo>", Integer.class); Boolean bool = XPathBuilder.xpath("foo/bar").evaluate(context, "<foo><bar>true</bar></foo>", Boolean.class); String name = XPathBuilder.xpath("foo/bar").evaluate(context, "<foo><bar>cheese</bar></foo>"); XPathBuilder INFO Using system property javax.xml.xpath.XPathFactory:http://saxon.sf.net/jaxp/xpath/om with value: net.sf.saxon.xpath.XPathFactoryImpl when creating XPathFactory -Djavax.xml.xpath.XPathFactory=org.apache.xpath.jaxp.XPathFactoryImpl <xpath factoryRef="saxonFactory" resultType="java.lang.String">current-dateTime()</xpath> <bean id="saxonFactory" class="net.sf.saxon.xpath.XPathFactoryImpl"/> <xpath objectModel="http://saxon.sf.net/jaxp/xpath/om" resultType="java.lang.String">current-dateTime()</xpath> <xpath saxon="true" resultType="java.lang.String">current-dateTime()</xpath> [me: {prefix -> namespace}, {prefix -> namespace}], [parent: [me: {prefix -> namespace}, {prefix -> namespace}], [parent: [me: {prefix -> namespace}]]] XPathBuilder.xpath("/foo:person/@id", String.class).logNamespaces() <xpath logNamespaces="true" resultType="String">/foo:person/@id</xpath> 2012-01-16 13:23:45,878 [stSaxonWithFlag] INFO XPathBuilder - Namespaces discovered in message: {xmlns:a=[http://apache.org/camel], DEFAULT=[http://apache.org/default], xmlns:b=[http://apache.org/camelA, http://apache.org/camelB]} .setHeader("myHeader").xpath("resource:classpath:myxpath.txt", String.class) <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-xslt-starter</artifactId> </dependency> xslt:templateName[?options] xslt:resourceUri from("activemq:My.Queue"). to("xslt:com/acme/mytransform.xsl"); from("activemq:My.Queue"). to("xslt:com/acme/mytransform.xsl"). to("activemq:Another.Queue"); <setHeader name="myParam"><constant>42</constant></setHeader> <to uri="xslt:MyTransform.xsl"/> <xsl: ...... > <xsl:param name="myParam"/> <xsl:template ...> <camelContext xmlns="http://activemq.apache.org/camel/schema/spring"> <route> <from uri="activemq:My.Queue"/> <to uri="xslt:org/apache/camel/spring/processor/example.xsl"/> <to uri="activemq:Another.Queue"/> </route> </camelContext> <xsl:include href="staff_template.xsl"/> <xsl:include href="../staff_other_template.xsl"/> <xsl:template match="/"> <html> <body> <xsl:for-each select="staff/programmer"> <p>Name: <xsl:value-of select="name"/><br /> <xsl:if test="dob=''"> <xsl:message terminate="yes">Error: DOB is an empty string!</xsl:message> </xsl:if> </p> </xsl:for-each> </body> </html> </xsl:template> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-xslt-saxon-starter</artifactId> </dependency> xslt-saxon:templateName[?options] ?option=value&option=value&... xslt-saxon:resourceUri from("activemq:My.Queue"). to("xslt-saxon:com/acme/mytransform.xsl"); from("activemq:My.Queue"). to("xslt-saxon:com/acme/mytransform.xsl"). to("activemq:Another.Queue"); <setHeader name="myParam"><constant>42</constant></setHeader> <to uri="xslt:MyTransform.xsl"/> <xsl: ...... > <xsl:param name="myParam"/> <xsl:template ...> <camelContext xmlns="http://activemq.apache.org/camel/schema/spring"> <route> <from uri="activemq:My.Queue"/> <to uri="xslt-saxon:org/apache/camel/spring/processor/example.xsl"/> <to uri="activemq:Another.Queue"/> </route> </camelContext> <xsl:include href="staff_template.xsl"/> <xsl:include href="../staff_other_template.xsl"/> SimpleRegistry registry = new SimpleRegistry(); registry.put("function1", new MyExtensionFunction1()); registry.put("function2", new MyExtensionFunction2()); CamelContext context = new DefaultCamelContext(registry); context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .to("xslt-saxon:org/apache/camel/component/xslt/extensions/extensions.xslt?saxonExtensionFunctions=#function1,#function2"); } }); <bean id="function1" class="org.apache.camel.component.xslt.extensions.MyExtensionFunction1"/> <bean id="function2" class="org.apache.camel.component.xslt.extensions.MyExtensionFunction2"/> <camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:extensions"/> <to uri="xslt-saxon:org/apache/camel/component/xslt/extensions/extensions.xslt?saxonExtensionFunctions=#function1,#function2"/> </route> </camelContext> <xsl:template match="/"> <html> <body> <xsl:for-each select="staff/programmer"> <p>Name: <xsl:value-of select="name"/><br /> <xsl:if test="dob=''"> <xsl:message terminate="yes">Error: DOB is an empty string!</xsl:message> </xsl:if> </p> </xsl:for-each> </body> </html> </xsl:template> - from: 1 uri: "direct:start" steps: 2 - filter: expression: simple: "USD{in.header.continue} == true" steps: - to: uri: "log:filtered" - to: uri: "log:original" filter: expression: simple: "USD{in.header.continue} == true" steps: - to: uri: "log:filtered" filter: expression: simple: "USD{in.header.continue} == true" filter: simple: "USD{in.header.continue} == true" filter: tokenize: token: "<" end-token: ">" marshal: json: library: Gson - from: uri: "timer:tick?period=1s" steps: - to: uri: "telegram:bots?authorizationToken=XXX" - from: uri: "timer://tick" parameters: period: "1s" steps: - to: uri: "telegram:bots" parameters: authorizationToken: "XXX" - beans: - name: beanFromMap 1 type: com.acme.MyBean 2 properties: 3 foo: bar - beans: # map style - name: beanFromMap type: com.acme.MyBean properties: field1: 'f1' field2: 'f2' nested: field1: 'nf1' field2: 'nf2' # properties style - name: beanFromProps type: com.acme.MyBean properties: field1: 'f1_p' field2: 'f2_p' nested.field1: 'nf1_p' nested.field2: 'nf2_p' - from: uri: "direct:start" steps: - choice: when: - jsonpath: expression: "person.middlename" suppress-exceptions: true steps: - to: "mock:middle" - jsonpath: expression: "person.lastname" suppress-exceptions: true steps: - to: "mock:last" otherwise: steps: - to: "mock:other" { "person": { "firstname": "John", "lastname": "Doe" } } <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-zipfile-starter</artifactId> </dependency> from("direct:start") .marshal().zipFile() .to("activemq:queue:MY_QUEUE"); from("file:input/directory?antInclude=*/.txt") .marshal().zipFile() .to("file:output/directory"); from("direct:start") .setHeader(Exchange.FILE_NAME, constant("report.txt")) .marshal().zipFile() .to("file:output/directory"); from("activemq:queue:MY_QUEUE") .unmarshal().zipFile() .process(new UnZippedMessageProcessor()); ZipFileDataFormat zipFile = new ZipFileDataFormat(); zipFile.setUsingIterator(true); from("file:src/test/resources/org/apache/camel/dataformat/zipfile/?delay=1000&noop=true") .unmarshal(zipFile) .split(body(Iterator.class)).streaming() .process(new UnZippedMessageProcessor()) .end(); from("file:src/test/resources/org/apache/camel/dataformat/zipfile?delay=1000&noop=true") .split(new ZipSplitter()).streaming() .process(new UnZippedMessageProcessor()) .end(); from("file:input/directory?antInclude=*/.txt") .aggregate(constant(true), new ZipAggregationStrategy()) .completionFromBatchConsumer().eagerCheckCompletion() .to("file:output/directory"); from("file:input/directory?antInclude=*/.txt") .aggregate(constant(true), new ZipAggregationStrategy()) .completionFromBatchConsumer().eagerCheckCompletion() .setHeader(Exchange.FILE_NAME, constant("reports.zip")) .to("file:output/directory");